PLSQL IQ v1.5
PLSQL IQ v1.5
1|Page
Created by: Nayan
Oracle Architecture: ........................................................................................................................................................... 24
Synonym: ............................................................................................................................................................................ 24
DB Link: ............................................................................................................................................................................... 24
Partitioning: ........................................................................................................................................................................ 24
New Partitioning features in 11g........................................................................................................................................ 27
COLLECTIONS: ..................................................................................................................................................................... 28
BULK Collect and FOR ALL: ................................................................................................................................................. 15
How can I combine multiple rows into a comma-delimited list in Oracle? ....................................................................... 29
Splitting string into multiple rows in Oracle ....................................................................................................................... 29
Table Functions: ................................................................................................................................................................. 29
Pipelined Table Functions: ................................................................................................................................................. 30
Bind Variable: ..................................................................................................................................................................... 30
NO COPY: ............................................................................................................................................................................ 30
For update and No wait:..................................................................................................................................................... 30
On delete cascade: ............................................................................................................................................................. 30
On Delete set null: .............................................................................................................................................................. 30
Oracle 12g features for developers: ................................................................................................................................... 30
2|Page
Created by: Nayan
where rownum < 5;
ENAME EMP_CATEGORY
---------- -----------------
SMITH Top Bosses
ALLEN General Employees
WARD Top Bosses
JONES Managers
select decode(null,
null, 'NULL',
'NOT NULL') null_test
from dual;
O/P:
NULL
----
NULL
select case null
when null then
'NULL'
else
'NOT NULL'
end null_test
from dual;
NULL_TES
--------
NOT NULL
3|Page
Created by: Nayan
'2', '2',
'3') t
from dual;
T
----------
2
select case 2
when 1 then
'1'
when '2' then
'2'
else
'3'
end
from dual;
4|Page
Created by: Nayan
Deleting duplicate records:
DELETE EMPLOYEES
WHERE ROWID NOT IN
(SELECT MIN(ROWID) FROM EMPLOYEES GROUP BY FIRST_NAME, LAST_NAME)
JOINS:
--JOINS
--INNER JOIN--MATCHING NOT NULL RECORDS
SELECT E.FIRST_NAME, E.LAST_NAME, D.DEPARTMENT_NAME
FROM EMPLOYEES E
INNER JOIN DEPARTMENTS D
ON E.DEPARTMENT_ID = D.DEPARTMENT_ID;
--EQUIJOIN
SELECT E.FIRST_NAME, E.LAST_NAME, D.DEPARTMENT_NAME
FROM EMPLOYEES E, DEPARTMENTS D
WHERE E.DEPARTMENT_ID = D.DEPARTMENT_ID;
--OUTER JOIN
SELECT E.FIRST_NAME, E.LAST_NAME, D.DEPARTMENT_NAME
FROM EMPLOYEES E
LEFT OUTER JOIN DEPARTMENTS D
ON E.DEPARTMENT_ID = D.DEPARTMENT_ID;
5|Page
Created by: Nayan
WHERE E.DEPARTMENT_ID = D.DEPARTMENT_ID(+);
--RIGHT JOIN
SELECT E.FIRST_NAME, E.LAST_NAME, D.DEPARTMENT_NAME
FROM EMPLOYEES E
RIGHT OUTER JOIN DEPARTMENTS D
ON E.DEPARTMENT_ID = D.DEPARTMENT_ID;
--CROSS JOIN
SELECT E.FIRST_NAME, E.LAST_NAME, D.DEPARTMENT_NAME
FROM EMPLOYEES E --107
CROSS JOIN DEPARTMENTS D --27
--SELF JOIN
SELECT E.FIRST_NAME EMPNAME, M.FIRST_NAME MANAGER_NAME
FROM EMPLOYEES E
INNER JOIN EMPLOYEES M
ON E.MANAGER_ID = M.EMPLOYEE_ID;
/*
TABLE1 TABLE2
1 2
2 3
3 4
3 6
5 8
NULL NULL
7
OUTPUT:
1) IJ= 2, 3, 3. 3 rows selected
*/
PROCDURE:
Block of Statements/ Sub Programs used to implement Business Logic
6|Page
Created by: Nayan
Example of parameterized procedure:
CREATE OR REPLACE PROCEDURE PRC_EXCEPTION_DEMO1( P_EID IN EMPLOYEES.Employee_Id%TYPE)
IS
V_FN EMPLOYEES.FIRST_NAME%TYPE;
BEGIN
--P_EID:=101; You cannot write since it is IN parameter
SELECT E.FIRST_NAME INTO V_FN FROM EMPLOYEES E WHERE E.EMPLOYEE_ID = P_EID;
DBMS_OUTPUT.PUT_LINE(V_FN);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('NO DATA FOUND');
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('TOO MANY ROWS');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(SQLERRM);
END;
FUNCTION:
It is a set of PL/SQL statements you can call by name; Function should always return a value.
Typically function takes an input, processes and returns the output in other words Functions are normally used for
computations
--FUNCTION
CREATE OR REPLACE FUNCTION FN_SQR(P_NUM IN NUMBER) RETURN NUMBER IS
BEGIN
RETURN (P_NUM * P_NUM);
END;
--Call in PLSQL
DECLARE
V_TEST NUMBER:=FN_SQR(5);
BEGIN
DBMS_OUTPUT.PUT_LINE(V_TEST);
END;
FUNCTION VS PROCEDURE:
• Functions are normally used for computation whereas procedures are normally used for executing
business logic
• Procedure may or may not return value whereas function should return one value
• We can call function within procedure but we cannot call procedure within function
• Function can be called from SQL statement whereas procedure can't be called from the SQL statement
7|Page
Created by: Nayan
• You can have DML (insert, update, delete) OR commit/rollback statements in a function. But, you
cannot call such a function in a SQL query
o Procedure can perform one or more tasks whereas function performs a specific task
o Stored Procedure: supports deferred name resolution. Example while writing a stored procedure that
uses table named tabl1 and tabl2 etc. But those tables do not exist in database is allowed only in during
creation but runtime throws error Function won’t support deferred name resolution.
o Stored procedure returns always integer value by default zero. Whereas function returns type could be
scalar or table or table value
o Stored procedure is pre-compiled execution plan whereas functions are not
Can we use out parameter in function:
Yes, function can take OUT type parameter but the good programing practice is to not use the OUT parameter since
function must return only one value to the calling environment.
Can we use commit in function:
Technically, the answer is yes. You can do that in PLSQL as follows
CREATE OR REPLACE FUNCTION COMMITTEST RETURN NUMBER AS
BEGIN
UPDATE MY_TABLE SET COL = 'x';
COMMIT;
RETURN 1;
END;
/
DECLARE NUMBER N;
BEGIN
N := COMMITTEST();
END;
/
However, you can't do this in SQL query as shown below,
SELECT COMMITTEST() FROM DUAL;
PRAGMA AUTONOMOUS_TRANSACTION;
Autonomous transactions allow you to leave the context of the calling transaction, perform an independent
transaction, and return to the calling transaction without affecting its state. The autonomous transaction has
no link to the calling transaction, so only committed data can be shared by both transactions.
In simple words, it creates an independent transaction irrespective of the current context.
So whatever (commit/rollback) happens in PAT will be limited to PAT only and not affect actual context in any
way and vice-versa.
8|Page
Created by: Nayan
TRIGGERS:
A trigger is a PLSQL block which gets invoked automatically on occurrence of particular events, which is either
on a table, view, schema, or the database.
Triggers are commonly used to:
• Automatically generate derived column values
• Enforce referential integrity
• Enforce complex business rules
• Provide transparent event logging
• Provide efficient auditing
• Maintain synchronous table replicates
• Gather statistics on table access
Types of Triggers:
1. BEFORE UPDATE, Statement Level: This trigger will insert a record into the table 'product_check' before a SQL update
statement is executed, at the statement level.
9|Page
Created by: Nayan
CREATE or REPLACE TRIGGER After_Update_Stat_product
AFTER
UPDATE ON product
BEGIN
INSERT INTO product_check
Values('After update, statement level', sysdate);
End;
/
4. AFTER UPDATE, Row Level: This trigger will insert a record into the table 'product_check' after each row is updated.
Follows keyword:
10 | P a g e
Created by: Nayan
:OLD- Contains all the values old values of the table before trigger get executed
You normally use the terms in a trigger using :old to reference the old value and :new to reference the new
value. Here is an example from the Oracle documentation linked to above
In this example the trigger fires BEFORE DELETE OR INSERT OR UPDATE :old.sal will contain the salary prior to
the trigger firing and :new.sal will contain the new value.
EXCEPTIONS:
An exception is an error condition (by the run-time system) during a program execution
Types of Exceptions:
Pre-defined Exceptions:
Raised implicitly by Oracle
Non-Predefined Exceptions:
User Defined Exceptions: Raised explicitly by User
Pre-defined Exceptions:
DECLARE
V_FN EMPLOYEES.FIRST_NAME%TYPE;
BEGIN
SELECT E.FIRST_NAME INTO V_FN FROM EMPLOYEES E WHERE E.EMPLOYEE_ID = 1;
DBMS_OUTPUT.PUT_LINE(V_FN);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('NO DATA FOUND');
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE('TOO MANY ROWS');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(SQLERRM);
END;
Non-Predefined Exceptions:
PRAGMA EXCEPTION_INIT:
DECLARE
V_SAL EMPLOYEES.SALARY%TYPE;
V_UDE EXCEPTION;
PRAGMA EXCEPTION_INIT(V_UDE,+100);
BEGIN
RAISE_APPLICATION_ERROR(-20654,'MY ERROR');
SELECT E.SALARY INTO V_SAL FROM EMPLOYEES E WHERE E.EMPLOYEE_ID = 1;
EXCEPTION
WHEN V_UDE THEN
DBMS_OUTPUT.PUT_LINE('USER DEFINED EXCEPTION OCCURED');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(SQLERRM);
11 | P a g e
Created by: Nayan
END;
RAISE_APPLICATION_ERROR('MY ERROR',-20654);
UTL_FILE Example:
DECLARE
FILE_RESULT UTL_FILE.FILE_TYPE;
V_OP_FILENAME VARCHAR2(20);
BEGIN
--TO REDIRECT OUTPUT TO THE FILE
--WE NEED TO CONFIGURE USING
--CREATE OR REPLACE DIRECTORY DIR_OUTPUT AS 'D:\UTL_DEMO';
--TO CREATE DIRECTORY PATH
V_OP_FILENAME := 'TESTFILE.TXT';
FILE_RESULT := UTL_FILE.FOPEN('DIR_OUTPUT', V_OP_FILENAME, 'W');
UTL_FILE.PUT_LINE(FILE_RESULT, 'TEST DATA');
END;
12 | P a g e
Created by: Nayan
CREATE OR REPLACE PROCEDURE PRC_DYN(P_TN VARCHAR2,
P_CN VARCHAR2,
P_VAL VARCHAR2) IS
V_SQL VARCHAR2(100);
V_FN VARCHAR2(100);
BEGIN
V_SQL := 'select ' || P_CN || ' from ' || P_TN || ' where ' || P_CN ||
'=''' || P_VAL || '''';
DBMS_OUTPUT.PUT_LINE(V_SQL);
EXECUTE IMMEDIATE V_SQL
INTO V_FN;
DBMS_OUTPUT.PUT_LINE(V_FN);
END;
It is also being used to execute DDL in procedure
If column contains duplicate values so how can we make sure that it shouldn’t allow
duplicate values for further inserts without deleting existing data?
We need add unique key but Oracle will not allow you to do so since the column already has duplicate values
but we can do this with NO VALIDATE option while adding unique key constraint
Packages:
A package is a schema object that groups logically related PL/SQL items such as Functions, Procedures, types,
variables, constants, cursors, and exceptions.
A package is compiled and stored in the database
How will you decide whether any newly created procedure is to be added into the package or to be created
as a standalone procedure?
It depends on the call of the procedure in subsequent program, refer first point from advantages
Package Specification:
A package specification declares public items like functions and procedures, Here we just define the prototype
of the subprograms and declares the variables
CREATE OR REPLACE PACKAGE PCK_DEMO AS
FUNCTION F_MUL(X INT, Y INT) RETURN INT;
PROCEDURE PROC_MUL(X1 INT, X2 INT, X3 OUT INT);
END PCK_DEMO;
Package Body:
If a package specification declares cursors or subprograms, then a package body is required; otherwise, it is
optional.
CREATE OR REPLACE PACKAGE BODY PCK_DEMO AS
FUNCTION F_MUL(X INT, Y INT) RETURN INT IS
Z INT;
BEGIN
Z := X * Y;
RETURN(Z);
END F_MUL;
PROCEDURE PROC_MUL(X1 INT, X2 INT, X3 OUT INT) IS
BEGIN
X3 := F_MUL(X1, X2);
DBMS_OUTPUT.PUT_LINE(X3);
END PROC_MUL;
END PCK_DEMO;
Forward reference: If you want to use any subprogram into the body, which is supposed to be defined after its
call then declare its prototype before the call as shown in below program,
CREATE OR REPLACE PACKAGE PCK_DEMO AS
PROCEDURE PROC_MUL(X1 INT, X2 INT, X3 OUT INT);
END PCK_DEMO;
As you know in row level triggers the values of each column is stored in :OLD and :NEW parameters. For the
above UPDATE statement, Oracle stores the old values of FIRAT_NAME and LAST_NAME in the :OLD parameter
and then update FIRST_NAME with :OLD.LAST_NAME and LAST_NAME with :OLD.FIRST_NAME.
BULK COLLECT: SELECT statements that retrieve multiple rows with a single fetch, improving the speed of data
retrieval
DECLARE
TYPE V_RT IS RECORD(
EMPLOYEE_ID EMPLOYEES.EMPLOYEE_ID%TYPE,
SALARY EMPLOYEES.SALARY%TYPE); --RECORD TYPE VARIABLE
TYPE C_T IS TABLE OF V_RT; --COLLECTION
V_EMP C_T; --OBJECT OF COLLECTION
BEGIN
SELECT EMPLOYEE_ID, SALARY
BULK COLLECT
INTO V_EMP
FROM EMPLOYEES
WHERE DEPARTMENT_ID = 10;
END;
FORALL: INSERTs, UPDATEs, and DELETEs that use collections to change multiple rows of data very quickly
FORALL I IN V_EMP.FIRST .. V_EMP.LAST
INSERT INTO FORALL_TEST VALUES V_EMP(I);
What is the optimal way to copy data from one DB/Table to another DB/Table:
We can do this using BULK collect and FORALL as shown below,
DECLARE
-- DEFINE ARRAY TYPE OF THE NEW TABLE
TYPE NEW_TABLE_ARRAY_TYPE IS TABLE OF NEW_TABLE%ROWTYPE INDEX BY BINARY_INTEGER;
15 | P a g e
Created by: Nayan
-- DO YOUR BUSINESS LOGIC HERE (IF ANY)
Suppose you have 40 million records in the table and you need to delete 15 million record from it, what will
be your approach to do this?
How DML get processed? It stores the data into undo log buffer until we commit the transaction, if you
commit the operation; Oracle flushes the information from the Log Buffer to the online redo log files.
The undo block is used to store the before image of the data, so that the DML statements can be rolled back if
necessary.
You can create temp table and dump the require data into it and truncate the original table and copy back the
required data from temp table.
Step 1: Create copy(backup) of the table with required data (Use Bulk collect and For all to copy data
efficiently)
Step 2: Truncate original table
Step 3: Copy back the required data from backup table (Or delete mail table and rename backup table)
LOGGING or NOLOGGING?
LOGGING is a keyword that used on creating the index, table or tablespace. If we use LOGGING when creating
the object then DML operations on the objects are logged in redo log file. If we use NOLOGGING when creating
the object, in some cases DML operations on the objects are not logged in redo log file.
SAVEPOINT:
If we want some part of the program to be COMMITted and some part to be ROLLBACKed in that scenario we
use SAVEPOINT
Simple Index:
CREATE INDEX EMP_DEPT_IDX
ON EMPLOYEES (first_name);
16 | P a g e
Created by: Nayan
Composite Index:
CREATE INDEX EMP_NAME_IDX
ON EMPLOYEES (FIRST_NAME, LAST_NAME)
COMPUTE STATISTICS;
Types of Indexes:
Cluster and Non Cluster: In Cluster index the actual data is being stored in the Index and in Non-Clustered
index the pointer to record is being stored
Example:
CREATE INDEX EMP_DEPTID_IX ON HR.EMPLOYEES(DEPARTMENT_ID);
Bitmap Index:
The database stores a bitmap for each index key. In a B-tree index, one index entry points to a single row. In a
bitmap index, each index key stores pointers to multiple rows.
The indexed columns have low cardinality, that is, the number of distinct values is small compared to the
number of table rows.
Example:
CREATE BITMAP INDEX EMPLOYEES_BM_IDX
ON EMPLOYEES (JOBS.JOB_TITLE)
FROM EMPLOYEES, JOBS
WHERE EMPLOYEES.JOB_ID = JOBS.JOB_ID;
17 | P a g e
Created by: Nayan
Invisible indexes can be useful for processes with specific indexing needs, where the presence of the indexes
may adversely affect other functional areas. They are also useful for testing the impact of dropping an index.
18 | P a g e
Created by: Nayan
In above query, to check the condition Optimizer needs to call UPPER function for each and every row of the
table, so we create a FBI on UPPER function so that Optimizer do not need to call the same function again and
again for each record, It can directly access the values from FBI for comparison
VIEW:
View is a virtual table that does not physically exist. It is created by a query joining one or more tables.
Materialized View:
A materialized view is a database object that contains the results of a query which is physically stored on the
child servers due to this we will get the result faster as the data is being stored physically on the local/child
servers
Since the MV is stored physically by executing the Complex query (with joins, Group by functions, aggregate
functions etc.), we will get the result faster since the time required for executing complex query will get
minimized
• FAST: It is the incremental refresh method, which performs the refresh according to the changes that
have occurred to the master tables since the last refresh
• COMPLETE: It is the complete refresh method, which is implemented by executing the given query of
the MV.
• FORCE: Specify FORCE to indicate that when a refresh occurs, Oracle will perform a fast refresh if one is
possible or a complete refresh if fast refresh is not possible.
• ON COMMIT: Specify ON COMMIT to indicate that a fast refresh is to occur whenever the database
commits a transaction that operates on a master table of the materialized view.
VIEW vs MVIEW:
In Views query result is not physically stored but MView store query result physically.
In case of View we always get latest data but in case of MView we need to refresh the view for getting latest
data.
View is dynamic while the MView is static
Deterministic Functions:
A deterministic function always returns the same value if the input parameters are identical.
1+1 is always equal to 2 but a function called Get_Customer_Name(4711) won't return the same value because
it fetches data from the database which changes.
Cursor:
It is a temporary work area which is used to store the row-set into the memory
2 types:
Implicit: DML and Select query returning only one row, is being managed by Oracle server automatically
DECLARE
TOTAL_ROWS NUMBER;
BEGIN
UPDATE EMPLOYEES
SET SALARY = SALARY + 500 WHERE ROWNUM<10;
IF SQL%NOTFOUND THEN
DBMS_OUTPUT.PUT_LINE('NO DATA UPDATED');
ELSIF SQL%FOUND THEN
TOTAL_ROWS := SQL%ROWCOUNT;
DBMS_OUTPUT.PUT_LINE( TOTAL_ROWS || ' ROWS UPDATED ');
END IF;
END;
Explicit: Select query returning more than one rows, is user defined and needs to be handle programmatically
DECLARE
V_FN EMPLOYEES.FIRST_NAME%TYPE;
V_LN EMPLOYEES.LAST_NAME%TYPE;
CURSOR C1 IS
20 | P a g e
Created by: Nayan
SELECT E.FIRST_NAME, E.LAST_NAME FROM EMPLOYEES E; --Cursor declaration
BEGIN
OPEN C1; --Opening Cursor
LOOP
FETCH C1
INTO V_FN, V_LN; --Fetching data from cursor and storing into the variable
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('FIRST NAME: ' || V_FN || ' LAST NAME: ' || V_LN);
END LOOP;
CLOSE C1; --Closing cursor
END;
REF Cursor:
It is useful to return the query result from Oracle DB to client application
You can use the same cursor for multiple times i.e. you can reopen the cursor for different query
DECLARE
V_FN EMPLOYEES.FIRST_NAME%TYPE;
V_LN EMPLOYEES.LAST_NAME%TYPE;
V_SAL EMPLOYEES.SALARY%TYPE;
V_ID EMPLOYEES.EMPLOYEE_ID%TYPE;
V_RC SYS_REFCURSOR; -- Declaring Ref cursor
BEGIN
OPEN V_RC FOR
SELECT E.FIRST_NAME, E.LAST_NAME FROM EMPLOYEES E; -- Opening cursor with given query
LOOP
FETCH V_RC
INTO V_FN, V_LN; -- Fetching data
EXIT WHEN V_RC%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('FIRST NAME: ' || V_FN || ' LAST NAME: ' || V_LN);
END LOOP;
CLOSE V_RC; --Closing Ref Cursor
DBMS_OUTPUT.PUT_LINE('Reusing the ref cursor for another query');
OPEN V_RC FOR
SELECT E.SALARY, E.EMPLOYEE_ID FROM EMPLOYEES E; -- Reopening cursor for another query
LOOP
FETCH V_RC
INTO V_SAL, V_ID;
EXIT WHEN V_RC%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('SALARY: ' || V_SAL || ' ID: ' || V_ID);
END LOOP;
CLOSE V_RC;
END;
21 | P a g e
Created by: Nayan
Sequence:
Automatically generates unique numbers
Typically used to generate PK values
CREATE SEQUENCE customers_seq
START WITH 10
INCREMENT BY 5
MINVALUE 10
MAXVALUE 100
CACHE 10
NOCYCLE;
External table:
It is used to link flat file and the data is being displayed in oracle table format.
SQL Loader:
Is used to load the data from external files to Oracle database
Load data from multiple datafiles during the same load session.
Load data into multiple tables during the same load session.
22 | P a g e
Created by: Nayan
DEMO of Parameter file:
USERID=HR/HR
CONTROL=TEST.ctl
DATA="D:\oracle study\loader\TEST.CSV"
LOG=LOG\TestLOG.log
BAD=BAD\Test_BAD.txt
DISCARD=DISC\Test_DISCARD.txt
23 | P a g e
Created by: Nayan
Oracle Architecture:
Synonym:
A synonym is an alternative name for DB objects such as tables, views, sequences, stored procedures, and
other database objects.
CREATE PUBLIC SYNONYM EMP
FOR HR.EMPLOYEES;
DB Link:
A database link is a schema object in one database that enables you to access objects on another database.
Partitioning:
This is process of dividing the large tables into the sub tables using specified condition to improve the
performance
Partitioning allows tables to be subdivided into smaller pieces, enabling these database objects to be managed
and accessed at a finer level of granularity.
24 | P a g e
Created by: Nayan
Types:
Range Partitioning: We specify range of values to be partitioned
CREATE TABLE EMPLOYEES
(
EMP_ID VARCHAR2(100),
SALARY NUMBER(10),
)
PARTITION BY RANGE (SALARY)
(
PARTITION P1 VALUES LESS THAN 10000,
PARTITION P2 VALUES LESS THAN 40000,
PARTITION P3 VALUES LESS THAN 100000,
PARTITION P4 VALUES LESS THAN 500000
);
Hash Partitioning: Oracle internally performs hash function to partition the values
CREATE TABLE PURCHASE_ORDER
(
PURCHASE_ORDER_NO NUMBER (10),
PURCHASE_ORDER_TYPE VARCHAR2 (5),
PURCHASE_ORDER_DATE DATE,
FREIGHT_DATE DATE,
FREIGHT_AMOUNT NUMBER (10, 2),
PURCHASE_ORDER_AMOUNT NUMBER (10, 2)
)
PARTITION BY HASH (PURCHASE_ORDER_NO)
PARTITIONS 4;
List Partitioning: We specify list of values based on which the partitioning is done
CREATE TABLE SALES
(
SALES_NO NUMBER,
DEPT_NAME VARCHAR2 (20),
SALE_AMOUNT NUMBER (10, 2),
REGION VARCHAR2 (10)
)
PARTITION BY LIST (REGION)
(
PARTITION P1 VALUES ('NORTH'),
25 | P a g e
Created by: Nayan
PARTITION P2 VALUES ('SOUTH'),
PARTITION P3 VALUES ('EAST'),
PARTITION P4 VALUES ('WEST')
);
Composite Partitioning: It consists combination of any of the above 2 types
*If the performance doesn’t get increased after doing partitioning then we can also add index to the
partitions
In a local index, all keys in a particular index partition refer only to rows stored in a single underlying table
partition. A local index is created by specifying the LOCAL attribute.
26 | P a g e
Created by: Nayan
CREATE INDEX cust_id_prod_id_global_ix
ON sales(cust_id,prod_id)
GLOBAL PARTITION BY HASH (cust_id)
( PARTITION p1 TABLESPACE tbs1
, PARTITION p2 TABLESPACE tbs2
, PARTITION p3 TABLESPACE tbs3
, PARTITION p4 TABLESPACE tbs4
)
PARALLEL NOLOGGING;
Reference Partitioning
This creates partitions identical to those in the parent table. The clause partition by reference has the name of
the foreign key in the partition definition. This instructs Oracle Database 11g to confirm the partitioning is done
per the scheme used in the parent table.
PARTITION BY REFERENCE (FK_SALES_01);
Reference partitions come extremely handy when you want to partition a child table in the same fashion as in
the parent table but do not have the same columns, and you do not want to introduce them just for the sake of
partitioning. Furthermore, you do not need to explicitly declare a long partitioning clause for each child table.
Interval Partitioning:
What happens if a record is inserted into the table that does not belong to any partition? The insert will fail
with the following error:
ORA-14400: inserted partition key does not map to any partition
27 | P a g e
Created by: Nayan
In 11g, you don't define partitions and their boundaries but merely an interval that defines each partition's
boundaries, Oracle will automatically create new partition on inserting new value based on the given Range.
Here is the same example in interval partitioning:
INTERVAL (NUMTOYMINTERVAL(1,'MONTH'))
(
PARTITION P0701 VALUES LESS THAN (TO_DATE('2007-02-01','YYYY-MM-DD'))
);
COLLECTIONS:
In normal FOR loop, the loop gets iterated for all the record of the collection which increases the database hits
so to reduce this we use FOR ALL which hits the database only once to perform the operation.
SAVE EXCEPTIONS:
You can use this to get the list of exceptions occurred while executing the DML on the Oracle sever using FOR
ALL
BEGIN
FORALL I IN V_EMP.FIRST .. V_EMP.LAST SAVE EXCEPTIONS
INSERT INTO FORALL_TEST VALUES V_EMP(I);
EXCEPTION
WHEN OTHERS THEN
IF SQLCODE = -24381 THEN
FOR INDX IN 1 .. SQL%BULK_EXCEPTIONS.COUNT LOOP
28 | P a g e
Created by: Nayan
DBMS_OUTPUT.PUT_LINE(SQL%BULK_EXCEPTIONS(INDX).ERROR_INDEX || ‘
:‘ || SQL%BULK_EXCEPTIONS(INDX).ERROR_CODE);
END LOOP;
ELSE
RAISE;
END IF;
END;
DEPARTMENT_ID EMPLOYEES
------------- ---------------------------------------
10 200
20 201,202
30 114,115,116,117,118,119
40 203
50 120,121,122,123,124,125,126,127,128,129
Table Functions:
Table functions are used to return PL/SQL collections. They can be queried like a regular table by using the
TABLE function in the FROM clause. Regular table functions require collections to be fully populated before
they are returned.
Since collections are held in memory, this can be a problem as large collections can waste a lot of memory and
take a long time to return the first row. Regular table functions require named row and table types to be
created as database objects.
Pipelined table functions include the PIPELINED clause and use the PIPE ROW call to push rows out of the
function as soon as they are created, rather than building up a table collection. Notice the empty RETURN call,
since there is no collection to return from the function.
-- Build a pipelined table function.
CREATE OR REPLACE FUNCTION get_tab_ptf (p_rows IN NUMBER) RETURN t_tf_tab PIPELINED AS
BEGIN
FOR i IN 1 .. p_rows LOOP
PIPE ROW(t_tf_row(i, 'Description for ' || i));
END LOOP;
RETURN;
END;
/
-- Test it.
SELECT * FROM TABLE(get_tab_ptf(10)) ORDER BY id DESC;
Bind Variable:
NO COPY:
On delete cascade:
Identity Columns
With Oracle 12c we can define a column as identity column. When new row is added sequence automatically increments
and writes the column.
CREATE TABLE T_MY_TAB
(
USER_ID NUMBER GENERATED AS IDENTITY
);
Top-N Feature
With Oracle 12c new keywords came out for Top-N queries
SELECT value FROM EMP ORDER BY value DESC FETCH FIRST 10 ROWS ONLY;
With Clause
We can use pl/sql in select query using new with clause
WITH
FUNCTION f_incr(n IN NUMBER) RETURN NUMBER IS
30 | P a g e
Created by: Nayan
BEGIN
RETURN n+1;
END;
SELECT f_incr(1)
FROM dual;
How do I get all dates from sysdate's month with Oracle SQL?
NAME M1 M2 M3 M4
---- ---------- ---------- ---------- ----------
A 1 2 3 4
B 6 3 4 5
C 1 5 2 1
Vice-versa:
SELECT NAME, LEAST(M1,M2,M3,M4) FROM YOUR_TABLE
How to check any missing number i.e. Gaps from a series of numbers or sequence?
select x, next_x
from (select x, lead(x) over(order by x) next_x from t)
where x <> next_x – 1
Analytical function:
Analytic functions also operate on subsets of rows, like aggregate functions in GROUP BY queries, but they do not reduce
the number of rows returned by the query.
SELECT e.*,
AVG(e.salary) OVER(PARTITION BY e.department_id) AS avg_dept_sal
FROM Employees e;
31 | P a g e
Created by: Nayan
SELECT e.*,
ROW_NUMBER() OVER(ORDER BY e.salary) AS row_num,
RANK() OVER(ORDER BY e.salary) AS row_rank,
DENSE_RANK() OVER(ORDER BY e.salary) AS row_dense_rank
FROM Employees e;
ACTION_ITEMS
-------
ID SOURCE_ID SOURCE_TYPE
1 12345 INC
2 67890 AUD
INCIDENTS
-------
ID
12345
AUDITS
-------
ID
67890
SELECT AI.*
FROM ACTION_ITEMS AI
LEFT JOIN INCIDENTS ON AI.SOURCE_TYPE = 'INC' AND (AI.SOURCE_ID = INCIDENTS.ID)
LEFT JOIN AUDITS ON AI.SOURCE_TYPE = 'AUD' AND (AI.SOURCE_ID = INCIDENTS.ID)
SELECT sid,
to_char(start_time, 'hh24:mi:ss') stime,
message,
(sofar / totalwork) * 100 percent
FROM v$session_longops
WHERE sofar / totalwork < 1
Purge statement:
Use the PURGE statement to remove the entire recycle bin
When issuing a DROP TABLE statement in Oracle, you can specify the PURGE option. The PURGE option will purge the
table and its dependent objects so that they do not appear in the recycle bin. The risk of specifying the PURGE option is
that you will not be able to recover the table. However, the benefit of using PURGE is that you can ensure that sensitive
data will not be left sitting in the recycle bin.
32 | P a g e
Created by: Nayan
Reverse key index:
Reverse key indexes literally reverse the bytes of the key value in the index to reduce block contention on sequence
generated primary keys.
A Reverse Key Index simply takes the index column values and reverses them before inserting into the index.
“Conceptually”, say the next generated ID is 123456, Oracle will reverse it to 654321 before inserting into the index. It
will then take the next generated ID 123457 and reverse it to 754321 and insert it into the index and so on. By doing this,
inserts are spread across the whole index structure, ensuring the right most block is no longer the only index leaf block
being hammered. Index contention is dramatically reduced or eliminated entirely.
The index, itself, does not enforce the uniqueness. The constraint does, and the constraint makes use of an index (be it a
UNIQUE index or an index that allows for duplicates) to make this enforcement go faster.
33 | P a g e
Created by: Nayan