0% found this document useful (0 votes)
185 views

PLSQL

The document discusses various Oracle PL/SQL concepts like defining and inserting values into tables, NULL values, conditional clauses in SELECT statements, sequences, constraints, joins, views, and more. Some key points include: 1. Tables can be defined using %ROWTYPE or records, and values can be inserted using INSERT statements or stored procedures. 2. NULL values represent unknown column values and NVL can be used to display alternate text for NULLs. 3. The order of conditional clauses in a SELECT is WHERE, GROUP BY, HAVING, ORDER BY. 4. Sequences are used to generate unique numbers and have options like START WITH, INCREMENT BY, MAXVALUE, CYCLE
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
185 views

PLSQL

The document discusses various Oracle PL/SQL concepts like defining and inserting values into tables, NULL values, conditional clauses in SELECT statements, sequences, constraints, joins, views, and more. Some key points include: 1. Tables can be defined using %ROWTYPE or records, and values can be inserted using INSERT statements or stored procedures. 2. NULL values represent unknown column values and NVL can be used to display alternate text for NULLs. 3. The order of conditional clauses in a SELECT is WHERE, GROUP BY, HAVING, ORDER BY. 4. Sequences are used to generate unique numbers and have options like START WITH, INCREMENT BY, MAXVALUE, CYCLE
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 17

defining a variable of table type can be done in 2 ways:

1. type emp_tab is table of employee%rowtype


2. type emp_rec is record (empid employee.emp_id%type,firstname employee.first_n
ame%type,lastname employee.last_name%type);
type emp_rec_t is table of emp_rec;
********************************************************************************
*********************************************************
Inserting values into a table can be done in the following ways:
1. declare
cust_rec employee%rowtype;
begin
cust_rec.emp_id :=2;
cust_rec.first_name :='Neha'
cust_rec.last_name := 'Singh'
insert into employee values cust_rec;
end
/
2.
create procedure insert_value_emp empid employee.emp_id%type,firstname employee.
first_name%type,lastname employee.last_name%type as
begin
insert into employee (emp_id,first_name,last_name) values (empid,firstname,lastn
ame);
exception
if dup_val_on_index then
update employee set first_name=firstname, last_name=lastname where emp_id=empid;
end
/
********************************************************************************
*********************************************************
ORACLE PL/SQL:
@@@@
DDL - Create, Alter, Comment, Rename, Drop, truncate (Hence can't be rolled back
and no triggers will be fired)
DML - Select, Insert, Update, Delete, Merge, CALL (Hence can be rolled back and
triggers can be fired)
DCL (DATA CONTROL LANGUAGE) - GRANT, REVOKE
TCL (Transaction Control Language) - COMMIT, SAVEPOINT, ROLLBACK, SET TRANSACTIO
N.
Delete - removes the rows from a table (a commit or rollback is required, all th
e triggers are fired.)
Truncate - removes the rows, can't be rolled back. (No triggers are fired)
Drop - Drops the table from the database hence all indexes or privilieges define
d for the tables will be dropped. (Can't be rolled back and no triggers are fire
d.)

@@@@
A Null value is nothing but a column with no values displayed since the value is
unknown. It is not a blank string.
NVL(column, "text to be displayed")
select first_name,last_name, NVL(first_name,"Unknown First Name") from employee
o/p
FIRST_NAME
---------First
First1

LAST_NAME NVL(first_name,"Unknown First Name")


--------- -----------------------------------Last
First
Last1
First1
Last2
Unknown First Name
********************************************************************************
***********************************************************
order of conditional clauses in a select statement:
1.
2.
3.
4.

where
group by
having
order by

e.g.
select group_id,market,avg(total_amount) AVG_TOTAL_AMT,count(*) Total_Count fro
m jpm_age_by_group where total_amount > 200 group by group_id,market
having avg(total_amount)=(select max(avg(total_amount))from jpm_age_by_group whe
re total_amount > 200 group by group_id,market)
select deptno, count(*) emp_count from employees group by deptno having count(*)
>4;
select deptno, count(*) emp_count from employees where bdate> date '1960-01-01'
group by deptno having count(*)>4;
select empno from employees group by empno having salary > (select avg(salary) f
rom eployees)
select * from (select * from employees order by salary desc) where rownum=2
********************************************************************************
***********************************************************
start with <Condition> connect by <child attrib>=<parent attrib> is used to sele
ct data that has a hierarchical relationship:
e.g. table1
id
Mgr_id
A
A1
B
A1
C
A
D
B
E
Z
select * from table1 where Mgr_id="A1" [without Start With]
OUTPUT:
id
Mgr_id
A
A1
B
A1
select * from table1 start with Mgr_id="A1" connect by id=Mgr_id

OUTPUT:
id
Mgr_id
A
A1
B
A1
C
A
D
B
********************************************************************************
**************************************************************
UNION ALL - returns all the rows including duplicate rows.
UNION - returns all the rows excluding duplicate
INTERSECT - returns the common rows
MINUS - returns the rows remain after subtracting the rows generated from the su
bquery
********************************************************************************
**************************************************************
create sequence <sequence name> [start with <num>][increment by <num>][MAXVALUE
<vall>|NOMAXVALUE][MINVALUE <val>|NOMINVALUE][CYCLE|NOCYCLE][CACHE|NOCACHE]
[ORDER|NOORDER];
e.g. create sequence s1; select s1.nextval from dual; drop sequence s1;
default start with is 1 increment is 1 default is NOMAXVALUE NOMINVALUE NOCYCLE
NOCACHE NOORDER
<sequence name>.nextval = gives the next value
alter sequence <sequence name> [start with <num>][increment by <num>][MAXVALUE <
vall>|NOMAXVALUE][MINVALUE <val>|NOMINVALUE][CYCLE|NOCYCLE][CACHE|NOCACHE]
[ORDER|NOORDER];
ORDER- guarantees that integers are generated in order or sequence.
NOORDER - doesn't guarantee any order,integers are generated randomly. [default]
CYCLE - specifies that sequence generates integer even if it reaches the maximum
value,in that case, next sequence generated would be the minimum value.
NOCYCLE - specified that sequence can't generate integer once it reaches the max
imum value. (default)
********************************************************************************
*************************************************************************
1. To rename a table:
RENAME <old table name> TO <new table name>;
2. Columns with constraints:
create table dept(
dept_name varchar(30) constraint dp_nn not null,
constraint dp_un unique,
constraint dp_chk check(dept_name=upper(dept_name)));
3.Referencing a column:
create table dept(
dept_name varchar(30) constraint dp_nn not null,
emp_no number referencing employee(emp_no));
4.drop <tablename> cascade constraint; [drops a table and all of its constraints
]
5. disable/enable constraints:
alter table dept disable constraint dp_un; alter table account enable constraint
fk;
6. user_cons_col -- this table stores the information about constraints [constra
int name, column name, table name etc.]
********************************************************************************
*************************************************************************

Foreign KEY:
altering table to add a constraint for foreign key
ALTER TABLE account ADD CONSTRAINT fk customerid REFERENCES customer(id) ON DELE
TE SET NULL; -- When a row in parent table deleted the, foreign key column in
corresponding rows in the child table are set to NULL.
DISABLING Foreign key -- alter table account disable constraint fk;
enabling foreign key -- alter table account enable constraint fk;
********************************************************************************
*****************************************************************************
The new SQL MERGE statement INSERTs some rows and UPDATEs others in a single ope
ration
Following example merges the non-matching rows of dept_online into dept table an
d matching rows are updated.
SELECT * FROM dept;
DEPTNO
---------10
20
30
60
40

DNAME
-------------ACCOUNTING
RESEARCH
SALES
HELP DESK
OPERATIONS

LOC
------------NEW YORK
DALLAS
CHICAGO
PITTSBURGH
BOSTON

SELECT * FROM dept_online;


DEPTNO
---------40
20
50

DNAME
-------------OPERATIONS
RESEARCH DEV
ENGINEERING

LOC
------------BOSTON
DALLAS
WEXFORD

MERGE INTO dept d


USING dept_online o
ON (d.deptno = o.deptno)
WHEN MATCHED THEN
UPDATE SET d.dname = o.dname, d.loc = o.loc
WHEN NOT MATCHED THEN
INSERT (d.deptno, d.dname, d.loc)
VALUES (o.deptno, o.dname, o.loc);
3 rows merged.
OUTPUT:
SELECT * FROM dept;
DEPTNO
---------10
20
30
50
60

DNAME
-------------ACCOUNTING
RESEARCH DEV
SALES
ENGINEERING
HELP DESK

LOC
------------NEW YORK
DALLAS
CHICAGO
WEXFORD
PITTSBURGH

40 OPERATIONS

BOSTON

********************************************************************************
*****************************************************************************
drop table <table name> cascade constraints; - dropping table along with its con
straints.
alter table registrations add (entered_by number(4) default 9 not null);
alter table registrations drop column entered_by ;
Adding comment syntax -add comment on [table|column] [tablename|tablename.columnname] is 'comments'; - all comments on a table are stored in user_tab_comments table
all comments on a columns are stored in user_col_comments table
********************************************************************************
****************************************************************************
SELECT e.ename, j.jobtitle FROM employee e right outer join job j WHERE e.empno
= j.empno; ---SELECT e.ename, j.jobtitle FROM employee e left outer join job j WHERE e.empno =
j.empno; ---OUTPUT:
ENAME
--------------Jason
John
Joe
Tom
Jane
Jack
Joke
James
Jodd

JOBTITLE
-------------------Tester
Accountant
Developer
COder
Director
Developer

USING clause: can be used inplace of ON clause to test which column value has to
be tested for equality amont
a. If Column name is same in both the tables:
SELECT * FROM COUNTRIES JOIN CITIES USING (COUNTRY)
b. If column names are different in the tables:
SELECT * FROM COUNTRIES JOIN CITIES USING (COUNTRY, COUNTRY_ISO_CODE)
********************************************************************************
****************************************************************************
VIEWS:
1. CHECK OPTION constraint:
CREATE VIEW emp_view AS
SELECT id, first_name, last_name

FROM employee where id<10 WITH CHECK OPTION CONSTRAINT emp_view_check;


insert into emp_view (id) values (11);
---Error as check clause is violated , any DML operations on a view must satisfy
the subquery used to create this view.
drop view <viewname>;
2. READ ONLY constraint:
CREATE VIEW emp_view AS
SELECT id, first_name, last_name
FROM employee where id<10 WITH READ ONLY CONSTRAINT emp_view_read_only;
insert into emp_view (id) values (11); -- Error
3. Creating view on user defined function:
create function emp_name (emp_id number) return varchar is
v_out varchar(255);
begin
select initcap(first_name)||':'||initcap(last_name) into v_out from employee whe
re id=emp_id;
return v_out;
end emp_name;
/
CREATE VIEW emp_view AS
select emp_name(id) EMP_NAME from employee where id<10;
4. creating view joining tables:
create or replace view crs_course_schedule as
select o.course as course_code, c.description, o.begindate
from course_schedule o
join
courses c
on (o.course = c.code);
5. dropping the constraint using ALTER VIEW:
ALTER VIEW emp_view DROP CONSTRAINT emp_view_read_only;
********************************************************************************
****************************************************************************
CREATE INDEX:
An Index is a performance tuning method of allowing faster retrieval of records.
By default, Oracle creates a B-Tree structure.
Oracle by default creates index for primary key and for columns which have a uni
que constraint.
If a new row is added it takes extra time to update the index. If no tablespace
is defined for index it is stored in user default tablespace.
UNIQUE index - it makes sure that only unique values are stored on the column in
each row, for which this index has been created.

create unique index <index name> on <table name>(<col name>) tablespace <tablesp
ace name>;
Composite index - index is created combining more than one column.
CTXSYS.CONTEXT - this type of index is used when we hav to index full text type
of data of larger size e.g. blob(storing .pdf,.doc) clob (plain text file).
e.g.
CREATE
id
name
doc
);

TABLE my_docs (
NUMBER(10)
NOT NULL,
VARCHAR2(200) NOT NULL,
BLOB
NOT NULL

CREATE INDEX my_docs_doc_idx ON my_docs(doc) INDEXTYPE IS CTXSYS.CONTEXT;


user_ind_col --- this table stores the information about indexes [index name, co
lumn name, table name etc.]
drop index <index name>;
Creating function index using case function:
create table case_tab (source_tran varchar2(5), po_id varchar2(5), voucher_id va
rchar2(5), journal_id varchar2(5));
create index case_tab_idx on case_tab (case source_tran when
CHER then voucher_id else journal_id end);

PO

then po_id when

ALTER INDEX employee_last_name_idx RENAME TO last_name_idx;


Function based index:
CREATE TABLE emp
(empno
ename
deptno

NUMBER

PRIMARY KEY,

VARCHAR2(10) NOT NULL ,


NUMBER(2)

NOT NULL ) CLUSTER personnel (deptno);

create index upper_idx on emp (UPPER(ename));


Now this index will boost search speed for the queries which use this upper func
tion in the where clause, e.g.
select * from emp where upper(ename)='KING' - this DML statement will make use o
f upper_idx index.
********************************************************************************
*****************************************************************************
Clusters and Indexes:
1. A cluster in Oracle is a schema object which optimizes database space. Rows o
f one or more tables that share same values in the common columns are stored
together in the database using cluster concept.

VOU

2. Cluster those tables that are frequently joined on cluster key columns throug
h SQL statements. Clustering multiple tables inproves the performance of joins.
But it reduces the performance of full table scan(select), insert and update whi
ch modifies cluster key values.
3. Cluster Key - Columns defined in create cluster command make up the cluster k
ey. Datatype and Size must correspond to the common columns in the tables.
Name may vary.
4. Two types of clusters are there: Indexed Cluster, Hash Cluster.
5. Indexed Cluster: Oracle stores the rows in the same data block having the sam
e cluster key value. An indexed cluster,an index must be created on the
cluster key. This index is called as the cluster index. A cluster index provides
fast access to rows inside a cluster based on the cluster key.
Indexed cluster is Useful when tables size is unpredictable
Search -> Input is Cluster Key -> Oracle finds corresponding cluster index in th
e cluster -> then finds corresponding row using ROWID.
Cluster Key - Name may vary but type and length should match with the table's co
lumn for which this cluster is gonna be used.
e.g.
CREATE CLUSTER personnel
( department_number NUMBER(2) )
SIZE 512
STORAGE (INITIAL 100K NEXT 50K PCTINCREASE 10);
Creating cluster index: CREATE INDEX idx_personnel ON CLUSTER personnel;
CREATE TABLE dept
(deptno NUMBER(2),
dname

VARCHAR2(9),

loc

VARCHAR2(9)) CLUSTER personnel (deptno);

CREATE TABLE emp


(empno
ename
deptno

NUMBER

PRIMARY KEY,

VARCHAR2(10) NOT NULL ,


NUMBER(2)

NOT NULL ) CLUSTER personnel (deptno);

6. Hash Cluster: Oracle stores the rows together,having the same hash key value.
Hash value for a row is the value returned by the cluster's hash function,
if no function is specified then default is oracle's internal hash function.
This is useful when rows are retrieved based on an equality condition involving
the cluster key columns. Also when size of the table is static and max no
of rows and size of the cluster can be determined.
Search -> Input is Cluster Key -> Oracle applies the hash function to the cluste
r key value -> using this hash values it finds all the matching columns in a

cluster. As hash key value can be same for multiple cluster key values.
Oracle's internal hash function returns value ranging from 0 to HASHKEYS-1.
Using HASH IS we can give a formula.
e.g.
a. Using Oracle's internal hash function [hash key values range from 0 to 499]
CREATE CLUSTER personnel
( department_number NUMBER )
SIZE 512 HASHKEYS 500
STORAGE (INITIAL 100K NEXT 50K PCTINCREASE 10);
b. Using HASH IS clause:
CREATE CLUSTER personnel
( home_area_code NUMBER,
home_prefix

NUMBER )

HASHKEYS 20
HASH IS MOD(home_area_code + home_prefix, 101);
SIZE - specifies space reserved for rows which belong to one cluster key value o
r hash key value. Then oracle determines how many key values can be stored in
each data block.
7. drop cluster <cluster name>;
8. IOT (Index-Organized table) - They store rows of a table in a sorted way bas
ed on the primary key value. Normal tables (heap-structure), IOTs B-Tree
structure, An IOT can not be in a cluster. Faster access to data when search is
made over a range of primary key values. Logical ROWID. No static physical
address, it may move across the data blocks if new rows are inserted.
-> An ORGANIZATION INDEX specifies that this is an Index-Organized table.
-> OVERFLOW clause - helps storing non key columns in a different overflow segme
nt to avoid space overflow.
-> PCTTHRESHOLD - specifies a maximum size which tells upto which column the row
will fit into the indexed block. Other portion of the row will be fit into
the overflow segment.
-> INCLUDE - specifies which are columns has to be stored along with the primary
key in the index block.
e.g.
CREATE TABLE admin_docindex(
token char(20),
doc_id NUMBER,
token_frequency NUMBER,
token_offsets VARCHAR2(2000),
CONSTRAINT pk_admin_docindex PRIMARY KEY (token, doc_id))
ORGANIZATION INDEX
TABLESPACE admin_tbs
PCTTHRESHOLD 20
OVERFLOW TABLESPACE admin_tbs2;

this tells that if a row size exceeds 20% of the index block size then rest of t
he portion will be stored in the overflow segment "admin_tbs2". Here main
index segment is "admin_tbs".
********************************************************************************
*****************************************************************************
SET AUTOTRACE
Setting autotrace allows displaying statistics and query plan on executing DML s
tatements:
SET AUTOTRACE ON - Enables all options, shows the execution plan as well as stat
istics along with the returned rows.
SET AUTOTRACE ON EXPLAIN - Shows execution plan only along with the returned row
s.
SET AUTOTRACE ON STATISTICS - Shows statistics only along with the returned rows
.
SET AUTOTRACE TRACEONLY - Shows the execution plan as well as statistics, but do
not print the returned rows.
SET AUTOTRACE OFF - Disables all the options.
********************************************************************************
*****************************************************************************
SELECT EXTRACT(MONTH FROM TO_DATE('01-JAN-2005 19:15:26','DD-MON-YYYY HH24:MI:SS
')) As MONTH FROM dual;
SELECT EXTRACT(YEAR FROM TO_DATE('01-JAN-2005 19:15:26','DD-MON-YYYY HH24:MI:SS
')) As YEAR FROM dual;
SELECT EXTRACT(DAY FROM TO_DATE('01-JAN-2005 19:15:26','DD-MON-YYYY HH24:MI:SS
')) As DAY FROM dual;
SELECT EXTRACT(HOUR FROM TO_DATE('01-JAN-2005 19:15:26','DD-MON-YYYY HH24:MI:SS
')) As HOUR FROM dual;
SELECT EXTRACT(MINUTE FROM TO_DATE('01-JAN-2005 19:15:26','DD-MON-YYYY HH24:MI:S
S')) As MINUTE FROM dual;
SELECT EXTRACT(SECOND FROM TO_DATE('01-JAN-2005 19:15:26','DD-MON-YYYY HH24:MI:S
S')) As SECOND FROM dual;
SELECT e.emp_id "ID", e.ename "Name", e.hire_date "Hire Date" FROM emp e ORDER B
Y EXTRACT(YEAR FROM hire_date) DESC, ename ASC;
SELECT MONTHS_BETWEEN('25-MAY-2005', '15-JAN-2005') FROM dual;
SELECT ADD_MONTHS('01-JAN-2005', 13) FROM dual; OUTPUT -> 01-FEB-06
SELECT TO_CHAR(LAST_DAY(TO_DATE('23SEP2006','ddMONyyyy'))) FROM dual;
TO_CHAR(L
--------30-SEP-06
SELECT id, TO_CHAR(Start_Date, 'Day fmMonth dd, yyyy') "Start_Date" FROM employe
e where id=1;
ID

Start_Date

---- ---------------------------01 Thursday July 25, 1996


select to_char(last_day(to_date('23Sep2012','ddMonyyyy'))) from dual;
30-SEP-12
select to_char(to_date('04-OCT-12','dd-MON-RR'), 'DD-MON-YYYY')
04-OCT-2012
ASCII('a') - 97
CHR(65) - A
CONCAT('AB','CD') - ABCD
INITCAP ('concat') - Concat [1st letter in caps]
INSTR(x,find_string,start,occurrence)
e.g. INSTR ('My name is Ram.His name is Raju.','name',1,2)
OUTPUT - 20 [returns the position of the searched string for its second occurren
ce.]
SELECT SUBSTR('My address is 123 Fourth St.',1,12)FROM dual
SUBSTR('MYAD
-----------My address i [starting from 1st character upto 12th character, total 12 charact
ers]
REPLACE (x,find_string,replace_string)
e.g. REPLACE('This is my house.','is','was')
output: This was my house.
sign(-6) --> -1
sign(6) --> 1
sign(0) --> 0
select decode(sign(marks),1,'Positive',
0,'Zero',
-1,'Negative') Sign from report;
SELECT empno, ename, orig_salary, ROWNUM FROM employee ORDER BY orig_salary;
EMPNO
---------1
2
4
3
7

ENAME
ORIG_SALARY
ROWNUM
--------------- ----------- ---------Jason
1234
1
John
2341
2
Tom
2413
4
Joe
4321
3
Jodd
5438
7

6
5
9
8

James
Jane
Jack
Joke

5679
7654
7896
8765

6
5
9
8

To get the second highest paid employee detail:


SELECT empno, ename, orig_salary FROM (select empno, ename, orig_salary from emp
loyee ORDER BY orig_salary desc) where ROWNUM=2;
OR
select empno, ename, orig_salary,RANK() over (order by orig_salary desc) ranking
from employee where ranking=2;
or
select empno, ename, orig_salary,ROW_NUMBER() over (order by orig_salary desc) r
anking from employee where ranking=2;

EMPNO ENAME
ORIG_SALARY
---------- --------------- ----------9 Jack
7896
Employee table
ID
------01
02
03
04
05
06
07
08

FIRST_NAME LAST_NAME START_DAT END_DATE


SALARY CITY
DESCRIPTION
---------- ---------- --------- --------- ---------- ---------- ----------Jason
Alison
James
Celia
Robert
Linda
David
James

Martin
Mathews
Smith
Rice
Black
Green
Larry
Cat

25-JUL-96
21-MAR-76
12-DEC-78
24-OCT-82
15-JAN-84
30-JUL-87
31-DEC-90
17-SEP-96

25-JUL-06
21-FEB-86
15-MAR-90
21-APR-99
08-AUG-98
04-JAN-96
12-FEB-98
15-APR-02

1234.56
6661.78
6544.78
2344.78
2334.78
4322.78
7897.78
1232.78

Toronto
Vancouver
Vancouver
Vancouver
Vancouver
New York
New York
Vancouver

Programmer
Tester
Tester
Manager
Tester
Tester
Manager
Tester

SELECT id, first_name, description, salary, RANK() OVER(PARTITION BY description


ORDER BY salary desc) rank FROM employee ORDER BY description;
ID
---07
04
01
02
03
06
05
08

FIRST_NAME
---------David
Celia
Jason
Alison
James
Linda
Robert
James

DESCRIPTION
SALARY
RANK
--------------- ---------- ---------Manager
7897.78
1
Manager
2344.78
2
Programmer
1234.56
1
Tester
6661.78
1
Tester
6544.78
2
Tester
4322.78
3
Tester
2334.78
4
Tester
1232.78
5

Grouping:
Subgroup
-------Manager
Manager

Group
Rank
-------- ----7897.78
1
2344.78
2

Programmer
Vancouver
Vancouver
Vancouver
Vancouver
Vancouver

1234.56
6661.78
6544.78
4322.78
2334.78
1232.78

1
1
2
3
4
5

To see highest salary in each description:


SELECT id, first_name, description, salary, RANK() OVER(PARTITION BY description
ORDER BY salary desc) rank FROM employee where rank=1;
ID
---07
01
02

FIRST_NAME
---------David
Jason
Alison

DESCRIPTION
SALARY
RANK
--------------- ---------- ---------Manager
7897.78
1
Programmer
1234.56
1
Tester
6661.78
1

create table emp


( empno
NUMBER(4)
constraint E_PK primary key
, ename
VARCHAR2(8)
, init
VARCHAR2(5)
, job
VARCHAR2(8)
, mgr
NUMBER(4)
, bdate
DATE
, sal
NUMBER(6,2)
, comm
NUMBER(6,2)
, deptno
NUMBER(2)
default 10
)
create table departments
( deptno NUMBER(2)
constraint D_PK primary key
, dname VARCHAR2(10)
, location VARCHAR2(8)
, mgr
NUMBER(4)
) ;
2. create view test_last_of_month as
select val, dt,
case when dt=max_dt then 'Y' else 'N' end last_dt
from (select val, dt, max(dt) over (partition by to_char(dt,'YYYY.MM'))
max_dt from test_month);
here partition clause divides the result set into group of months and then query
selects maximum date in each group
********************************************************************************
*****************************************************************************
TYPE <type name> IS RECORD
(col1 type,col2 type);
case <col name>
when <cond1> then <stmt>;
when <cond2> then <stmt1>;
else <stmt2>;
end case;

for i in 1..n
loop
stmt
end loop
********************************************************************************
*****************************************************************************
Cursors:
declare
cursor c1 is select id,empname from (select id,empname from employee order by sa
lary desc) where rownum>=8;
emp_rec c1%ROWTYPE;
begin
open c1
loop
exit when c1%NOTFOUND
fetch c1 into emp_rec
dbms_output.put_line(emp_rec.id);
end loop;
end;
/
********************************************************************************
*******************************************************************************
COMMIT & ROLLBACK:
begin
2
update employee set salary = 0;
3
savepoint SaveDept10Update;
4
update employee set salary = 100 where id ='01';
5
update employee set salary = 200 where id ='02';
6
7
Rollback to SaveDept10Update;
8
9 end;
10 /
PL/SQL procedure successfully completed.
SQL>
SQL> select * from employee;
ID FIRST_NAME
TY
DESCRIPTION
---- --------------------------- --------------01 Jason
ronto
Programmer
02 Alison
ncouver Tester
03 James
ncouver Tester
04 Celia
ncouver Manager

LAST_NAME

START_DAT END_DATE

SALARY CI

-------------------- --------- --------- ---------- -Martin

25-JUL-96 25-JUL-06

0 To

Mathews

21-MAR-76 21-FEB-86

0 Va

Smith

12-DEC-78 15-MAR-90

0 Va

Rice

24-OCT-82 21-APR-99

0 Va

********************************************************************************
*****************************************************************************
1. IF else

IF cond1 THEN
stmt1
ELSEIF cond1 THEN
stmt2
ELSE
stmt3
END IF;
2. CASE
case <col1>
when <cond1> then <stmt1>;
when <cond2> then <stmt2>;
else <stmt3>;
end case;
naming a case block:
case <col1>
when <cond1> then <stmt1>;
when <cond2> then <stmt2>;
else <stmt3>;
end case new_case;

variable assignment with case statement:


create or replace procedure case1 (p1 in number)
declare
v_name varchar(2);
begin
v_name :=
case
when p1=1 then 'A'
when p1=2 then 'B'
else 'C'
end case;
dbms_output.put_line ("Grade: " +v_name);
end;
/
3. LOOP with cursor:
create or replace procedure p1 as
declare
v_first_name varchar(20);
v_last_name varchar(30);
cursor c1 is select first_name,last_name from emp where id>'05' order by salary
desc;
begin
open c1;
loop
fetch c1 into v_first_name,v_last_name;
dbms_output.put_line("First Name: "+v_first_name+" Last Name: "+v_last_name);
exit when c1%NOTFOUND;
end loop;
close c1;
end;

/
4. FOR loop
begin
for i in 1..10
loop
dbms__output.put_line(i);
end loop;
end;
/
5. WHILE loop
declare
i number:=0;
begin
while i<=10
loop
i = i+1;
dbms_output.put_line(i);
end loop;
end;
/
6. GOTO and labels:
labels should be in <<>>.
if cond1
then
stmt1; GOTO label1;
else
stm2;
end if;
<<label1>>
dbms_output.put_line("This is Label1.");
end;
/
********************************************************************************
****************************************************************************
Dynamic SQL:
Generally DDL statements like insert,delete,drop can't be executed inside a PL/S
QL block directly. But using Dynamic SQL these statments can be used inside a
PL/SQL block.
1.
create or replace procedure drop_table_t (v_tab_name varchar(20))
begin
execute immediate 'drop table'||v_tab_name;
end;
/
2.
create or replace function select_tabe (v_id varchar , v_col varchar2) return va
rchar2 is
declare
v_out varchar2(2000);

v_sql varchar2(2000);
begin
v_sql := 'select'||v_col||'from employee'||'where id='||'"||v_id||"';
execute immediate v_sql into v_out;
return v_out;
EXCEPTION
when others
then return null;
raise;
end;
/
********************************************************************************
****************************************************************************
Autonomous transactions:
Oracle can suspend current transaction and transfer execution contorl to an inde
pendent child transaction known as autonomous transaction.
An autonomous transaction does not share any resources,locks or commit dependenc
ies with the calling transaction.
Main advantage of autonomous transaction is that the DML statements can be execu
ted and committed even if the calling transaction is rolled back.
Syntax:
a. Defining a procedure as anonymous transaction:
create or replace procedure <proc name>
is
pragma autonoumous_transaction;
begin
stmt1
end
b. Defining a block as anonymous transaction:
declare
pragma autonoumous_transaction;
begin
stmt1
end

You might also like