Oracle Notes-Sathya
Oracle Notes-Sathya
Oracle Trainer
ORACLE
ORACLE is a database, and also known as RELATIONAL DATA BASE
MANAGEMENT SYSTEM (RDBMS)
RDBMS is a software and it is useful store data, manage data and to automate
business activities.
Ex of RDBMS:
Oracle
Microsoft SQL SERVER
IBM DB2. . . . etc
DATA:
Data is defined as a collection of raw facts.
Information:
Processed data is known as information.
DATA BASE:
It is a software which stores and manages the collection of information of all objects
in the business.
It is a collection of programs and each program is specific for performing a task.
DATABASE MANAGEMENT SYSTEM:
DB which is along with data management system services is known as DBMS.
RDBMS:
It is a Collection of information of all related objects with in the business is known as
RDBMS.
Author of RDBMS is E.F. CODD.
Data is stored in the form of Tables.
A Table is a collection of Rows and Columns.
A Row is known as Record (collection of columns)
A Column is known as a Field.
SQL (Structured Query Language)
Definition:
It is a collection of predefined commands, key words, and syntax rules. It is used to
communicate with any database. 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
DINESH PV
Oracle Trainer
SQL*PLUS
SQL * PLUS is a client application and it is an interface between client user
and database. In this window we can write queries and programs.
How to open SQL*PLUS window?
STARTProgramsOracleSQL PLUS
How to connect to Oracle database?
Open SQL*PLUS
Type as follows
Connect username/password [ Enter ]
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.
I) Character data
It contains alphabets, digits and symbols.
CHAR (size)
It is useful to store fixed length character values. By default the size is 1 character,
and max size is 2000 chars or bytes.
DINESH PV
Oracle Trainer
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
DINESH PV
Oracle Trainer
It is a pointer to the external file, that is saved on the disk. We can read data from
external file and write data on to the external file through BFILE.
INSERTING RECORDS INTO A TABLE
INSERT
It is used to insert new records in to a table.
syntax:
INSERT INTO <Tbl> [(col1, col2,. . . coln)] VALUES(val1, val2, . . . . ,val-n);
Character and date type values should be enclosed in single quotes.
Ex:
Create table empinfo
(
Eid number(4),
Ename varchar2(20),
Sal number(5),
Jdate date,
Desg varchar2(20),
Gender char
);
insert into empinfo(eid,ename,sal,jdate,desg,gender)
values(1111,'dinesh',75000,'23-may-14','developer','M');
insert into empinfo values(1110,'john',11700,'23-may-14','developer','M');
insert into empinfo values('mahitha',23000,'developer','F');
Error: Not enough values
insert into empinfo (ename,sal,desg,gender) values('mahitha',23000,'developer','F');
insert into empinfo values(null,'smitha',33000,null,'developer','F');
insert into empinfo (ename,sal) values('dinesh','75000');
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?
DINESH PV
Oracle Trainer
developer
clerk
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
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
select ename, sal,job from emp order by 2;
sample output:
ENAME SAL JOB
SMITH 800 CLERK
JAMES 950 CLERK
ADAMS 1100 CLERK
WARD 1250 SALESMAN
MARTIN 1250 SALESMAN
OPERATORS
Arithmetic Operators:
+ - * /
DINESH PV
Oracle Trainer
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?
select sal "Basic Sal", (0.02*sal) "TA" from emp;
Ex:
select pname, price, (0.25*price) Discount, price-(0.25*price) "final price"
from prod_dtls;
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?
DINESH PV
Oracle Trainer
SPECIAL OPERATORS
BETWEEN NOT BETWEEN
IN NOT IN
IS NULL IS NOT NULL
LIKE NOT LIKE
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.
DINESH PV
Oracle Trainer
DML COMMANDS
UPDATE
By using update command, We can change old values with new values in the table.
By default, it updates all values in the column without where clause.
syntax
UPDATE <tbl> SET col1 = value, col2 = value, . . .
where <cond>;
Ex: update the commission of 7369 as 500?
update emp set comm=500 where empno=7369;
Ex: update all emps commissions as 1000?
update emp set comm=1000;
Ex: update the salesman salary with 20% increment , change their designition as
Sr.SALES ?
update emp set sal=sal+(0.20*sal), job='Sr.SALES' where job='SALESMAN';
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;
Ex: delete employees information who is not getting any commission?
delete from emp where comm is null;
TRANSACTION CONTROL LANGUAGE COMMANDS
Generally, DML operations on table data are considered as transactions.
To make transactions as permanent or cancel the transactions , we will use these
commands.
COMMIT
It is used to make transactions as permanent. Once committed, we cannot cancel
these transactions.
DINESH PV
Oracle Trainer
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;
select * from cust;
rollback;
select * from cust;
Ex-2
Insert into cust values('c02','hellen');
delete from cust where cname='Sanju';
savepoint s1;
update cust set cid='c99' where cname='hellen';
savepoint s2;
delete from cust;
select * from cust;
rollback to s2; [ It will cancel transactions after "S2"]
DDL COMMANDS
CREATE ALTER DROP
RENAME TRUNCATE
ALTER
It is used to change the structure of the table by doing the following
We can add new columns, delete old columns, change column name, change table
name and change column data type and size.
ADDING COLUMNS
Alter Table <table_name> ADD
( <col_1> datatype(size), <col_2> datatype(size), ----- ----- );
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;
Ex: drop user dinesh;
RENAME
It is used to change name of oracle table.
syntax: RENAME <Old TableName> TO <New TableName>;
Ex: change the table name "customers" as "custinfo"?
RENAME customers TO custinfo;
TRUNCATE
It is useful to delete all the records permanently from the table.
syn: truncate table <table_name>;
Ex: truncate table custinfo ;
Note:
In the above table the marked values are invalid according to business of client.
How to avoid / restrict invalid values into business database?
We can define constraints on the tables before data to be inserted into the table.
Constraints are divided into 3 categories.
1) Key Constraints
2) Domain Constraints
3) Referential Integrity constraints / Ref Constraints
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,
DINESH PV
Oracle Trainer
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.
Example columns : bank account numbers, empid, regnumbers... etc.
Primary keys are 2 types.
simple primary key [SPK]
It is defined on single column.
composite primary key [CPK]
It is defined on more than one column.
( max number of columns in to CPK are 32)
SYN:-1 Creating table with key constraints:
create table <table_name>
(
col1 datatype(size) <constraint_name>,
col2 datatype(size) <constraint_name>,
---- ----- ----
---- ----- ----
);
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)
How to get constraints from a table
Use the table USER_CONSTRAINTS
Ex:
select constraint_name, constraint_type from USER_CONSTRAINTS
where table_name='STUDENT';
CONSTRAINT_NAME CONSTRAINT_TYPE
SYS_C007050 C -either Not null or Check
SYS_C007051 P --Primary key
DINESH PV
Oracle Trainer
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 Maximum data duplicity is
reduced is known as normalization process.
Ist NF(normal form)
Dividing big table into sub tables based on repeated groups of data.
IInd NF: Eleminate duplicate records and defining primary keys in the above tables
DINESH PV
Oracle Trainer
Advantages:
No communication gap.
Duplicity is reduced
Occupy less disk space.
Data search time is reduced.
REFERENCES
DINESH PV
Oracle Trainer
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
create table comp_dtls
(
cmpid char(5)
constraint pk_cmpid_cmp primary key,
cmpname varchar2(20) not null,
Country varchar2(20) not null
);
create table prod_dtls
(
pid char(4) primary key,
pname varchar2(20) not null,
cost number(7,2),
mfg date,
warrenty varchar2(10),
cmpid char(5),
constraint fk_cmpid_prod FOREIGN KEY(cmpid)
REFERENCES COMP_DTLS(cmpid) );
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.
SYNTAX
col datatype(size) DEFAULT 'value'
DINESH PV
Oracle Trainer
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’);
Select * from customers;
11 krish DELHI
22 raj DELHI
33 john DELHI
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:
CREATE SEQUENCE <seq_name>
START WITH <val>;
By default , sequence value start with 1 and increment by 1
PSEUDO COLUMNS of sequence
The following are virtual columns associated with any sequence.
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;
11112
Ex: select custid.currval from dual;
11112
DINESH PV
Oracle Trainer
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.
DINESH PV
Oracle Trainer
SYNTAX
SELECT . . . . . FROM T1
MINUS
SELECT . . . . . FROM T2
MINUS
-----;
Sample Tables:
CREATE TABLE CUST_BR1
(
CID CHAR(3),
CNAME VARCHAR2(20),
MOBILE NUMBER(10),
CITY VARCHAR2(20),
GENDER VARCHAR2(10)
);
INSERT INTO CUST_BR1 VALUES('C1','VIJAY',9800198001,'HYD','MALE');
INSERT INTO CUST_BR1 VALUES('C2','JOHN',9800298002,'DELHI','MALE');
INSERT INTO CUST_BR1 VALUES('C3','SWATHI',9877987700,'HYD','FEMALE');
CREATE TABLE CUST_BR2
(
CID CHAR(3),
CNAME VARCHAR2(20),
MOBILE NUMBER(10),
CITY VARCHAR2(20),
GENDER VARCHAR2(10)
);
INSERT INTO CUST_BR2 VALUES('C1','KIRAN',9898989898,'HYD','MALE');
INSERT INTO CUST_BR2 VALUES('C2','JOHN',9800298002,'DELHI','MALE');
INSERT INTO CUST_BR2 ALUES('C3','LAKSHMI',8989898989,'DELHI','FEMALE');
CREATE TABLE CUST_BR3
(
CID CHAR(3),
CNAME VARCHAR2(20),
MOBILE NUMBER(10),
CITY VARCHAR2(20),
GENDER VARCHAR2(10)
);
INSERT INTO CUST_BR3 VALUES('C1','KIRAN',9898989898,'HYD','MALE');
INSERT INTO CUST_BR3 VALUES('C2','JOHN',9800298002,'DELHI','MALE');
INSERT INTO CUST_BR3 VALUES('C5','VINAY',7878787878,'DELHI','MALE');
Examples:
Get all female customers from br1 and b3?
select * from cust_br1 where gender='f'
union all
select * from cust_br3 where gender='f';
get all common customer names and mobile numbers from all branches?
DINESH PV
Oracle Trainer
PSEUDO COLUMNS
These are 2 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 beginning of the table.
Ex: select * from emp where rownum<=5;
2) ROWID
It maintains physical address of each record. By using this value, oracle engine
identify any record in the database server.
DINESH PV
Oracle Trainer
JOINS
Joins are useful to display data from multiple related tables.
Types of joins: 4
i) CROSS JOIN or CARTESIAN PRODUCT
ii) EQUI JOIN / INNER JOIN
iii) SELF JOIN
iv) OUTER JOINS
Left Outer Join
Right Outer Join
Full Outer Join
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 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.
DINESH PV
Oracle Trainer
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.
syntax:
select alias2.* from TBL alias1, TBL alias2
where alias-1.col='value' and alias1.col=alias2.col;
employee
ename city
kiran mumbai
hari hyd
madhu hyd
smith delhi
scott mumbai
allen hyd
soumya mumbai
john delhi
OUTER JOINS
Outer joins will display all the data from one table and only matched data from other
table.
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
Display products information along with company information
/* EQUI JOIN */
SELECT P.*,C.* FROM PROD_DTLS P, COMP_DTLS C
WHERE P.PROD_COMP_ID=C.COMP_ID;
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.
TYPES OF SUBQUERIES:
DINESH PV
Oracle Trainer
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
2) Composite or read-only or Join view
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?
ex: connect as dba in oracle 11g
DINESH PV
Oracle Trainer
Where p.cmpid=c.cmpid;
INDEXES
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);
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()
NUMERIC FUNCTIONS [ GROUP Category]
These functions are executing on columns only.
SUM(col) , AVG(col), MAX(col), MIN(col), COUNT(col), COUNT(*)
i) SUM(colname)
It will display addition of values from given column.
Ex: display addition of all salaries?
select sum(sal) from emp;
ii) AVG(colname)
It will display average value from given column.
Ex: display average product cost?
select avg(cost) from prod_dtls;
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)
It will Display least value from the given column.
Ex: Find out least cost among all laptops?
select min(cost) from prod_dtls where prod_name='LAPTOP';
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:
DINESH PV
Oracle Trainer
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
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;
1)ABS(-n) [ ABSOLUTE ]
It will convert given negative value as positive value.
Ex: select abs(-9) from dual;
9
2) MOD(m,n) [MODULUS]
It will display remainder value after m devided by n.
Ex: select mod(17,3) from dual;
2
3)POWER(m,n)
It will display "m" to the power of "n"th value.
Ex: select power(5,4) from dual;
625
4) SQRT(n) [ Square Root ]
It will display square root value of "n".
Ex: select sqrt(625) from dual;
25
5)ROUND(m,n)
It will Display value "m" which is rounded to the "n" number of places.
If "n" is positive, then given value is rounded in decimal part.
If "n" is negative, then given value is rounded in integer part.
Before displaying "nth" digit ,round() will check " n+1"th digit, if it is >= 5 then
"n"th digit increment by 1.
Syntax SELECT ROUND(M,N) FROM DUAL;
Ex:
select round(2519.8235621,2) from dual;
6) TRUNC(m,n)
Display value "m" which is truncated to the n number of decimal places.It will never
check any "n+1" digit and never make any increments.
Ex: select trunc(63.354,1) from dual;
63.3
Ex: select trunc(69.554) from dual;
DINESH PV
Oracle Trainer
69
7) FLOOR(n)
It will display highest integer below or equal to given value.
Ex: select floor(64.2) from dual;
64
8) CEIL(n)
It will display least integer above or equal to given value.
Ex: select ceil(64.2) from dual;
9) LEAST(val1,val2,....)
It will display minimum value from the given values and expression results. And also,
least value from each record of given columns.
EX: select least(32,(6*5), (20-10), (36/2)) from dual;
10
10) GREATEST (val1, val2, ....)
It will display highest value from given values, expressions and columns. And also,
highest value from each record of given columns.
Ex: select greatest (32,(6*5), (20-10), (36/2)) from dual;
32
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
DINESH PV
Oracle Trainer
(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');
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)
DINESH PV
Oracle Trainer
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.
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;
7)LAST_DAY(d)
DINESH PV
Oracle Trainer
100700.00 01,00,700.00
1223501.01 12,23,501.01
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
DINESH PV
Oracle Trainer
from emp;
Ex: Write a query to find nth highest salary?
SELECT DISTINCT SALARY FROM
(SELECT SALARY, DENSE_RANK() OVER(ORDER BY SALARY DESC) AS DRK
FROM EMP )
WHERE DRK=n
Note: In the above example , substitute any one digit like 1,2,3,. . .
Ex: How to delete duplicate records from a table?
Delete from emp
Where rowid not in(select max(rowid) from emp group by empid, ename,
salary);
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>;
DINESH PV
Oracle Trainer
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
select col1, col2, ....,coln INTO var_1, var_2,....var-n from tablename
where <condition>;
Note:
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.
Ex: write a program to display welcome message .
begin
dbms_output.put_line('welcome to oracle pl/sql');
end;
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;
/
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:
Ex: write a program to display the employee information of empID 7654?
DINESH PV
Oracle Trainer
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 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
('=============================================');
dbms_output.put_line('Name of emp: '||vname);
DINESH PV
Oracle Trainer
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
=============================================
PL/SQL procedure successfully completed.
Ex: Write a program to display number of male customers and number
of female customers?
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:
1) Write a program to display designition of empid 7788?
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
DINESH PV
Oracle Trainer
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);
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;
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
DINESH PV
Oracle Trainer
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
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.
DINESH PV
Oracle Trainer
var_name . colname;
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)||
'*****************************'
);
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
DINESH PV
Oracle Trainer
);
end;
SUB PROGRAMS
Database programs which are saved under database server permanently.
Sub programs are 2 types.
They are
1) PROCEDURES
2) FUNCTIONS
/* Procedure body */
<declaration stmts>;
BEGIN
-----
-----
DINESH PV
Oracle Trainer
EXCEPTION
--
--
END <proc_name>;
/ ( to compile the procedure in SQL * PLUS)
Procedure created.
HOW TO EXECUTE A PROCEDURE?
We can execute a procedure in 2 methods.
1) By calling procedure
We can make a call to the procedure from program, procedure, function, package,
and trigger.
NOTE: Procedure never called using SELECT Query.
Syntax
proc_name[(Argval1,Argval2,....)];
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
DINESH PV
Oracle Trainer
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)||
'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;
DINESH PV
Oracle Trainer
BEGIN
proc_ecount_30; --Procedure calling stmt
dbms_output.put_line(' calling procedure is finished');
dbms_output.put_line(' Program Execution is finished');
END;
DYNAMIC PROCEDURES
WRITING THE PROCEDURE TO DISPLAY THE NUMBER OF EMPS IN THE
GIVEN DEPTNO?
SAMPLE EXECUTIONS:
EXEC PROC_2(10);
DINESH PV
Oracle Trainer
EXEC PROC_2(20);
EXEC PROC_2(30);
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 >
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.
ii) NO_DATA_FOUND
It will be raised if select query not selecting data from the table.
iii) ZERO_DIVIDE
It will be raised if a value is divided by zero.
iv) CURSOR_ALREADY_OPEN
It will be raised if we are trying to open a cursor which is already opened.
v) VALUE_ERROR
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);
DINESH PV
Oracle Trainer
ex:
DINESH PV
Oracle Trainer
end proc_emp_comm;
sample output:
PROCEDURE PROC_EMP_COMM compiled
EX:
EXEC PROC_EMP_COMM(7654);
anonymous block completed
comm of 7654 is 1400
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;
elsif (s>=1000 and s<2000) then
DINESH PV
Oracle Trainer
vbonus:=0.05*s;
elsif (s>=2000 and s<3000) then
vbonus:=0.10*s;
elsif (s>=3000 and s<5000) then
vbonus:=0.20*s;
else
vbonus:=0.25*s;
end if;
return(vbonus);
end func_bonus;
/
--Procedure to display empid, salary, bonus and total salary for given empid?
create or replace procedure proc_emp_fsal
(veno IN emp.empno%type)
is
vsal emp.sal%type;
b number(7,2);
Tsal number(7,2);
begin
select sal into vsal
from emp
where empno=veno;
------>function calling stmt
b:=func_bonus(vsal);
tsal := vsal+b;
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?
create or replace 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);
t sal number(7,2);
BEGIN
DINESH PV
Oracle Trainer
OPEN c;
dbms_output.put_line
(chr(10)||'empid salary bonus final salary'||chr(10)||
'-----------------------------------------------------------------');
LOOP
FETCH c into veno,vsal;
b := func_bonus(vsal); /* function calling stmt */
tsal := vsal+b;
EXIT WHEN (c%notfound);
dbms_output.put_line
(veno ||' '||vsal||' '||b||' '||tsal);
END LOOP;
CLOSE c;
end proc_emps_fsal;
/
Ex:
write a procedure to display empid, sal, bonus and total salary for all emps under
given job category?
create or replace procedure proc_emps_fsal_job
(vjob IN emp.job%type)
is
cursor c is select empno,sal from emp where job=vjob;
veno emp.empno%type;
vsal emp.sal%type;
b number(7,2);
tsal number(7,2);
begin
open c;
dbms_output.put_line
('Given Job Category : '||vjob);
dbms_output.put_line
('veno salary bonus final salary');
dbms_output.put_line
('-------------------------------------------------------');
loop
fetch c into veno,vsal;
b:=func_bonus(vsal); /* function calling stmt */
tsal := vsal+b;
exit when (c%notfound);
dbms_output.put_line
(veno ||' '||vsal||' '||b||' '||tsal);
end loop;
close c;
end proc_emps_fsal_job;
/
DINESH PV
Oracle Trainer
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>;
PROCEDURE <procedure calling stmts>;
FUNCTION <function calling stmts> RETURN <datatype>;
end <pkg_name>;
/ [ to compile package ]
2) package body
It contains procedure bodies and function bodies.
create or replace package Body <pkg_name>
IS
Procedure <proc-1-name> (.....)
is
--
--
DINESH PV
Oracle Trainer
end <proc-1>;
is
--
--
end <proc-2>;
Function <func-1>(.....)
return <datatype>
is
--
--
end <func-1>;
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?
CREATE OR REPLACE PACKAGE emppkg
AS
PROCEDURE PROC_EMP_FSAL
(VENO EMP.EMPNO%TYPE);
PROCEDURE PROC_EMPs_Fsal;
PROCEDURE PROC_EMPs_FSAL_JOB
(vjob emp.job%type);
FUNCTION FUNC_bonus(S EMP.SAL%TYPE)
RETURN NUMBER;
END emppkg;
/
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;
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);
DINESH PV
Oracle Trainer
begin
open c;
dbms_output.put_line
('----------------------------------------------------');
dbms_output.put_line
('salary bonus final salary');
dbms_output.put_line
('*************************************************');
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;
close c;
end proc_emps_fsal_job;
END emppkg;
/
HOW TO EXECUTE A PROCEDURE FROM A PACKAGE?
syn: exec pkg_name.proc_name(argval, argval......);
Ex: exec emppkg.proc_emp_fsal(7654);
How to call function from a package?
DINESH PV
Oracle Trainer
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
Invoked and executed automatically for any DDL command.
2) DML level triggers
Invoked and executed automatically for any DML command.
3) SESSION level triggers
Invoked and executed automatically for any session level command.
Interview Questions
1) What is the definition of data?
2) What is the definition of information?
3) What is the definition of a table?
4) Row is known as . . . . . ?
5) Column is known as ……..?
6) What is the full form of SQL?
7) What is the use of SQL?
8) SQL is a collection of . . . . . ?
9) How to display unique values from a column?
10) How to display unique records from a table?
11) What is the query to create a table?
12) How to insert values in to a table?
13) How to display structure of a table?
14) How to display data from a table and give an example?
15) What is the default order of table data?
16) How to display ordered values from a column?
17) Can we apply ORDER BY clause on multiple columns? If YES, what is the
expected result?
18) How to filter table data?
19) What is the use of relational operators?
20) How to search NULL values?
21) What is a null value?
22) What is the use of LIKE operator?
23) How to change old values with new values?
24) How to delete records from a table?
25) What is the difference between delete, truncate and drop commands?
26) What are the transactions?
27) How to make transactions permanently?
28) How to cancel transactions?
29) What is the use of GRANT command?
30) How to add a column to the old table?
31) Can I add columns in the middle of the existed columns?
32) What are the logical operators and what is their use?
33) What is the use of constraints?
34) What are constraints?
35) What is the use of unique constraint?
36) What is the use of Primary key?
37) What is the difference between UNIQUE and PRIMARY KEY?
DINESH PV
Oracle Trainer
38) What is the FOREIGN KEY? And what is the use of foreign key?
39) What is NORMALIZATION?
40) What is the use of JOINS?
41) What is a sub query?
42) What is a Nested query?
43) What is prerequisite for JOIN and sub query?
44) What is a view and what are the advantages of a view?
45) What is index and what is the use of index?
46) What is the use of GROUP BY clause?
47) What are the aggregations?
48) How to display highest salary and write the sample query?
49) How to display 2nd highest salary without using DENSE_RANK() function?
50) How to display Nth highest salary?
51) What is the use of DENSE_RANK()?
52) What is window clause?
53) How to delete duplicate records?
54) What is the use of set operators?
55) How to display matched data from multiple tables?
56) How to display combined data from multiple similar tables?
57) What is the use of ROWID?
58) How to display top n number of records from a table?
59) What is the use of ROUND() function?
60) What is the use of SUBSTR() function?
61) What is the use of TRIM() function?
62) What is the use of ASCII() function?
63) What is a program?
64) Why are you writing data base programs?
65) What is a stored procedure?
66) What is a built in datatype?
67) What is a built in function?
68) What is user defined function?
69) In PLSQL, what are the differences between procedure and function?
70) What is a cursor and what is its use?
71) What is exception?
72) What is a trigger?
73) How to delete column from a table?
74) How to change table name?
75) Can I delete a parent table if there exists any child table?
76) What is a self-join?
77) What is outer join?
78) What is metadata?
79) What is sql * plus?
80) What is the use of RDBMS?