PLSQL
PLSQL
@@@@
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
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
DNAME
-------------OPERATIONS
RESEARCH DEV
ENGINEERING
LOC
------------BOSTON
DALLAS
WEXFORD
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
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
PO
NUMBER
PRIMARY KEY,
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
NUMBER
PRIMARY KEY,
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
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
EMPNO ENAME
ORIG_SALARY
---------- --------------- ----------9 Jack
7896
Employee table
ID
------01
02
03
04
05
06
07
08
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
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
FIRST_NAME
---------David
Jason
Alison
DESCRIPTION
SALARY
RANK
--------------- ---------- ---------Manager
7897.78
1
Programmer
1234.56
1
Tester
6661.78
1
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
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;
/
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