Vous êtes sur la page 1sur 3446

Oracle sql & Pl/sql

search

Home Sql and pl/sql Sql Interview Questions

JUL

20

INLINE view in Oracle with 12c New Features

Named sub Query in FROM clause is call it as INLINE VIEW.

Oracle process a inline view faster than sub query

Inline View in Oracle

--Query to display all the employees who are all getting salary more than their department
average salary

SELECT First_name

, last_name

, salary

, department_id

FROM employees a , ( SELECT b.department_id

, AVG(b.salary) avg_sal

FROM employees b

GROUP BY b.department_id

)b
WHERE a.department_id = b.department_id

AND a.salary > b.avg_salary;

Display all the customer who have placed more number of orders by using INLINE view

CREATE TABLE customer_order_det_tb

( custm_id NUMBER ,

custm_nm VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

ttl_amt NUMBER(7,2)

);

BEGIN

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '11-Jul-15' , 45000.00);

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '14-Jul-15' , 27000.00);

INSERT INTO customer_order_det_tb VALUES(101, 'Raja' , '13-Jul-15' , 17000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 34000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 38000.00);

COMMIT;

END;

SELECT c.*

FROM customer_order_det_tb c;
--------------------------------------------

custm_id custm_nm order_dt ttl_amt

--------------------------------------------

100 Murugappan 7/11/2015 45000.00

100 Murugappan 7/14/2015 27000.00

101 Raja 7/13/2015 17000.00

102 Ramesh 7/15/2015 34000.00

102 Ramesh 7/15/2015 38000.00

--------------------------------------------

--Writing a Quer to display all the customer who have placed maximum number of order

--Query #1 for inline view

SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC;

--------------------------------

custm_id custm_nm total_odr

--------------------------------

100 Murugappan 2

102 Ramesh 2
101 Raja 1

--------------------------------

--Query #2 for inline view

SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm;

----------

total_odr

----------

----------

Inline view to find all the customers who have placed maximum number of orders

/****************************************

Syntax

SELECT * FROM <query1> x, <query2> y

WHERE contition;

****************************************/

SELECT query1.* FROM


( SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC

) query1,

( SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm

) query2

WHERE query1.total_odr = query2.total_odr;

-------------------------------

custm_id custm_nm total_odr

-------------------------------

100 Murugappan 2

102 Ramesh 2

-------------------------------

DROP TABLE customer_order_det_tb;

--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT

SELECT first_name, salary

FROM ( SELECT first_name, salary


FROM employees e

WHERE job_id NOT IN ('SALESMAN','PRESIDENT')

ORDER BY salary DESC

WHERE ROWNUM < 4;

New Oracle 12c Inline view Syntax

LATERAL clause for In-line views

Allows for columns in the inline view to be accessed!!

Example :

--in 11g

SELECT * FROM employees e, (

SELECT *

FROM departments d

WHERE e.department_id = d.department_id);

ORA-0090: "E"."DEPARTMENT_ID": Invalid Identifier

--in 12c
SELECT * FROM employees e, LATERAL(

SELECT *

FROM departments d

WHERE e.department_id = d.department_id

);

--in 11g

WITH t

AS

( SELECT LEVEL a

FROM dual

CONNECT BY LEVEL <= 30)

SELECT *

FROM t, (SELECT *

FROM employees

WHERE department_id = t.a

);

ORA-00904: "T"."A": invalid Identifier

--in 12c

WITH t

AS

(SELECT LEVEL a FROM dual CONNECT BY LEVEL <= 30)


SELECT * FROM t,

LATERAL(SELECT *

FROM employees

WHERE department_id = t.a);

Hope you have enjoyed this little article

Feed backs are always Welcome :) (:

Posted 20th July 2015 by Unknown

0 Add a comment

JAN

23

Salary Related Questions in Oracle

--creating table

CREATE TABLE employee_data

eid NUMBER(4),

ename VARCHAR2(30),
depno NUMBER(3),

salary NUMBER(8)

);

BEGIN

--Inserting records

INSERT INTO employee_data VALUES(1000,'Name01',90,30000);

INSERT INTO employee_data VALUES(1001,'Name02',90,6000);

INSERT INTO employee_data VALUES(1002,'Name03',90,23000);

INSERT INTO employee_data VALUES(1003,'Name04',60,35000);

INSERT INTO employee_data VALUES(1004,'Name05',60,60000);

INSERT INTO employee_data VALUES(1005,'Name06',60,30000);

INSERT INTO employee_data VALUES(1006,'Name07',80,36000);

INSERT INTO employee_data VALUES(1007,'Name08',80,29000);

INSERT INTO employee_data VALUES(1008,'Name09',80,37000);

INSERT INTO employee_data VALUES(1009,'Name10',80,41000);

COMMIT;

END;

SELECT * FROM employee_data

ORDER BY salary DESC;


--query to find maximum salary from employee_data table

SELECT MAX(salary) FROM employee_data;

--query to find minimum salary from employee_data table

SELECT MIN(salary) FROM employee_data;

--query to find second maximum salary from employee_data table

SELECT MAX(salary)

FROM employee_data

WHERE salary NOT IN (SELECT MAX(salary)

FROM employee_data);

--query to select 5th maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= 5);


--query to select nth maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= &n);

--query to select all the details of the employee whose getting nth maximum salary

SELECT *

FROM (SELECT emp.*,

rownum rn

FROM (SELECT *

FROM employee_data

ORDER BY salary DESC) emp)

WHERE rn = 9;

--same query using row_numbr( ) function

SELECT *

FROM (SELECT emp.*,


row_number() over(ORDER BY salary) rank

FROM employee_data emp)

WHERE rank = 9;

--same query using rank( ) function

SELECT *

FROM (SELECT emp.*,

rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--same query using dense_rank( ) function

SELECT *

FROM (SELECT emp.*,

dense_rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--query to display display maximum salary in all the department

SELECT e.depno "Department id",

MAX(salary) "Maximum Salary"


FROM employee_data e

GROUP BY e.depno;

--query to display all the employees who are all getting salary more than average salary of the
company

SELECT e.* FROM employee_data e

WHERE salary > (SELECT AVG(salary) FROM employee_data);

--query to display all the employees who are all getting salary more than their department
average salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE department_id = OUT.department_id);

--query to display all the employees who are all getting salary more than their manager salary

SELECT employee_id,

first_name,
salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE employee_id = OUT.manager_id);

Documented By : Murugappan Annamalai

Posted on : 23-Jan-15 16:34:00 IST.

Hope you have enjoyed this little article

Feed backs are always welcome :)

Posted 23rd January 2015 by Unknown

7 View comments

JAN

22

Why prefer COALESCE over NVL

Documented By : Nimish Garg


I prefer using "COALESCE" over "NVL" is some of the scenarios. Last week One of my friend
asked me what is the advantage of using "COALESCE" where we can simply use "NVL". I simply
gave him the reply from Oracle Docs i.e. NVL lets you replace null (returned as a blank) with a
string in the results of a query and COALESCE returns the first non-null expr in the expression list.
Oracle Database uses short-circuit evaluation with "COALESCE".

He replied that he knows the difference, he knows that "COALESCE" can take multiple arguments
and so on. He was more interested in understanding "short-circuit evaluation" of "COALESCE"
and the scenarios where I prefer using "COALESCE" over "NVL".

To make him understand I created following function which takes One second in every execution
and simply returns '--null--' and executed 2 very similar queries one with NVL and other with
COALESCE.

SQL> create or replace function f_null return varchar2

2 is

3 begin

4 dbms_lock.sleep(1);

5 return '--null--';

6 end;

7 /

Function created.

Following are the queries which I used to demonstrate that NVL evaluates both arguments even
if the second argument is not used and COALESCE uses short-circuit evaluation i.e. it only
evaluates the arguments only if they are needed.
SQL> select e.empno, e.ename ename, nvl(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.

Elapsed: 00:00:14.01
SQL> select e.empno, e.ename ename, coalesce(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.

Elapsed: 00:00:01.01
Here we can see easily that the first query with NVL took 14+ seconds, one second for each
record even if the "f_null" value was used only in one record. On the contrary as mentioned in
Oracle Documentation "COALESCE" uses its "short-circuit evaluation" and "f_null" was called
only once and so second query took only One Second. "COALESCE" is certainly use less resources
than NVL.

Posted 22nd January 2015 by Unknown

0 Add a comment

DEC

21

Constraints

It Enforce Rule On Table

We can create constraint at the time of Creating Table

1. Column Level Declaration

2. Table Level Declaration

1. We can provide own name.


Format : [part_of_project_name-table_name-column_name-constraint_type]

Example : gmind_emp_id_pk _uk _ck _f

2. system name name

Format : sys_cn

Example : SYS_C405323

We can create constraint after the table has been created

Types

Primary Key

Not allowed Null value

Not allowed you to enter duplicate value

Ex : Employee_id, Student_id

Unique Key

allowed Null value

Not allowed you to enter duplicate value


Ex : Contact_no, email

Foreign Key

It will allowed you to enter NULL and Duplicate value.

c1(pk) : 1 2 3

c2(f) : 1 1 2 3 4 Not allowed

Allowed you to enter duplicate value and null value

Not Null

It will not allowed you to enter null value

Check

You can check your own condition

Simple Table for understanding

------------------------------------

Duplicate NULL
------------------------------------

Primary Key X X

Unique Key X Allowed

Foreign Key Allowed Allowed

------------------------------------

creating table with all constraint type

Create table my_stu_details

S_id Number(2),

S_name Varchar2(30) Not Null, --SYS_Cn

s_mail Varchar2(30),

s_gender char(1),

s_did Number(3),

Constraint my_stu_sid_pk PRIMARY KEY (s_id),

constraint my_stu_mail_uk UNIQUE (s_mail) ,

Constraint my_stu_gen_ck CHECK (s_gender IN ('M', 'F', 'm', 'f')),

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

);

DESC my_stu_details;
------------------------------------

Name Type Nullable

------------------------------------

S_ID NUMBER(2)

S_NAME VARCHAR2(30)

S_MAIL VARCHAR2(30) Y

S_GENDER CHAR(1) Y

S_DID NUMBER(3) Y

------------------------------------

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name1' , 'name1@gmail.com' , 'm' , 60 );

Select * from my_stu_details;

Validating Primary Key

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)


values (1 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-00001: unique constraint (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (NULL, 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-01400: cannot insert NULL into (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (2 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

Validating NOT NULL Constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , NULL , 'name3@gmail.com' , 'F' , 80 );

ORA-01400: cannot insert NULL into ("HR"."MY_STU_DETAILS"."S_NAME")

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)


values (3 , 'Name3' , 'name3@gmail.com' , 'F' , 80 );

Select * from my_stu_details;

Validating Unique Key Constraint

--Duplicate Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , 'name3@gmail.com' , 'F' , 80 );

ORA-00001: unique constraint (HR.MY_STU_MAIL_UK) violated

--Null Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , null , 'M' , 70 );

Select * from my_stu_details;


Validating Check constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'j' , 70 );

ORA-02290: check constraint (HR.MY_STU_GEN_CK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'M' , 70 );

Select * from my_stu_details;

Validating Foreign Key

Select * from Departments;

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 3 );


ORA-02291: integrity constraint (HR.MY_STU_DID_FK) violated - parent key not found

Departments table : parent table

my_stu_details : Child table

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

--------------------------------------------------------

s_id s_name s_mail s_gender s_did

--------------------------------------------------------

1 name1 name1@gmail.com m 60

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 M 70

5 Name5 name5@gmail.com M 70

6 Name6 name6@gmail.com F 90

--------------------------------------------------------
Deleting the Primary key value which is referred by Foreign Key

Select * from Departments;

DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID

------------------------------------------------------------

60 IT 103 1400 <---- Delete

-- don't execute this query

--Delete From Departments

--Where Department_id = 60;

1) ON DELETE SET NULL

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

1 name1 name1@gmail.com m -
2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

2) ON DELETE SET CASCADE

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

Syntax

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE CASCADE

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE SET NULL


Constraint Related Data Dictionary Table information.

To view constraint Information

SELECT c.owner,

c.constraint_name,

c.constraint_type,

c.table_name,

c.r_constraint_name,

c.status

FROM user_constraints c

WHERE c.table_name = 'MY_STU_DETAILS';

------------------------------------------------------------------------------------

owner constraint_name constraint_type table_name r_constraint_name status

------------------------------------------------------------------------------------

HR SYS_C004023 C MY_STU_DETAILS ENABLED

HR MY_STU_GEN_CK C MY_STU_DETAILS ENABLED

HR MY_STU_SID_PK P MY_STU_DETAILS ENABLED

HR MY_STU_MAIL_UK U MY_STU_DETAILS ENABLED

HR MY_STU_DID_FK R MY_STU_DETAILS DEPT_ID_PK ENABLED


------------------------------------------------------------------------------------

To view constraint name with corresponding column name

SELECT * FROM user_cons_columns c

WHERE c.table_name = 'MY_STU_DETAILS';

-------------------------------------------------------------

owner constraint_name table_name column_name position

-------------------------------------------------------------

HR MY_STU_MAIL_UK MY_STU_DETAILS S_MAIL 1

HR MY_STU_SID_PK MY_STU_DETAILS S_ID 1

HR MY_STU_GEN_CK MY_STU_DETAILS S_GENDER

HR SYS_C004023 MY_STU_DETAILS S_NAME

HR MY_STU_DID_FK MY_STU_DETAILS S_DID 1

-------------------------------------------------------------

Creating Composite Primary Key

Creating Primary Key with more than one number of column


ALTER TABLE table_name

ADD CONSTRAINT constraint_name PRIMARY KEY(column1, column_2 , column3);

In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.

creating constraint after the table creation

ALTER TABLE table_name

ADD CONSTRAINT constraint_name CONSTRAINT_TYPE(column_name);

ALTER TABLE table_name

DROP CONSTRAINT constraint_name;

ALTER TABLE table_name

DROP PRIMARY KEY;

To drop related foreign key

ALTER TABLE table_name

DROP PRIMARY KEY CASCADE;


ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name;

Disable constraint with related foreign key constraint

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name CASCADE;

ALTER TABLE table_name

ENABLE CONSTRAINT constraint_name;

Interview Questions

What are all the type of constraint available in oracle?

Difference between PRIMARY KEY and UNIQUE key.

Difference between PRIMARY KEY ans FOREIGN KEY.

Difference between UNIQUE key and FOREIGN KEY.

Is it possible to create tow primary key in single table.

Write a syntax to create FOREIGN constraint.

How to create constraint after the table has been created?


How to enable and disable a constraint.

Which data dictionary table contains information about constraints?

Which Data Dictionary table contains information about constraint with corresponding column
name?

What is composite primary key?

Explain ON DELETE CASCADE and ON DELETE SET NULL option.

~Thanks For Reading~

Post your valuable feedback below

Posted 21st December 2014 by Unknown

1 View comments

DEC

listagg in Oracle 11g

Oracle 11gR2 listagg built-in function allows for many table columns to be displayed within a
single row, a non-first-normal form display

Syntax :
listagg(column_value,'delimiter') WITHIN GROUP(ORDER BY column_name)

--Example 1:

CREATE TABLE test_ins(empid NUMBER,product VARCHAR2(30));

BEGIN

INSERT INTO test_ins VALUES( 101,'pendrive');

INSERT INTO test_ins VALUES( 102,'toy');

INSERT INTO test_ins VALUES( 101,'ipod');

INSERT INTO test_ins VALUES( 102,'hat');

INSERT INTO test_ins VALUES( 103,'cpu');

INSERT INTO test_ins VALUES( 104,'pen');

INSERT INTO test_ins VALUES( 104,'car');

INSERT INTO test_ins VALUES( 104,'mat');

INSERT INTO test_ins VALUES( 105,'tv');

INSERT INTO test_ins VALUES( 106,'laptop');

commit;

END;

SELECT * FROM test_ins;

SELECT empid "Employee",

listagg(product,
',') within

GROUP (ORDER BY empid) "Products"

FROM test_ins

GROUP BY empid;

-->-- Result set --<--

DROP TABLE test_ins;

-->-- Example 2

select department_id "Department id", listagg(first_name,', ') WITHIN GROUP(ORDER BY


employee_id) "Employees"
FROM employees

WHERE department_id IN (10,20,30,60)

GROUP BY department_id;

-->-- Result set --<--

Posted 4th December 2014 by Unknown

0 Add a comment

NOV

Condition and Looping Statement

IF

IF ELSE

Multiple IF ELSE

LOOP

FOR LOOP

WHILE LOOP
create table test_udt(id NUMBER, salary NUMBER);

BEGIN

INSERT INTO test_udt VALUES(001,23000);

INSERT INTO test_udt VALUES(002,43000);

INSERT INTO test_udt VALUES(003,78000);

INSERT INTO test_udt VALUES(004,25000);

INSERT INTO test_udt VALUES(005,26000);

INSERT INTO test_udt VALUES(006,90000);

Commit;

END;

select * from test_udt;

IF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary
INTO v_id,v_salary

FROM test_udt

WHERE id = 1;

IF v_salary > 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

END IF;

commit;

END;

IF ELSE

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;
IF v_salary < 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

ELSE

UPDATE test_udt t

SET t.salary = v_salary+20007

WHERE t.id = v_id ;

END IF;

commit;

END;

--same example with less number of lines

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;
IF v_salary < 20000 THEN

v_salary := v_salary+10005;

ELSE

v_salary := v_salary+20007;

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

Multiple IF ELSIF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt
WHERE id = 3;

IF v_id = 1 THEN

v_salary := 1000;

dbms_output.put_line('1 inside');

ELSIF v_id = 2 THEN

v_salary := 2000;

dbms_output.put_line('2 inside');

ELSIF v_id = 3 THEN

v_salary := 3000;

dbms_output.put_line('3 inside');

ELSIF v_id = 4 THEN

v_salary := 4000;

dbms_output.put_line('4 inside');

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;


LOOP

--syntax

LOOP

--statements

--increment

--exit statement

END LOOP;

CREATE TABLE prod_details (pid VARCHAR2(3), pname VARCHAR2(30));

DECLARE

i NUMBER := 1;

x VARCHAR2(3);

BEGIN

LOOP

x := lpad(i,3,'0');

dbms_output.put_line('x value : '|| x);

INSERT INTO prod_details VALUES(i, 'Product '||i);

EXIT WHEN i >900;

i := i+1;
IF MOD(i,100) = 0 THEN

commit;

dbms_output.put_line('commit executed');

END IF;

END LOOP;

END;

SELECT * FROM prod_details ORDER BY 1;

DROP TABLE prod_details;

FOR LOOP

BEGIN

FOR I in 1..5

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

FOR LOOP - Reverse

BEGIN
FOR I in REVERSE 14..50

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

WHILE LOOP

DECLARE

i_val NUMBER:=0;

BEGIN

WHILE (i_val < 11)

LOOP

dbms_output.put_line('The value of I is '||i_val);

i_val := i_val + 1;

END LOOP;

END;

sample output:

The value of I is 0

The value of I is 1

The value of I is 2
The value of I is 3

The value of I is 4

The value of I is 5

The value of I is 6

The value of I is 7

The value of I is 8

The value of I is 9

The value of I is 10

Posted 8th November 2014 by Unknown

0 Add a comment

OCT

21

Bulk Collect

This is used for array fetches

With this you can retrieve multiple rows of data with a single round trip.

This reduces the number of context switches between the pl/sql and sql engines.

You can use bulk collect in both dynamic and static sql.

You can use bulk collect in select, fetch into and returning into clauses.

SQL engine automatically initializes and extends the collections you reference in the bulk
collect clause.

You can fetch into multiple collections with one column each.
You can use the limit clause of bulk collect to restrict the no of rows retrieved.

SELECT * FROM product_details;

-->-- Bulk collect in FETCH INTO --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

/
-->-- Bulk collect in SELECT clause --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

BEGIN

SELECT * BULK COLLECT INTO dta FROM product_details;

FOR i IN dta.FIRST .. dta.LAST LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- LIMIT in Bulk collect --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;
FETCH proddt_cur BULK COLLECT

INTO dta LIMIT 30;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Multiple fetches in INTO clause --<--

SELECT * FROM product_details;

DECLARE

TYPE alldata_typ1 IS TABLE OF product_details.p_id%TYPE;

TYPE alldata_typ2 IS TABLE OF product_details.p_name%TYPE;

dta1 alldata_typ1;

dta2 alldata_typ2;

CURSOR proddt_cur IS

SELECT p_id, p_name FROM product_details;

BEGIN

OPEN proddt_cur;
FETCH proddt_cur BULK COLLECT

INTO dta1, dta2;

CLOSE proddt_cur;

FOR i IN dta1.FIRST .. dta1.COUNT LOOP

dbms_output.put_line('Department Id : ' || dta1(i));

END LOOP;

FOR i IN dta2.FIRST .. dta2.COUNT LOOP

dbms_output.put_line('Department Name : ' || dta2(i));

END LOOP;

END;

DROP TABLE dep_details;

DROP TABLE product_details;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Ref Cursor
This is unconstrained cursor which will return different types depends upon the user input.

Ref cursors cannot be closed implicitly.

Ref cursor with return type is called strong cursor.

Ref cursor without return type is called weak cursor.

You can declare ref cursor type in package spec as well as body.

You can declare ref cursor types in local subprograms or anonymous blocks.

CREATE OR REPLACE PROCEDURE ref_c_sp(dep_det_c IN OUT SYS_REFCURSOR)

AS

BEGIN

OPEN dep_det_c

FOR

SELECT * FROM dep_details d;

END;

DECLARE

dep_det_c SYS_REFCURSOR;

tab_data dep_details%ROWTYPE;

BEGIN

ref_c_sp(dep_det_c);
LOOP

FETCH dep_det_c INTO tab_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department Name : '|| tab_data.d_name);

END LOOP;

CLOSE dep_det_c;

END;

/*sample output*/

Department Name : Admin

Department Name : HR

Department Name : Sales

Department Name : Marketing

DROP PROCEDURE ref_c_sp;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21
Cursor

SQL Private work Area where the query get passed and executed.

Types

******

Implicit(SQL)

Explicit

-->-- advanced cursor types --<--

Parametrized Cursor

Ref Cursor

Implicit

********

ORACLE implicitly opens a cursor to process each SQL statement not associated with an
explicitly declared cursor.

PL/SQL lets you refer to the most recent implicit cursor as the SQL” cursor. So, although you
cannot use the OPEN,

FETCH, and CLOSE statements to control an implicit cursor, you can still use cursor attributes to
access information

about the most recently executed SQL statement.

Cursor Stages
**************

OPEN cursor_name

FETCH (with in loop)

CLOSE cursor_name

Explicit

The set of rows returned by a query can consist of zero, one, or multiple rows,

depending on how many rows meet your search criteria. When a query returns multiple rows,

you can explicitly define a cursor to process the rows. You use three commands to control the
cursor

Cursor Attributes

*****************

%FOUND

%NOTFOUND

%ISOPEN

%ROWCOUNT

%BULK_ROWCOUNT --<-- used to handle error while using bulk collection.

%BULK_EXCEPTIONS --<-- used to handle error while using bulk collection.

Cursor Declaration

DECLARE
CURSOR <cursor_name>

IS

<SELECT statement>

BEGIN

--> some stmt

END;

Cursor Loop

Loop

While Loop

For Loop

Cursor Clauses

Return

For update

Where current of

Bulk collect

-->-- creating table

create table product_details

p_id NUMBER,

p_name VARCHAR2(30),
p_order_dt DATE

);

-->-- Inserting data

BEGIN

FOR i IN 1 .. 75 LOOP

INSERT INTO product_details VALUES (i, 'prod_name_' || i, SYSDATE + i);

END LOOP;

commit;

END;

-->-- selecting data

SELECT * FROM product_details;

---------------------------------------------

p_id p_name p_order_dt

---------------------------------------------

1 prod_name_1 10/11/2014 3:48:32 PM

2 prod_name_2 10/12/2014 3:48:32 PM

3 prod_name_3 10/13/2014 3:48:32 PM

4 prod_name_4 10/14/2014 3:48:32 PM


5 prod_name_5 10/15/2014 3:48:32 PM

6 prod_name_6 10/16/2014 3:48:32 PM

7 prod_name_7 10/17/2014 3:48:32 PM

8 prod_name_8 10/18/2014 3:48:32 PM

9 prod_name_9 10/19/2014 3:48:32 PM

10 prod_name_10 10/20/2014 3:48:32 PM

11 prod_name_11 10/21/2014 3:48:32 PM

12 prod_name_12 10/22/2014 3:48:32 PM

13 prod_name_13 10/23/2014 3:48:32 PM

14 prod_name_14 10/24/2014 3:48:32 PM

15 prod_name_15 10/25/2014 3:48:32 PM

16 prod_name_16 10/26/2014 3:48:32 PM

17 prod_name_17 10/27/2014 3:48:32 PM

18 prod_name_18 10/28/2014 3:48:32 PM

19 prod_name_19 10/29/2014 3:48:32 PM

20 prod_name_20 10/30/2014 3:48:32 PM

---------------------------------------------

----------------------------------------------

Implicit Cursor

----------------------------------------------

--will update soon


----------------------------------------------

Explicit Cursor

----------------------------------------------

**********************************************

Processing cursor data by using LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND; --<-- if next record not found means control will
come out from the loop

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;
END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||


' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

EXIT WHEN prod_detail_cur%FOUND; --<-- if next record found means control will come
out from the loop

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;


dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor Already closed


DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

-->-- CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE
dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor closed

**********************************************

Processing cursor data by using WHILE LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;
--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

OPEN prod_detail_cur;

FETCH prod_detail_cur

INTO all_data;

WHILE prod_detail_cur%FOUND LOOP

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

FETCH prod_detail_cur

INTO all_data;

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )


************************************************************

Processing cursor data by using FOR LOOP - CURSOR FOR LOOP

************************************************************

DECLARE

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

FOR i IN prod_detail_cur

LOOP

dbms_output.put_line('Product id : ' || i.p_id ||

' Product Name : ' || i.p_name ||

' ( Orderd on : ' || TRIM(i.p_order_dt) || ' )');

END LOOP;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )


Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

Parameterized Cursor

*********************

This was used when you are going to use the cursor in more than one place with different
values for the same where clause.

Cursor parameters must be in mode.

Cursor parameters may have default values.

The scope of cursor parameter is within the select statement.

CREATE TABLE dep_details(d_id NUMBER,d_name VARCHAR2(30), location_id NUMBER);

BEGIN

INSRT INTO dep_details VALUES(001,'Admin',1010);

INSRT INTO dep_details VALUES(002,'HR',1010);

INSRT INTO dep_details VALUES(003,'Sales',1020);

INSRT INTO dep_details VALUES(004,'Marketing',1020);

commit;

END;
SELECT * FROM dep_details;

----------------------------

d_id d_name location_id

----------------------------

1 Admin 1010

2 HR 1010

3 Sales 1020

4 Marketing 1020

----------------------------

DECLARE

-->--Declaring parameterized cursor

CURSOR dep_det_c(p_location_id NUMBER) IS

SELECT * FROM dep_details d WHERE d.location_id = p_location_id;

all_data dep_details%ROWTYPE;

BEGIN

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

OPEN dep_det_c(1010);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;


dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

-->-- opening same cursor with different input value

OPEN dep_det_c(1020);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

END;

/*sample output*/

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
Department id : 1 Department Name : Admin

Department id : 2 Department Name : HR

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 3 Department Name : Sales

Department id : 4 Department Name : Marketing

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Handling Exception

Error Handling in oracle

ERROR

Any departure from the expected behavior of the system or program,

which stops the working of the system is an error.

Types : compile time error

Run time error

EXCEPTION

Any error or problem which one can handle and continue to work normally.
Handling Exception

When exception is raised, control passes to the exception section of the block.

i.e. EXCEPTION

WHEN name_of_exception THEN

Types : Pre Defined Exceptions

User Defined Exceptions

Predefined Exception

*********************

Oracle has predefined several exceptions that correspond to the most common oracle errors.

------------------------------------------------------------------------

Exception Oracle Error SQL Code Value

------------------------------------------------------------------------

ZERO_DIVIDE ORA-01476 -1476

NO_DATA_FOUND ORA-01403 +100

DUP_VAL_ON_INDEX ORA-00001 -1

TOO_MANY_ROWS ORA-01422 -1422

VALUE_ERROR ORA-06502 -6502


CURSOR_ALREADY_OPEN ORA-06511 -6511

OTHERS

------------------------------------------------------------------------

-->-- ZERO_DIVIDE --<--

Your program attempts to divide a number by zero.

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN ZERO_DIVIDE THEN

dbms_output.put_line('Divisor is equal to zero');

END;

-->-- NO_DATA_FOUND --<--

Single row SELECT returned no rows or your program referenced a deleted element in a nested
table

or an uninitialized element in an associative array (index-by table).


CREATE TABLE test_tb(id NUMBER PRIMARY KEY);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN NO_DATA_FOUND THEN

dbms_output.put_line('There is no data inside the table');

END;

-->-- DUP_VAL_ON_INDEX --<--

A program attempted to insert duplicate values in a column that is constrained by a unique


index.

INSERT INTO test_tb VALUES (1);

INSERT INTO test_tb VALUES (2);

commit;

BEGIN

INSERT INTO test_tb VALUES (2);

EXCEPTION

WHEN DUP_VAL_ON_INDEX THEN


dbms_output.put_line('Duplicate values are not allowed');

END;

-->-- TOO_MANY_ROWS --<--

Single row SELECT returned multiple rows.

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN TOO_MANY_ROWS THEN

dbms_output.put_line('Query returning more than one row');

END;

DROP TABLE test_tb;

-->-- VALUE_ERROR --<--

An arithmetic, conversion, truncation, or size constraint error occurred.


DECLARE

num1 NUMBER(2);

BEGIN

num1 := 345;

EXCEPTION

WHEN VALUE_ERROR THEN

dbms_output.put_line('check the size of the variable');

END;

-->-- CURSOR_ALREADY_OPEN --<--

A program attempted to open an already opened cursor.

CREATE TABLE emp(id NUMBER, name VARCHAR2(30));

BEGIN

INSERT INTO emp VALUES(1,'Name1');

INSERT INTO emp VALUES(2,'Name2');

INSERT INTO emp VALUES(3,'Name3');

INSERT INTO emp VALUES(4,'Name4');

COMMIT;

END;
SELECT * FROM emp;

DECLARE

cursor emp_c IS

SELECT * FROM emp;

all_data emp%ROWTYPE;

BEGIN

OPEN emp_c;

OPEN emp_c;

NULL;

CLOSE emp_c;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

END;

DROP TABLE emp;

-->-- OTHERS --<--

DECLARE

v_result NUMBER;

BEGIN
SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

WHEN OTHERS THEN

dbms_output.put_line('Some other error ' || SQLERRM);

END;

User Defined Exception

**********************

A user-defined exception is an error that is defined by the programmer.

User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,

exceptions have a type EXCEPTION and scope.

DECLARE

v_gender CHAR := '&gender';

gender_ex EXCEPTION;

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE gender_ex;

END IF;
dbms_output.put_line('Gender : '||v_gender);

EXCEPTION

WHEN gender_ex THEN

dbms_output.put_line('Please Enter valid gender');

END;

create table test_insert (id NUMBER, Name VARCHAR2(30));

DECLARE

abort_ex EXCEPTION;

BEGIN

FOR i IN 1..100

LOOP

BEGIN

IF mod(i,10)=0 THEN

RAISE abort_ex;

END IF;

INSERT INTO test_insert VALUES(i, 'Name'||i);

EXCEPTION

WHEN abort_ex THEN

NULL;

END;

END LOOP;

COMMIT;
END;

SELECT * FROM test_insert;

DROP TABLE test_insert;

SQLERRM and SQLCODE

********************

SQLCODE returns the current error code, and SQLERRM returns the current error message
text;

For user-defined exception SQLCODE returns 1 and SQLERRM returns “user-defined


exception”.

SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.

CREATE TABLE test_tb (id NUMBER);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

dbms_output.put_line(v_id);

EXCEPTION

WHEN OTHERS THEN


dbms_output.put_line('SQLERRM : ' || SQLERRM);

dbms_output.put_line('SQLCODE : ' || SQLCODE);

END;

/*sample output*/

SQLERRM : ORA-01403: no data found

SQLCODE : 100

DROP TABLE test_tb;

PRAGMA EXCEPTION_INIT

*********************

Using this you can associate a named exception with a particular oracle error.

This gives you the ability to trap this error specifically, rather than via an OTHERS handler.

Syntax:

PRAGMA EXCEPTION_INIT(exception_name, oracle_error_number);

DECLARE

v_result NUMBER;

PRAGMA EXCEPTION_INIT(Invalid, -1476);


BEGIN

SELECT 453 / 0 INTO v_result FROM dual;

dbms_output.put_line('Result : ' || v_result);

EXCEPTION

WHEN INVALID THEN

dbms_output.put_line('Invalid Exception');

END;

RAISE_APPLICATION_ERROR

************************

You can use this built-in function to create your own error messages, which can be more
descriptive than named exceptions.

Error Number :

Oracle Error Range : From -00000 to -19999

User Error Range : From -20000 to -20999

DECLARE

v_gender CHAR := '&gender';

BEGIN
IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE_APPLICATION_ERROR(-20003, 'Enter valid gender');

END IF;

dbms_output.put_line('Gender : ' || v_gender);

END;

Posted 21st October 2014 by Unknown

1 View comments

Loading

Dynamic Views theme. Powered by Blogger.

Oracle sql & Pl/sql

search

Home Sql and pl/sql Sql Interview Questions

JUL

20

INLINE view in Oracle with 12c New Features

Named sub Query in FROM clause is call it as INLINE VIEW.


Oracle process a inline view faster than sub query

Inline View in Oracle

--Query to display all the employees who are all getting salary more than their department
average salary

SELECT First_name

, last_name

, salary

, department_id

FROM employees a , ( SELECT b.department_id

, AVG(b.salary) avg_sal

FROM employees b

GROUP BY b.department_id

)b

WHERE a.department_id = b.department_id

AND a.salary > b.avg_salary;

Display all the customer who have placed more number of orders by using INLINE view

CREATE TABLE customer_order_det_tb

( custm_id NUMBER ,

custm_nm VARCHAR2(30) ,
order_dt DATE DEFAULT SYSDATE ,

ttl_amt NUMBER(7,2)

);

BEGIN

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '11-Jul-15' , 45000.00);

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '14-Jul-15' , 27000.00);

INSERT INTO customer_order_det_tb VALUES(101, 'Raja' , '13-Jul-15' , 17000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 34000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 38000.00);

COMMIT;

END;

SELECT c.*

FROM customer_order_det_tb c;

--------------------------------------------

custm_id custm_nm order_dt ttl_amt

--------------------------------------------

100 Murugappan 7/11/2015 45000.00

100 Murugappan 7/14/2015 27000.00

101 Raja 7/13/2015 17000.00

102 Ramesh 7/15/2015 34000.00

102 Ramesh 7/15/2015 38000.00

--------------------------------------------
--Writing a Quer to display all the customer who have placed maximum number of order

--Query #1 for inline view

SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC;

--------------------------------

custm_id custm_nm total_odr

--------------------------------

100 Murugappan 2

102 Ramesh 2

101 Raja 1

--------------------------------

--Query #2 for inline view

SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm;

----------
total_odr

----------

----------

Inline view to find all the customers who have placed maximum number of orders

/****************************************

Syntax

SELECT * FROM <query1> x, <query2> y

WHERE contition;

****************************************/

SELECT query1.* FROM

( SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC

) query1,

( SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm

) query2

WHERE query1.total_odr = query2.total_odr;


-------------------------------

custm_id custm_nm total_odr

-------------------------------

100 Murugappan 2

102 Ramesh 2

-------------------------------

DROP TABLE customer_order_det_tb;

--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT

SELECT first_name, salary

FROM ( SELECT first_name, salary

FROM employees e

WHERE job_id NOT IN ('SALESMAN','PRESIDENT')

ORDER BY salary DESC

WHERE ROWNUM < 4;

New Oracle 12c Inline view Syntax


LATERAL clause for In-line views

Allows for columns in the inline view to be accessed!!

Example :

--in 11g

SELECT * FROM employees e, (

SELECT *

FROM departments d

WHERE e.department_id = d.department_id);

ORA-0090: "E"."DEPARTMENT_ID": Invalid Identifier

--in 12c

SELECT * FROM employees e, LATERAL(

SELECT *

FROM departments d

WHERE e.department_id = d.department_id

);

--in 11g

WITH t

AS
( SELECT LEVEL a

FROM dual

CONNECT BY LEVEL <= 30)

SELECT *

FROM t, (SELECT *

FROM employees

WHERE department_id = t.a

);

ORA-00904: "T"."A": invalid Identifier

--in 12c

WITH t

AS

(SELECT LEVEL a FROM dual CONNECT BY LEVEL <= 30)

SELECT * FROM t,

LATERAL(SELECT *

FROM employees

WHERE department_id = t.a);

Hope you have enjoyed this little article

Feed backs are always Welcome :) (:

Posted 20th July 2015 by Unknown


0 Add a comment

JAN

23

Salary Related Questions in Oracle

--creating table

CREATE TABLE employee_data

eid NUMBER(4),

ename VARCHAR2(30),

depno NUMBER(3),

salary NUMBER(8)

);

BEGIN

--Inserting records

INSERT INTO employee_data VALUES(1000,'Name01',90,30000);

INSERT INTO employee_data VALUES(1001,'Name02',90,6000);


INSERT INTO employee_data VALUES(1002,'Name03',90,23000);

INSERT INTO employee_data VALUES(1003,'Name04',60,35000);

INSERT INTO employee_data VALUES(1004,'Name05',60,60000);

INSERT INTO employee_data VALUES(1005,'Name06',60,30000);

INSERT INTO employee_data VALUES(1006,'Name07',80,36000);

INSERT INTO employee_data VALUES(1007,'Name08',80,29000);

INSERT INTO employee_data VALUES(1008,'Name09',80,37000);

INSERT INTO employee_data VALUES(1009,'Name10',80,41000);

COMMIT;

END;

SELECT * FROM employee_data

ORDER BY salary DESC;

--query to find maximum salary from employee_data table

SELECT MAX(salary) FROM employee_data;

--query to find minimum salary from employee_data table

SELECT MIN(salary) FROM employee_data;

--query to find second maximum salary from employee_data table


SELECT MAX(salary)

FROM employee_data

WHERE salary NOT IN (SELECT MAX(salary)

FROM employee_data);

--query to select 5th maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= 5);

--query to select nth maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= &n);


--query to select all the details of the employee whose getting nth maximum salary

SELECT *

FROM (SELECT emp.*,

rownum rn

FROM (SELECT *

FROM employee_data

ORDER BY salary DESC) emp)

WHERE rn = 9;

--same query using row_numbr( ) function

SELECT *

FROM (SELECT emp.*,

row_number() over(ORDER BY salary) rank

FROM employee_data emp)

WHERE rank = 9;

--same query using rank( ) function

SELECT *

FROM (SELECT emp.*,

rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)


WHERE rank = 4;

--same query using dense_rank( ) function

SELECT *

FROM (SELECT emp.*,

dense_rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--query to display display maximum salary in all the department

SELECT e.depno "Department id",

MAX(salary) "Maximum Salary"

FROM employee_data e

GROUP BY e.depno;

--query to display all the employees who are all getting salary more than average salary of the
company

SELECT e.* FROM employee_data e

WHERE salary > (SELECT AVG(salary) FROM employee_data);

--query to display all the employees who are all getting salary more than their department
average salary
SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE department_id = OUT.department_id);

--query to display all the employees who are all getting salary more than their manager salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE employee_id = OUT.manager_id);

Documented By : Murugappan Annamalai


Posted on : 23-Jan-15 16:34:00 IST.

Hope you have enjoyed this little article

Feed backs are always welcome :)

Posted 23rd January 2015 by Unknown

7 View comments

JAN

22

Why prefer COALESCE over NVL

Documented By : Nimish Garg

I prefer using "COALESCE" over "NVL" is some of the scenarios. Last week One of my friend
asked me what is the advantage of using "COALESCE" where we can simply use "NVL". I simply
gave him the reply from Oracle Docs i.e. NVL lets you replace null (returned as a blank) with a
string in the results of a query and COALESCE returns the first non-null expr in the expression list.
Oracle Database uses short-circuit evaluation with "COALESCE".

He replied that he knows the difference, he knows that "COALESCE" can take multiple arguments
and so on. He was more interested in understanding "short-circuit evaluation" of "COALESCE"
and the scenarios where I prefer using "COALESCE" over "NVL".

To make him understand I created following function which takes One second in every execution
and simply returns '--null--' and executed 2 very similar queries one with NVL and other with
COALESCE.
SQL> create or replace function f_null return varchar2

2 is

3 begin

4 dbms_lock.sleep(1);

5 return '--null--';

6 end;

7 /

Function created.

Following are the queries which I used to demonstrate that NVL evaluates both arguments even
if the second argument is not used and COALESCE uses short-circuit evaluation i.e. it only
evaluates the arguments only if they are needed.

SQL> select e.empno, e.ename ename, nvl(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE


7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.

Elapsed: 00:00:14.01

SQL> select e.empno, e.ename ename, coalesce(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE


7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.

Elapsed: 00:00:01.01

Here we can see easily that the first query with NVL took 14+ seconds, one second for each
record even if the "f_null" value was used only in one record. On the contrary as mentioned in
Oracle Documentation "COALESCE" uses its "short-circuit evaluation" and "f_null" was called
only once and so second query took only One Second. "COALESCE" is certainly use less resources
than NVL.

Posted 22nd January 2015 by Unknown

0 Add a comment

DEC

21
Constraints

It Enforce Rule On Table

We can create constraint at the time of Creating Table

1. Column Level Declaration

2. Table Level Declaration

1. We can provide own name.

Format : [part_of_project_name-table_name-column_name-constraint_type]

Example : gmind_emp_id_pk _uk _ck _f

2. system name name

Format : sys_cn

Example : SYS_C405323

We can create constraint after the table has been created

Types
Primary Key

Not allowed Null value

Not allowed you to enter duplicate value

Ex : Employee_id, Student_id

Unique Key

allowed Null value

Not allowed you to enter duplicate value

Ex : Contact_no, email

Foreign Key

It will allowed you to enter NULL and Duplicate value.

c1(pk) : 1 2 3

c2(f) : 1 1 2 3 4 Not allowed

Allowed you to enter duplicate value and null value


Not Null

It will not allowed you to enter null value

Check

You can check your own condition

Simple Table for understanding

------------------------------------

Duplicate NULL

------------------------------------

Primary Key X X

Unique Key X Allowed

Foreign Key Allowed Allowed

------------------------------------

creating table with all constraint type

Create table my_stu_details


(

S_id Number(2),

S_name Varchar2(30) Not Null, --SYS_Cn

s_mail Varchar2(30),

s_gender char(1),

s_did Number(3),

Constraint my_stu_sid_pk PRIMARY KEY (s_id),

constraint my_stu_mail_uk UNIQUE (s_mail) ,

Constraint my_stu_gen_ck CHECK (s_gender IN ('M', 'F', 'm', 'f')),

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

);

DESC my_stu_details;

------------------------------------

Name Type Nullable

------------------------------------

S_ID NUMBER(2)

S_NAME VARCHAR2(30)

S_MAIL VARCHAR2(30) Y

S_GENDER CHAR(1) Y

S_DID NUMBER(3) Y

------------------------------------
Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name1' , 'name1@gmail.com' , 'm' , 60 );

Select * from my_stu_details;

Validating Primary Key

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-00001: unique constraint (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (NULL, 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-01400: cannot insert NULL into (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (2 , 'name2' , 'name2@gmail.com' , 'F' , 90 );


Select * from my_stu_details;

Validating NOT NULL Constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , NULL , 'name3@gmail.com' , 'F' , 80 );

ORA-01400: cannot insert NULL into ("HR"."MY_STU_DETAILS"."S_NAME")

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , 'Name3' , 'name3@gmail.com' , 'F' , 80 );

Select * from my_stu_details;

Validating Unique Key Constraint

--Duplicate Check
Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , 'name3@gmail.com' , 'F' , 80 );

ORA-00001: unique constraint (HR.MY_STU_MAIL_UK) violated

--Null Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , null , 'M' , 70 );

Select * from my_stu_details;

Validating Check constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'j' , 70 );

ORA-02290: check constraint (HR.MY_STU_GEN_CK) violated


Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'M' , 70 );

Select * from my_stu_details;

Validating Foreign Key

Select * from Departments;

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 3 );

ORA-02291: integrity constraint (HR.MY_STU_DID_FK) violated - parent key not found

Departments table : parent table

my_stu_details : Child table

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 90 );


Select * from my_stu_details;

--------------------------------------------------------

s_id s_name s_mail s_gender s_did

--------------------------------------------------------

1 name1 name1@gmail.com m 60

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 M 70

5 Name5 name5@gmail.com M 70

6 Name6 name6@gmail.com F 90

--------------------------------------------------------

Deleting the Primary key value which is referred by Foreign Key

Select * from Departments;

DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID

------------------------------------------------------------

60 IT 103 1400 <---- Delete


-- don't execute this query

--Delete From Departments

--Where Department_id = 60;

1) ON DELETE SET NULL

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

1 name1 name1@gmail.com m -

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

2) ON DELETE SET CASCADE

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------
6 Name6 name6@gmail.com F 90

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

Syntax

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE CASCADE

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE SET NULL

Constraint Related Data Dictionary Table information.

To view constraint Information

SELECT c.owner,

c.constraint_name,

c.constraint_type,

c.table_name,
c.r_constraint_name,

c.status

FROM user_constraints c

WHERE c.table_name = 'MY_STU_DETAILS';

------------------------------------------------------------------------------------

owner constraint_name constraint_type table_name r_constraint_name status

------------------------------------------------------------------------------------

HR SYS_C004023 C MY_STU_DETAILS ENABLED

HR MY_STU_GEN_CK C MY_STU_DETAILS ENABLED

HR MY_STU_SID_PK P MY_STU_DETAILS ENABLED

HR MY_STU_MAIL_UK U MY_STU_DETAILS ENABLED

HR MY_STU_DID_FK R MY_STU_DETAILS DEPT_ID_PK ENABLED

------------------------------------------------------------------------------------

To view constraint name with corresponding column name

SELECT * FROM user_cons_columns c

WHERE c.table_name = 'MY_STU_DETAILS';

-------------------------------------------------------------

owner constraint_name table_name column_name position


-------------------------------------------------------------

HR MY_STU_MAIL_UK MY_STU_DETAILS S_MAIL 1

HR MY_STU_SID_PK MY_STU_DETAILS S_ID 1

HR MY_STU_GEN_CK MY_STU_DETAILS S_GENDER

HR SYS_C004023 MY_STU_DETAILS S_NAME

HR MY_STU_DID_FK MY_STU_DETAILS S_DID 1

-------------------------------------------------------------

Creating Composite Primary Key

Creating Primary Key with more than one number of column

ALTER TABLE table_name

ADD CONSTRAINT constraint_name PRIMARY KEY(column1, column_2 , column3);

In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.

creating constraint after the table creation

ALTER TABLE table_name

ADD CONSTRAINT constraint_name CONSTRAINT_TYPE(column_name);


ALTER TABLE table_name

DROP CONSTRAINT constraint_name;

ALTER TABLE table_name

DROP PRIMARY KEY;

To drop related foreign key

ALTER TABLE table_name

DROP PRIMARY KEY CASCADE;

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name;

Disable constraint with related foreign key constraint

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name CASCADE;

ALTER TABLE table_name


ENABLE CONSTRAINT constraint_name;

Interview Questions

What are all the type of constraint available in oracle?

Difference between PRIMARY KEY and UNIQUE key.

Difference between PRIMARY KEY ans FOREIGN KEY.

Difference between UNIQUE key and FOREIGN KEY.

Is it possible to create tow primary key in single table.

Write a syntax to create FOREIGN constraint.

How to create constraint after the table has been created?

How to enable and disable a constraint.

Which data dictionary table contains information about constraints?

Which Data Dictionary table contains information about constraint with corresponding column
name?

What is composite primary key?

Explain ON DELETE CASCADE and ON DELETE SET NULL option.

~Thanks For Reading~

Post your valuable feedback below


Posted 21st December 2014 by Unknown

1 View comments

DEC

listagg in Oracle 11g

Oracle 11gR2 listagg built-in function allows for many table columns to be displayed within a
single row, a non-first-normal form display

Syntax :

listagg(column_value,'delimiter') WITHIN GROUP(ORDER BY column_name)

--Example 1:

CREATE TABLE test_ins(empid NUMBER,product VARCHAR2(30));

BEGIN

INSERT INTO test_ins VALUES( 101,'pendrive');

INSERT INTO test_ins VALUES( 102,'toy');

INSERT INTO test_ins VALUES( 101,'ipod');

INSERT INTO test_ins VALUES( 102,'hat');


INSERT INTO test_ins VALUES( 103,'cpu');

INSERT INTO test_ins VALUES( 104,'pen');

INSERT INTO test_ins VALUES( 104,'car');

INSERT INTO test_ins VALUES( 104,'mat');

INSERT INTO test_ins VALUES( 105,'tv');

INSERT INTO test_ins VALUES( 106,'laptop');

commit;

END;

SELECT * FROM test_ins;

SELECT empid "Employee",

listagg(product,

',') within

GROUP (ORDER BY empid) "Products"

FROM test_ins

GROUP BY empid;

-->-- Result set --<--


DROP TABLE test_ins;

-->-- Example 2

select department_id "Department id", listagg(first_name,', ') WITHIN GROUP(ORDER BY


employee_id) "Employees"

FROM employees

WHERE department_id IN (10,20,30,60)

GROUP BY department_id;

-->-- Result set --<--

Posted 4th December 2014 by Unknown

0 Add a comment
NOV

Condition and Looping Statement

IF

IF ELSE

Multiple IF ELSE

LOOP

FOR LOOP

WHILE LOOP

create table test_udt(id NUMBER, salary NUMBER);

BEGIN

INSERT INTO test_udt VALUES(001,23000);

INSERT INTO test_udt VALUES(002,43000);

INSERT INTO test_udt VALUES(003,78000);

INSERT INTO test_udt VALUES(004,25000);

INSERT INTO test_udt VALUES(005,26000);

INSERT INTO test_udt VALUES(006,90000);

Commit;
END;

select * from test_udt;

IF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 1;

IF v_salary > 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

END IF;

commit;

END;
/

IF ELSE

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

ELSE

UPDATE test_udt t

SET t.salary = v_salary+20007

WHERE t.id = v_id ;

END IF;

commit;

END;

/
--same example with less number of lines

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

v_salary := v_salary+10005;

ELSE

v_salary := v_salary+20007;

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

/
select * from test_udt;

Multiple IF ELSIF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 3;

IF v_id = 1 THEN

v_salary := 1000;

dbms_output.put_line('1 inside');

ELSIF v_id = 2 THEN

v_salary := 2000;

dbms_output.put_line('2 inside');

ELSIF v_id = 3 THEN

v_salary := 3000;

dbms_output.put_line('3 inside');

ELSIF v_id = 4 THEN


v_salary := 4000;

dbms_output.put_line('4 inside');

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

LOOP

--syntax

LOOP

--statements

--increment

--exit statement

END LOOP;
CREATE TABLE prod_details (pid VARCHAR2(3), pname VARCHAR2(30));

DECLARE

i NUMBER := 1;

x VARCHAR2(3);

BEGIN

LOOP

x := lpad(i,3,'0');

dbms_output.put_line('x value : '|| x);

INSERT INTO prod_details VALUES(i, 'Product '||i);

EXIT WHEN i >900;

i := i+1;

IF MOD(i,100) = 0 THEN

commit;

dbms_output.put_line('commit executed');

END IF;

END LOOP;

END;

SELECT * FROM prod_details ORDER BY 1;

DROP TABLE prod_details;


FOR LOOP

BEGIN

FOR I in 1..5

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

FOR LOOP - Reverse

BEGIN

FOR I in REVERSE 14..50

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

WHILE LOOP

DECLARE

i_val NUMBER:=0;

BEGIN
WHILE (i_val < 11)

LOOP

dbms_output.put_line('The value of I is '||i_val);

i_val := i_val + 1;

END LOOP;

END;

sample output:

The value of I is 0

The value of I is 1

The value of I is 2

The value of I is 3

The value of I is 4

The value of I is 5

The value of I is 6

The value of I is 7

The value of I is 8

The value of I is 9

The value of I is 10

Posted 8th November 2014 by Unknown

0 Add a comment
OCT

21

Bulk Collect

This is used for array fetches

With this you can retrieve multiple rows of data with a single round trip.

This reduces the number of context switches between the pl/sql and sql engines.

You can use bulk collect in both dynamic and static sql.

You can use bulk collect in select, fetch into and returning into clauses.

SQL engine automatically initializes and extends the collections you reference in the bulk
collect clause.

You can fetch into multiple collections with one column each.

You can use the limit clause of bulk collect to restrict the no of rows retrieved.

SELECT * FROM product_details;

-->-- Bulk collect in FETCH INTO --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;
CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Bulk collect in SELECT clause --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

BEGIN

SELECT * BULK COLLECT INTO dta FROM product_details;

FOR i IN dta.FIRST .. dta.LAST LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;
END;

-->-- LIMIT in Bulk collect --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta LIMIT 30;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

/
-->-- Multiple fetches in INTO clause --<--

SELECT * FROM product_details;

DECLARE

TYPE alldata_typ1 IS TABLE OF product_details.p_id%TYPE;

TYPE alldata_typ2 IS TABLE OF product_details.p_name%TYPE;

dta1 alldata_typ1;

dta2 alldata_typ2;

CURSOR proddt_cur IS

SELECT p_id, p_name FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta1, dta2;

CLOSE proddt_cur;

FOR i IN dta1.FIRST .. dta1.COUNT LOOP

dbms_output.put_line('Department Id : ' || dta1(i));

END LOOP;

FOR i IN dta2.FIRST .. dta2.COUNT LOOP

dbms_output.put_line('Department Name : ' || dta2(i));

END LOOP;
END;

DROP TABLE dep_details;

DROP TABLE product_details;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Ref Cursor

This is unconstrained cursor which will return different types depends upon the user input.

Ref cursors cannot be closed implicitly.

Ref cursor with return type is called strong cursor.

Ref cursor without return type is called weak cursor.

You can declare ref cursor type in package spec as well as body.

You can declare ref cursor types in local subprograms or anonymous blocks.

CREATE OR REPLACE PROCEDURE ref_c_sp(dep_det_c IN OUT SYS_REFCURSOR)

AS
BEGIN

OPEN dep_det_c

FOR

SELECT * FROM dep_details d;

END;

DECLARE

dep_det_c SYS_REFCURSOR;

tab_data dep_details%ROWTYPE;

BEGIN

ref_c_sp(dep_det_c);

LOOP

FETCH dep_det_c INTO tab_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department Name : '|| tab_data.d_name);

END LOOP;

CLOSE dep_det_c;

END;

/*sample output*/
Department Name : Admin

Department Name : HR

Department Name : Sales

Department Name : Marketing

DROP PROCEDURE ref_c_sp;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Cursor

SQL Private work Area where the query get passed and executed.

Types

******

Implicit(SQL)

Explicit

-->-- advanced cursor types --<--

Parametrized Cursor
Ref Cursor

Implicit

********

ORACLE implicitly opens a cursor to process each SQL statement not associated with an
explicitly declared cursor.

PL/SQL lets you refer to the most recent implicit cursor as the SQL” cursor. So, although you
cannot use the OPEN,

FETCH, and CLOSE statements to control an implicit cursor, you can still use cursor attributes to
access information

about the most recently executed SQL statement.

Cursor Stages

**************

OPEN cursor_name

FETCH (with in loop)

CLOSE cursor_name

Explicit

The set of rows returned by a query can consist of zero, one, or multiple rows,

depending on how many rows meet your search criteria. When a query returns multiple rows,

you can explicitly define a cursor to process the rows. You use three commands to control the
cursor
Cursor Attributes

*****************

%FOUND

%NOTFOUND

%ISOPEN

%ROWCOUNT

%BULK_ROWCOUNT --<-- used to handle error while using bulk collection.

%BULK_EXCEPTIONS --<-- used to handle error while using bulk collection.

Cursor Declaration

DECLARE

CURSOR <cursor_name>

IS

<SELECT statement>

BEGIN

--> some stmt

END;

Cursor Loop

Loop

While Loop
For Loop

Cursor Clauses

Return

For update

Where current of

Bulk collect

-->-- creating table

create table product_details

p_id NUMBER,

p_name VARCHAR2(30),

p_order_dt DATE

);

-->-- Inserting data

BEGIN

FOR i IN 1 .. 75 LOOP

INSERT INTO product_details VALUES (i, 'prod_name_' || i, SYSDATE + i);

END LOOP;

commit;
END;

-->-- selecting data

SELECT * FROM product_details;

---------------------------------------------

p_id p_name p_order_dt

---------------------------------------------

1 prod_name_1 10/11/2014 3:48:32 PM

2 prod_name_2 10/12/2014 3:48:32 PM

3 prod_name_3 10/13/2014 3:48:32 PM

4 prod_name_4 10/14/2014 3:48:32 PM

5 prod_name_5 10/15/2014 3:48:32 PM

6 prod_name_6 10/16/2014 3:48:32 PM

7 prod_name_7 10/17/2014 3:48:32 PM

8 prod_name_8 10/18/2014 3:48:32 PM

9 prod_name_9 10/19/2014 3:48:32 PM

10 prod_name_10 10/20/2014 3:48:32 PM

11 prod_name_11 10/21/2014 3:48:32 PM

12 prod_name_12 10/22/2014 3:48:32 PM

13 prod_name_13 10/23/2014 3:48:32 PM

14 prod_name_14 10/24/2014 3:48:32 PM

15 prod_name_15 10/25/2014 3:48:32 PM


16 prod_name_16 10/26/2014 3:48:32 PM

17 prod_name_17 10/27/2014 3:48:32 PM

18 prod_name_18 10/28/2014 3:48:32 PM

19 prod_name_19 10/29/2014 3:48:32 PM

20 prod_name_20 10/30/2014 3:48:32 PM

---------------------------------------------

----------------------------------------------

Implicit Cursor

----------------------------------------------

--will update soon

----------------------------------------------

Explicit Cursor

----------------------------------------------

**********************************************

Processing cursor data by using LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration
CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND; --<-- if next record not found means control will
come out from the loop

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )


DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

EXIT WHEN prod_detail_cur%FOUND; --<-- if next record found means control will come
out from the loop

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )


DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');


END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor Already closed

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;
LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

-->-- CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )


Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor closed

**********************************************

Processing cursor data by using WHILE LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

OPEN prod_detail_cur;

FETCH prod_detail_cur

INTO all_data;

WHILE prod_detail_cur%FOUND LOOP

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||


' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

FETCH prod_detail_cur

INTO all_data;

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

************************************************************

Processing cursor data by using FOR LOOP - CURSOR FOR LOOP

************************************************************

DECLARE

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN
FOR i IN prod_detail_cur

LOOP

dbms_output.put_line('Product id : ' || i.p_id ||

' Product Name : ' || i.p_name ||

' ( Orderd on : ' || TRIM(i.p_order_dt) || ' )');

END LOOP;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

Parameterized Cursor

*********************

This was used when you are going to use the cursor in more than one place with different
values for the same where clause.

Cursor parameters must be in mode.

Cursor parameters may have default values.


The scope of cursor parameter is within the select statement.

CREATE TABLE dep_details(d_id NUMBER,d_name VARCHAR2(30), location_id NUMBER);

BEGIN

INSRT INTO dep_details VALUES(001,'Admin',1010);

INSRT INTO dep_details VALUES(002,'HR',1010);

INSRT INTO dep_details VALUES(003,'Sales',1020);

INSRT INTO dep_details VALUES(004,'Marketing',1020);

commit;

END;

SELECT * FROM dep_details;

----------------------------

d_id d_name location_id

----------------------------

1 Admin 1010

2 HR 1010

3 Sales 1020

4 Marketing 1020

----------------------------
DECLARE

-->--Declaring parameterized cursor

CURSOR dep_det_c(p_location_id NUMBER) IS

SELECT * FROM dep_details d WHERE d.location_id = p_location_id;

all_data dep_details%ROWTYPE;

BEGIN

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

OPEN dep_det_c(1010);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

-->-- opening same cursor with different input value

OPEN dep_det_c(1020);

LOOP

FETCH dep_det_c
INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

END;

/*sample output*/

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 1 Department Name : Admin

Department id : 2 Department Name : HR

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 3 Department Name : Sales

Department id : 4 Department Name : Marketing

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Posted 21st October 2014 by Unknown

0 Add a comment
OCT

21

Handling Exception

Error Handling in oracle

ERROR

Any departure from the expected behavior of the system or program,

which stops the working of the system is an error.

Types : compile time error

Run time error

EXCEPTION

Any error or problem which one can handle and continue to work normally.

Handling Exception

When exception is raised, control passes to the exception section of the block.

i.e. EXCEPTION

WHEN name_of_exception THEN

Types : Pre Defined Exceptions

User Defined Exceptions


Predefined Exception

*********************

Oracle has predefined several exceptions that correspond to the most common oracle errors.

------------------------------------------------------------------------

Exception Oracle Error SQL Code Value

------------------------------------------------------------------------

ZERO_DIVIDE ORA-01476 -1476

NO_DATA_FOUND ORA-01403 +100

DUP_VAL_ON_INDEX ORA-00001 -1

TOO_MANY_ROWS ORA-01422 -1422

VALUE_ERROR ORA-06502 -6502

CURSOR_ALREADY_OPEN ORA-06511 -6511

OTHERS

------------------------------------------------------------------------

-->-- ZERO_DIVIDE --<--

Your program attempts to divide a number by zero.

DECLARE

v_result NUMBER;
BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN ZERO_DIVIDE THEN

dbms_output.put_line('Divisor is equal to zero');

END;

-->-- NO_DATA_FOUND --<--

Single row SELECT returned no rows or your program referenced a deleted element in a nested
table

or an uninitialized element in an associative array (index-by table).

CREATE TABLE test_tb(id NUMBER PRIMARY KEY);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN NO_DATA_FOUND THEN

dbms_output.put_line('There is no data inside the table');

END;
-->-- DUP_VAL_ON_INDEX --<--

A program attempted to insert duplicate values in a column that is constrained by a unique


index.

INSERT INTO test_tb VALUES (1);

INSERT INTO test_tb VALUES (2);

commit;

BEGIN

INSERT INTO test_tb VALUES (2);

EXCEPTION

WHEN DUP_VAL_ON_INDEX THEN

dbms_output.put_line('Duplicate values are not allowed');

END;

-->-- TOO_MANY_ROWS --<--

Single row SELECT returned multiple rows.

DECLARE

v_id NUMBER;
BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN TOO_MANY_ROWS THEN

dbms_output.put_line('Query returning more than one row');

END;

DROP TABLE test_tb;

-->-- VALUE_ERROR --<--

An arithmetic, conversion, truncation, or size constraint error occurred.

DECLARE

num1 NUMBER(2);

BEGIN

num1 := 345;

EXCEPTION

WHEN VALUE_ERROR THEN

dbms_output.put_line('check the size of the variable');

END;

-->-- CURSOR_ALREADY_OPEN --<--


A program attempted to open an already opened cursor.

CREATE TABLE emp(id NUMBER, name VARCHAR2(30));

BEGIN

INSERT INTO emp VALUES(1,'Name1');

INSERT INTO emp VALUES(2,'Name2');

INSERT INTO emp VALUES(3,'Name3');

INSERT INTO emp VALUES(4,'Name4');

COMMIT;

END;

SELECT * FROM emp;

DECLARE

cursor emp_c IS

SELECT * FROM emp;

all_data emp%ROWTYPE;

BEGIN

OPEN emp_c;

OPEN emp_c;

NULL;
CLOSE emp_c;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

END;

DROP TABLE emp;

-->-- OTHERS --<--

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

WHEN OTHERS THEN

dbms_output.put_line('Some other error ' || SQLERRM);

END;

User Defined Exception

**********************
A user-defined exception is an error that is defined by the programmer.

User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,

exceptions have a type EXCEPTION and scope.

DECLARE

v_gender CHAR := '&gender';

gender_ex EXCEPTION;

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE gender_ex;

END IF;

dbms_output.put_line('Gender : '||v_gender);

EXCEPTION

WHEN gender_ex THEN

dbms_output.put_line('Please Enter valid gender');

END;

create table test_insert (id NUMBER, Name VARCHAR2(30));

DECLARE

abort_ex EXCEPTION;
BEGIN

FOR i IN 1..100

LOOP

BEGIN

IF mod(i,10)=0 THEN

RAISE abort_ex;

END IF;

INSERT INTO test_insert VALUES(i, 'Name'||i);

EXCEPTION

WHEN abort_ex THEN

NULL;

END;

END LOOP;

COMMIT;

END;

SELECT * FROM test_insert;

DROP TABLE test_insert;

SQLERRM and SQLCODE

********************

SQLCODE returns the current error code, and SQLERRM returns the current error message
text;
For user-defined exception SQLCODE returns 1 and SQLERRM returns “user-defined
exception”.

SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.

CREATE TABLE test_tb (id NUMBER);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

dbms_output.put_line(v_id);

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('SQLERRM : ' || SQLERRM);

dbms_output.put_line('SQLCODE : ' || SQLCODE);

END;

/*sample output*/

SQLERRM : ORA-01403: no data found

SQLCODE : 100

DROP TABLE test_tb;


PRAGMA EXCEPTION_INIT

*********************

Using this you can associate a named exception with a particular oracle error.

This gives you the ability to trap this error specifically, rather than via an OTHERS handler.

Syntax:

PRAGMA EXCEPTION_INIT(exception_name, oracle_error_number);

DECLARE

v_result NUMBER;

PRAGMA EXCEPTION_INIT(Invalid, -1476);

BEGIN

SELECT 453 / 0 INTO v_result FROM dual;

dbms_output.put_line('Result : ' || v_result);

EXCEPTION

WHEN INVALID THEN

dbms_output.put_line('Invalid Exception');

END;

RAISE_APPLICATION_ERROR
************************

You can use this built-in function to create your own error messages, which can be more
descriptive than named exceptions.

Error Number :

Oracle Error Range : From -00000 to -19999

User Error Range : From -20000 to -20999

DECLARE

v_gender CHAR := '&gender';

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE_APPLICATION_ERROR(-20003, 'Enter valid gender');

END IF;

dbms_output.put_line('Gender : ' || v_gender);

END;

Posted 21st October 2014 by Unknown

1 View comments
Loading

Dynamic Views theme. Powered by Blogger.

Oracle sql & Pl/sql

search

Home Sql and pl/sql Sql Interview Questions

JUL

20

INLINE view in Oracle with 12c New Features

Named sub Query in FROM clause is call it as INLINE VIEW.

Oracle process a inline view faster than sub query

Inline View in Oracle

--Query to display all the employees who are all getting salary more than their department
average salary

SELECT First_name

, last_name

, salary

, department_id

FROM employees a , ( SELECT b.department_id


, AVG(b.salary) avg_sal

FROM employees b

GROUP BY b.department_id

)b

WHERE a.department_id = b.department_id

AND a.salary > b.avg_salary;

Display all the customer who have placed more number of orders by using INLINE view

CREATE TABLE customer_order_det_tb

( custm_id NUMBER ,

custm_nm VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

ttl_amt NUMBER(7,2)

);

BEGIN

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '11-Jul-15' , 45000.00);

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '14-Jul-15' , 27000.00);

INSERT INTO customer_order_det_tb VALUES(101, 'Raja' , '13-Jul-15' , 17000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 34000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 38000.00);

COMMIT;

END;
SELECT c.*

FROM customer_order_det_tb c;

--------------------------------------------

custm_id custm_nm order_dt ttl_amt

--------------------------------------------

100 Murugappan 7/11/2015 45000.00

100 Murugappan 7/14/2015 27000.00

101 Raja 7/13/2015 17000.00

102 Ramesh 7/15/2015 34000.00

102 Ramesh 7/15/2015 38000.00

--------------------------------------------

--Writing a Quer to display all the customer who have placed maximum number of order

--Query #1 for inline view

SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC;

--------------------------------
custm_id custm_nm total_odr

--------------------------------

100 Murugappan 2

102 Ramesh 2

101 Raja 1

--------------------------------

--Query #2 for inline view

SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm;

----------

total_odr

----------

----------

Inline view to find all the customers who have placed maximum number of orders

/****************************************

Syntax

SELECT * FROM <query1> x, <query2> y


WHERE contition;

****************************************/

SELECT query1.* FROM

( SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC

) query1,

( SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm

) query2

WHERE query1.total_odr = query2.total_odr;

-------------------------------

custm_id custm_nm total_odr

-------------------------------

100 Murugappan 2

102 Ramesh 2

-------------------------------

DROP TABLE customer_order_det_tb;

--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT
SELECT first_name, salary

FROM ( SELECT first_name, salary

FROM employees e

WHERE job_id NOT IN ('SALESMAN','PRESIDENT')

ORDER BY salary DESC

WHERE ROWNUM < 4;

New Oracle 12c Inline view Syntax

LATERAL clause for In-line views

Allows for columns in the inline view to be accessed!!

Example :

--in 11g

SELECT * FROM employees e, (

SELECT *

FROM departments d

WHERE e.department_id = d.department_id);


ORA-0090: "E"."DEPARTMENT_ID": Invalid Identifier

--in 12c

SELECT * FROM employees e, LATERAL(

SELECT *

FROM departments d

WHERE e.department_id = d.department_id

);

--in 11g

WITH t

AS

( SELECT LEVEL a

FROM dual

CONNECT BY LEVEL <= 30)

SELECT *

FROM t, (SELECT *

FROM employees

WHERE department_id = t.a

);

ORA-00904: "T"."A": invalid Identifier


--in 12c

WITH t

AS

(SELECT LEVEL a FROM dual CONNECT BY LEVEL <= 30)

SELECT * FROM t,

LATERAL(SELECT *

FROM employees

WHERE department_id = t.a);

Hope you have enjoyed this little article

Feed backs are always Welcome :) (:

Posted 20th July 2015 by Unknown

0 Add a comment

JAN

23

Salary Related Questions in Oracle

--creating table
CREATE TABLE employee_data

eid NUMBER(4),

ename VARCHAR2(30),

depno NUMBER(3),

salary NUMBER(8)

);

BEGIN

--Inserting records

INSERT INTO employee_data VALUES(1000,'Name01',90,30000);

INSERT INTO employee_data VALUES(1001,'Name02',90,6000);

INSERT INTO employee_data VALUES(1002,'Name03',90,23000);

INSERT INTO employee_data VALUES(1003,'Name04',60,35000);

INSERT INTO employee_data VALUES(1004,'Name05',60,60000);

INSERT INTO employee_data VALUES(1005,'Name06',60,30000);

INSERT INTO employee_data VALUES(1006,'Name07',80,36000);

INSERT INTO employee_data VALUES(1007,'Name08',80,29000);

INSERT INTO employee_data VALUES(1008,'Name09',80,37000);

INSERT INTO employee_data VALUES(1009,'Name10',80,41000);

COMMIT;

END;

/
SELECT * FROM employee_data

ORDER BY salary DESC;

--query to find maximum salary from employee_data table

SELECT MAX(salary) FROM employee_data;

--query to find minimum salary from employee_data table

SELECT MIN(salary) FROM employee_data;

--query to find second maximum salary from employee_data table

SELECT MAX(salary)

FROM employee_data

WHERE salary NOT IN (SELECT MAX(salary)

FROM employee_data);

--query to select 5th maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary


FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= 5);

--query to select nth maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= &n);

--query to select all the details of the employee whose getting nth maximum salary

SELECT *

FROM (SELECT emp.*,

rownum rn

FROM (SELECT *

FROM employee_data

ORDER BY salary DESC) emp)

WHERE rn = 9;
--same query using row_numbr( ) function

SELECT *

FROM (SELECT emp.*,

row_number() over(ORDER BY salary) rank

FROM employee_data emp)

WHERE rank = 9;

--same query using rank( ) function

SELECT *

FROM (SELECT emp.*,

rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--same query using dense_rank( ) function

SELECT *

FROM (SELECT emp.*,

dense_rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;
--query to display display maximum salary in all the department

SELECT e.depno "Department id",

MAX(salary) "Maximum Salary"

FROM employee_data e

GROUP BY e.depno;

--query to display all the employees who are all getting salary more than average salary of the
company

SELECT e.* FROM employee_data e

WHERE salary > (SELECT AVG(salary) FROM employee_data);

--query to display all the employees who are all getting salary more than their department
average salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE department_id = OUT.department_id);

--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE employee_id = OUT.manager_id);

Documented By : Murugappan Annamalai

Posted on : 23-Jan-15 16:34:00 IST.

Hope you have enjoyed this little article

Feed backs are always welcome :)

Posted 23rd January 2015 by Unknown

7 View comments

JAN

22
Why prefer COALESCE over NVL

Documented By : Nimish Garg

I prefer using "COALESCE" over "NVL" is some of the scenarios. Last week One of my friend
asked me what is the advantage of using "COALESCE" where we can simply use "NVL". I simply
gave him the reply from Oracle Docs i.e. NVL lets you replace null (returned as a blank) with a
string in the results of a query and COALESCE returns the first non-null expr in the expression list.
Oracle Database uses short-circuit evaluation with "COALESCE".

He replied that he knows the difference, he knows that "COALESCE" can take multiple arguments
and so on. He was more interested in understanding "short-circuit evaluation" of "COALESCE"
and the scenarios where I prefer using "COALESCE" over "NVL".

To make him understand I created following function which takes One second in every execution
and simply returns '--null--' and executed 2 very similar queries one with NVL and other with
COALESCE.

SQL> create or replace function f_null return varchar2

2 is

3 begin

4 dbms_lock.sleep(1);

5 return '--null--';

6 end;

7 /

Function created.
Following are the queries which I used to demonstrate that NVL evaluates both arguments even
if the second argument is not used and COALESCE uses short-circuit evaluation i.e. it only
evaluates the arguments only if they are needed.

SQL> select e.empno, e.ename ename, nvl(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--


14 rows selected.

Elapsed: 00:00:14.01

SQL> select e.empno, e.ename ename, coalesce(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--


14 rows selected.

Elapsed: 00:00:01.01

Here we can see easily that the first query with NVL took 14+ seconds, one second for each
record even if the "f_null" value was used only in one record. On the contrary as mentioned in
Oracle Documentation "COALESCE" uses its "short-circuit evaluation" and "f_null" was called
only once and so second query took only One Second. "COALESCE" is certainly use less resources
than NVL.

Posted 22nd January 2015 by Unknown

0 Add a comment

DEC

21

Constraints

It Enforce Rule On Table

We can create constraint at the time of Creating Table

1. Column Level Declaration


2. Table Level Declaration

1. We can provide own name.

Format : [part_of_project_name-table_name-column_name-constraint_type]

Example : gmind_emp_id_pk _uk _ck _f

2. system name name

Format : sys_cn

Example : SYS_C405323

We can create constraint after the table has been created

Types

Primary Key

Not allowed Null value

Not allowed you to enter duplicate value

Ex : Employee_id, Student_id
Unique Key

allowed Null value

Not allowed you to enter duplicate value

Ex : Contact_no, email

Foreign Key

It will allowed you to enter NULL and Duplicate value.

c1(pk) : 1 2 3

c2(f) : 1 1 2 3 4 Not allowed

Allowed you to enter duplicate value and null value

Not Null

It will not allowed you to enter null value

Check

You can check your own condition

Simple Table for understanding


------------------------------------

Duplicate NULL

------------------------------------

Primary Key X X

Unique Key X Allowed

Foreign Key Allowed Allowed

------------------------------------

creating table with all constraint type

Create table my_stu_details

S_id Number(2),

S_name Varchar2(30) Not Null, --SYS_Cn

s_mail Varchar2(30),

s_gender char(1),

s_did Number(3),

Constraint my_stu_sid_pk PRIMARY KEY (s_id),

constraint my_stu_mail_uk UNIQUE (s_mail) ,

Constraint my_stu_gen_ck CHECK (s_gender IN ('M', 'F', 'm', 'f')),

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)


);

DESC my_stu_details;

------------------------------------

Name Type Nullable

------------------------------------

S_ID NUMBER(2)

S_NAME VARCHAR2(30)

S_MAIL VARCHAR2(30) Y

S_GENDER CHAR(1) Y

S_DID NUMBER(3) Y

------------------------------------

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name1' , 'name1@gmail.com' , 'm' , 60 );

Select * from my_stu_details;


Validating Primary Key

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-00001: unique constraint (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (NULL, 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-01400: cannot insert NULL into (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (2 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

Validating NOT NULL Constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , NULL , 'name3@gmail.com' , 'F' , 80 );


ORA-01400: cannot insert NULL into ("HR"."MY_STU_DETAILS"."S_NAME")

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , 'Name3' , 'name3@gmail.com' , 'F' , 80 );

Select * from my_stu_details;

Validating Unique Key Constraint

--Duplicate Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , 'name3@gmail.com' , 'F' , 80 );

ORA-00001: unique constraint (HR.MY_STU_MAIL_UK) violated

--Null Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)


values (4 , 'Name4' , null , 'M' , 70 );

Select * from my_stu_details;

Validating Check constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'j' , 70 );

ORA-02290: check constraint (HR.MY_STU_GEN_CK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'M' , 70 );

Select * from my_stu_details;

Validating Foreign Key


Select * from Departments;

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 3 );

ORA-02291: integrity constraint (HR.MY_STU_DID_FK) violated - parent key not found

Departments table : parent table

my_stu_details : Child table

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

--------------------------------------------------------

s_id s_name s_mail s_gender s_did

--------------------------------------------------------

1 name1 name1@gmail.com m 60

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80
4 Name4 M 70

5 Name5 name5@gmail.com M 70

6 Name6 name6@gmail.com F 90

--------------------------------------------------------

Deleting the Primary key value which is referred by Foreign Key

Select * from Departments;

DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID

------------------------------------------------------------

60 IT 103 1400 <---- Delete

-- don't execute this query

--Delete From Departments

--Where Department_id = 60;

1) ON DELETE SET NULL

-------------------------------------------------
S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

1 name1 name1@gmail.com m -

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

2) ON DELETE SET CASCADE

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

Syntax

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)


ON DELETE CASCADE

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE SET NULL

Constraint Related Data Dictionary Table information.

To view constraint Information

SELECT c.owner,

c.constraint_name,

c.constraint_type,

c.table_name,

c.r_constraint_name,

c.status

FROM user_constraints c

WHERE c.table_name = 'MY_STU_DETAILS';

------------------------------------------------------------------------------------

owner constraint_name constraint_type table_name r_constraint_name status

------------------------------------------------------------------------------------

HR SYS_C004023 C MY_STU_DETAILS ENABLED


HR MY_STU_GEN_CK C MY_STU_DETAILS ENABLED

HR MY_STU_SID_PK P MY_STU_DETAILS ENABLED

HR MY_STU_MAIL_UK U MY_STU_DETAILS ENABLED

HR MY_STU_DID_FK R MY_STU_DETAILS DEPT_ID_PK ENABLED

------------------------------------------------------------------------------------

To view constraint name with corresponding column name

SELECT * FROM user_cons_columns c

WHERE c.table_name = 'MY_STU_DETAILS';

-------------------------------------------------------------

owner constraint_name table_name column_name position

-------------------------------------------------------------

HR MY_STU_MAIL_UK MY_STU_DETAILS S_MAIL 1

HR MY_STU_SID_PK MY_STU_DETAILS S_ID 1

HR MY_STU_GEN_CK MY_STU_DETAILS S_GENDER

HR SYS_C004023 MY_STU_DETAILS S_NAME

HR MY_STU_DID_FK MY_STU_DETAILS S_DID 1

-------------------------------------------------------------

Creating Composite Primary Key


Creating Primary Key with more than one number of column

ALTER TABLE table_name

ADD CONSTRAINT constraint_name PRIMARY KEY(column1, column_2 , column3);

In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.

creating constraint after the table creation

ALTER TABLE table_name

ADD CONSTRAINT constraint_name CONSTRAINT_TYPE(column_name);

ALTER TABLE table_name

DROP CONSTRAINT constraint_name;

ALTER TABLE table_name

DROP PRIMARY KEY;

To drop related foreign key


ALTER TABLE table_name

DROP PRIMARY KEY CASCADE;

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name;

Disable constraint with related foreign key constraint

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name CASCADE;

ALTER TABLE table_name

ENABLE CONSTRAINT constraint_name;

Interview Questions

What are all the type of constraint available in oracle?

Difference between PRIMARY KEY and UNIQUE key.

Difference between PRIMARY KEY ans FOREIGN KEY.


Difference between UNIQUE key and FOREIGN KEY.

Is it possible to create tow primary key in single table.

Write a syntax to create FOREIGN constraint.

How to create constraint after the table has been created?

How to enable and disable a constraint.

Which data dictionary table contains information about constraints?

Which Data Dictionary table contains information about constraint with corresponding column
name?

What is composite primary key?

Explain ON DELETE CASCADE and ON DELETE SET NULL option.

~Thanks For Reading~

Post your valuable feedback below

Posted 21st December 2014 by Unknown

1 View comments

DEC

listagg in Oracle 11g

Oracle 11gR2 listagg built-in function allows for many table columns to be displayed within a
single row, a non-first-normal form display

Syntax :

listagg(column_value,'delimiter') WITHIN GROUP(ORDER BY column_name)

--Example 1:

CREATE TABLE test_ins(empid NUMBER,product VARCHAR2(30));

BEGIN

INSERT INTO test_ins VALUES( 101,'pendrive');

INSERT INTO test_ins VALUES( 102,'toy');

INSERT INTO test_ins VALUES( 101,'ipod');

INSERT INTO test_ins VALUES( 102,'hat');

INSERT INTO test_ins VALUES( 103,'cpu');

INSERT INTO test_ins VALUES( 104,'pen');

INSERT INTO test_ins VALUES( 104,'car');

INSERT INTO test_ins VALUES( 104,'mat');

INSERT INTO test_ins VALUES( 105,'tv');

INSERT INTO test_ins VALUES( 106,'laptop');

commit;

END;
SELECT * FROM test_ins;

SELECT empid "Employee",

listagg(product,

',') within

GROUP (ORDER BY empid) "Products"

FROM test_ins

GROUP BY empid;

-->-- Result set --<--

DROP TABLE test_ins;


-->-- Example 2

select department_id "Department id", listagg(first_name,', ') WITHIN GROUP(ORDER BY


employee_id) "Employees"

FROM employees

WHERE department_id IN (10,20,30,60)

GROUP BY department_id;

-->-- Result set --<--

Posted 4th December 2014 by Unknown

0 Add a comment

NOV

Condition and Looping Statement

IF

IF ELSE

Multiple IF ELSE
LOOP

FOR LOOP

WHILE LOOP

create table test_udt(id NUMBER, salary NUMBER);

BEGIN

INSERT INTO test_udt VALUES(001,23000);

INSERT INTO test_udt VALUES(002,43000);

INSERT INTO test_udt VALUES(003,78000);

INSERT INTO test_udt VALUES(004,25000);

INSERT INTO test_udt VALUES(005,26000);

INSERT INTO test_udt VALUES(006,90000);

Commit;

END;

select * from test_udt;

IF

DECLARE
v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 1;

IF v_salary > 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

END IF;

commit;

END;

IF ELSE

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary
INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

ELSE

UPDATE test_udt t

SET t.salary = v_salary+20007

WHERE t.id = v_id ;

END IF;

commit;

END;

--same example with less number of lines

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary
INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

v_salary := v_salary+10005;

ELSE

v_salary := v_salary+20007;

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

Multiple IF ELSIF

DECLARE

v_salary NUMBER;

v_id NUMBER;
BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 3;

IF v_id = 1 THEN

v_salary := 1000;

dbms_output.put_line('1 inside');

ELSIF v_id = 2 THEN

v_salary := 2000;

dbms_output.put_line('2 inside');

ELSIF v_id = 3 THEN

v_salary := 3000;

dbms_output.put_line('3 inside');

ELSIF v_id = 4 THEN

v_salary := 4000;

dbms_output.put_line('4 inside');

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;
/

select * from test_udt;

LOOP

--syntax

LOOP

--statements

--increment

--exit statement

END LOOP;

CREATE TABLE prod_details (pid VARCHAR2(3), pname VARCHAR2(30));

DECLARE

i NUMBER := 1;

x VARCHAR2(3);

BEGIN

LOOP

x := lpad(i,3,'0');

dbms_output.put_line('x value : '|| x);


INSERT INTO prod_details VALUES(i, 'Product '||i);

EXIT WHEN i >900;

i := i+1;

IF MOD(i,100) = 0 THEN

commit;

dbms_output.put_line('commit executed');

END IF;

END LOOP;

END;

SELECT * FROM prod_details ORDER BY 1;

DROP TABLE prod_details;

FOR LOOP

BEGIN

FOR I in 1..5

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

/
FOR LOOP - Reverse

BEGIN

FOR I in REVERSE 14..50

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

WHILE LOOP

DECLARE

i_val NUMBER:=0;

BEGIN

WHILE (i_val < 11)

LOOP

dbms_output.put_line('The value of I is '||i_val);

i_val := i_val + 1;

END LOOP;

END;

sample output:
The value of I is 0

The value of I is 1

The value of I is 2

The value of I is 3

The value of I is 4

The value of I is 5

The value of I is 6

The value of I is 7

The value of I is 8

The value of I is 9

The value of I is 10

Posted 8th November 2014 by Unknown

0 Add a comment

OCT

21

Bulk Collect

This is used for array fetches

With this you can retrieve multiple rows of data with a single round trip.

This reduces the number of context switches between the pl/sql and sql engines.
You can use bulk collect in both dynamic and static sql.

You can use bulk collect in select, fetch into and returning into clauses.

SQL engine automatically initializes and extends the collections you reference in the bulk
collect clause.

You can fetch into multiple collections with one column each.

You can use the limit clause of bulk collect to restrict the no of rows retrieved.

SELECT * FROM product_details;

-->-- Bulk collect in FETCH INTO --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP


dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Bulk collect in SELECT clause --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

BEGIN

SELECT * BULK COLLECT INTO dta FROM product_details;

FOR i IN dta.FIRST .. dta.LAST LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- LIMIT in Bulk collect --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;
CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta LIMIT 30;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Multiple fetches in INTO clause --<--

SELECT * FROM product_details;

DECLARE

TYPE alldata_typ1 IS TABLE OF product_details.p_id%TYPE;

TYPE alldata_typ2 IS TABLE OF product_details.p_name%TYPE;

dta1 alldata_typ1;

dta2 alldata_typ2;
CURSOR proddt_cur IS

SELECT p_id, p_name FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta1, dta2;

CLOSE proddt_cur;

FOR i IN dta1.FIRST .. dta1.COUNT LOOP

dbms_output.put_line('Department Id : ' || dta1(i));

END LOOP;

FOR i IN dta2.FIRST .. dta2.COUNT LOOP

dbms_output.put_line('Department Name : ' || dta2(i));

END LOOP;

END;

DROP TABLE dep_details;

DROP TABLE product_details;

Posted 21st October 2014 by Unknown


0 Add a comment

OCT

21

Ref Cursor

This is unconstrained cursor which will return different types depends upon the user input.

Ref cursors cannot be closed implicitly.

Ref cursor with return type is called strong cursor.

Ref cursor without return type is called weak cursor.

You can declare ref cursor type in package spec as well as body.

You can declare ref cursor types in local subprograms or anonymous blocks.

CREATE OR REPLACE PROCEDURE ref_c_sp(dep_det_c IN OUT SYS_REFCURSOR)

AS

BEGIN

OPEN dep_det_c

FOR

SELECT * FROM dep_details d;

END;

DECLARE
dep_det_c SYS_REFCURSOR;

tab_data dep_details%ROWTYPE;

BEGIN

ref_c_sp(dep_det_c);

LOOP

FETCH dep_det_c INTO tab_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department Name : '|| tab_data.d_name);

END LOOP;

CLOSE dep_det_c;

END;

/*sample output*/

Department Name : Admin

Department Name : HR

Department Name : Sales

Department Name : Marketing

DROP PROCEDURE ref_c_sp;

Posted 21st October 2014 by Unknown


0 Add a comment

OCT

21

Cursor

SQL Private work Area where the query get passed and executed.

Types

******

Implicit(SQL)

Explicit

-->-- advanced cursor types --<--

Parametrized Cursor

Ref Cursor

Implicit

********

ORACLE implicitly opens a cursor to process each SQL statement not associated with an
explicitly declared cursor.

PL/SQL lets you refer to the most recent implicit cursor as the SQL” cursor. So, although you
cannot use the OPEN,
FETCH, and CLOSE statements to control an implicit cursor, you can still use cursor attributes to
access information

about the most recently executed SQL statement.

Cursor Stages

**************

OPEN cursor_name

FETCH (with in loop)

CLOSE cursor_name

Explicit

The set of rows returned by a query can consist of zero, one, or multiple rows,

depending on how many rows meet your search criteria. When a query returns multiple rows,

you can explicitly define a cursor to process the rows. You use three commands to control the
cursor

Cursor Attributes

*****************

%FOUND

%NOTFOUND

%ISOPEN

%ROWCOUNT

%BULK_ROWCOUNT --<-- used to handle error while using bulk collection.


%BULK_EXCEPTIONS --<-- used to handle error while using bulk collection.

Cursor Declaration

DECLARE

CURSOR <cursor_name>

IS

<SELECT statement>

BEGIN

--> some stmt

END;

Cursor Loop

Loop

While Loop

For Loop

Cursor Clauses

Return

For update

Where current of

Bulk collect

-->-- creating table


create table product_details

p_id NUMBER,

p_name VARCHAR2(30),

p_order_dt DATE

);

-->-- Inserting data

BEGIN

FOR i IN 1 .. 75 LOOP

INSERT INTO product_details VALUES (i, 'prod_name_' || i, SYSDATE + i);

END LOOP;

commit;

END;

-->-- selecting data

SELECT * FROM product_details;

---------------------------------------------

p_id p_name p_order_dt


---------------------------------------------

1 prod_name_1 10/11/2014 3:48:32 PM

2 prod_name_2 10/12/2014 3:48:32 PM

3 prod_name_3 10/13/2014 3:48:32 PM

4 prod_name_4 10/14/2014 3:48:32 PM

5 prod_name_5 10/15/2014 3:48:32 PM

6 prod_name_6 10/16/2014 3:48:32 PM

7 prod_name_7 10/17/2014 3:48:32 PM

8 prod_name_8 10/18/2014 3:48:32 PM

9 prod_name_9 10/19/2014 3:48:32 PM

10 prod_name_10 10/20/2014 3:48:32 PM

11 prod_name_11 10/21/2014 3:48:32 PM

12 prod_name_12 10/22/2014 3:48:32 PM

13 prod_name_13 10/23/2014 3:48:32 PM

14 prod_name_14 10/24/2014 3:48:32 PM

15 prod_name_15 10/25/2014 3:48:32 PM

16 prod_name_16 10/26/2014 3:48:32 PM

17 prod_name_17 10/27/2014 3:48:32 PM

18 prod_name_18 10/28/2014 3:48:32 PM

19 prod_name_19 10/29/2014 3:48:32 PM

20 prod_name_20 10/30/2014 3:48:32 PM

---------------------------------------------

----------------------------------------------
Implicit Cursor

----------------------------------------------

--will update soon

----------------------------------------------

Explicit Cursor

----------------------------------------------

**********************************************

Processing cursor data by using LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND; --<-- if next record not found means control will
come out from the loop
dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;
LOOP

FETCH prod_detail_cur

INTO all_data;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

EXIT WHEN prod_detail_cur%FOUND; --<-- if next record found means control will come
out from the loop

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN
OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )


Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor Already closed

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

-->-- CLOSE prod_detail_cur;


IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor closed

**********************************************

Processing cursor data by using WHILE LOOP


**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

OPEN prod_detail_cur;

FETCH prod_detail_cur

INTO all_data;

WHILE prod_detail_cur%FOUND LOOP

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

FETCH prod_detail_cur

INTO all_data;

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/
Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

************************************************************

Processing cursor data by using FOR LOOP - CURSOR FOR LOOP

************************************************************

DECLARE

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

FOR i IN prod_detail_cur

LOOP

dbms_output.put_line('Product id : ' || i.p_id ||

' Product Name : ' || i.p_name ||

' ( Orderd on : ' || TRIM(i.p_order_dt) || ' )');

END LOOP;

END;
/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

Parameterized Cursor

*********************

This was used when you are going to use the cursor in more than one place with different
values for the same where clause.

Cursor parameters must be in mode.

Cursor parameters may have default values.

The scope of cursor parameter is within the select statement.

CREATE TABLE dep_details(d_id NUMBER,d_name VARCHAR2(30), location_id NUMBER);

BEGIN

INSRT INTO dep_details VALUES(001,'Admin',1010);

INSRT INTO dep_details VALUES(002,'HR',1010);


INSRT INTO dep_details VALUES(003,'Sales',1020);

INSRT INTO dep_details VALUES(004,'Marketing',1020);

commit;

END;

SELECT * FROM dep_details;

----------------------------

d_id d_name location_id

----------------------------

1 Admin 1010

2 HR 1010

3 Sales 1020

4 Marketing 1020

----------------------------

DECLARE

-->--Declaring parameterized cursor

CURSOR dep_det_c(p_location_id NUMBER) IS

SELECT * FROM dep_details d WHERE d.location_id = p_location_id;

all_data dep_details%ROWTYPE;

BEGIN

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1010);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

-->-- opening same cursor with different input value

OPEN dep_det_c(1020);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

END;

/
/*sample output*/

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 1 Department Name : Admin

Department id : 2 Department Name : HR

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 3 Department Name : Sales

Department id : 4 Department Name : Marketing

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Handling Exception

Error Handling in oracle

ERROR

Any departure from the expected behavior of the system or program,

which stops the working of the system is an error.


Types : compile time error

Run time error

EXCEPTION

Any error or problem which one can handle and continue to work normally.

Handling Exception

When exception is raised, control passes to the exception section of the block.

i.e. EXCEPTION

WHEN name_of_exception THEN

Types : Pre Defined Exceptions

User Defined Exceptions

Predefined Exception

*********************

Oracle has predefined several exceptions that correspond to the most common oracle errors.

------------------------------------------------------------------------

Exception Oracle Error SQL Code Value

------------------------------------------------------------------------
ZERO_DIVIDE ORA-01476 -1476

NO_DATA_FOUND ORA-01403 +100

DUP_VAL_ON_INDEX ORA-00001 -1

TOO_MANY_ROWS ORA-01422 -1422

VALUE_ERROR ORA-06502 -6502

CURSOR_ALREADY_OPEN ORA-06511 -6511

OTHERS

------------------------------------------------------------------------

-->-- ZERO_DIVIDE --<--

Your program attempts to divide a number by zero.

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN ZERO_DIVIDE THEN

dbms_output.put_line('Divisor is equal to zero');

END;

-->-- NO_DATA_FOUND --<--


Single row SELECT returned no rows or your program referenced a deleted element in a nested
table

or an uninitialized element in an associative array (index-by table).

CREATE TABLE test_tb(id NUMBER PRIMARY KEY);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN NO_DATA_FOUND THEN

dbms_output.put_line('There is no data inside the table');

END;

-->-- DUP_VAL_ON_INDEX --<--

A program attempted to insert duplicate values in a column that is constrained by a unique


index.

INSERT INTO test_tb VALUES (1);

INSERT INTO test_tb VALUES (2);


commit;

BEGIN

INSERT INTO test_tb VALUES (2);

EXCEPTION

WHEN DUP_VAL_ON_INDEX THEN

dbms_output.put_line('Duplicate values are not allowed');

END;

-->-- TOO_MANY_ROWS --<--

Single row SELECT returned multiple rows.

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN TOO_MANY_ROWS THEN

dbms_output.put_line('Query returning more than one row');

END;

DROP TABLE test_tb;


-->-- VALUE_ERROR --<--

An arithmetic, conversion, truncation, or size constraint error occurred.

DECLARE

num1 NUMBER(2);

BEGIN

num1 := 345;

EXCEPTION

WHEN VALUE_ERROR THEN

dbms_output.put_line('check the size of the variable');

END;

-->-- CURSOR_ALREADY_OPEN --<--

A program attempted to open an already opened cursor.

CREATE TABLE emp(id NUMBER, name VARCHAR2(30));

BEGIN

INSERT INTO emp VALUES(1,'Name1');


INSERT INTO emp VALUES(2,'Name2');

INSERT INTO emp VALUES(3,'Name3');

INSERT INTO emp VALUES(4,'Name4');

COMMIT;

END;

SELECT * FROM emp;

DECLARE

cursor emp_c IS

SELECT * FROM emp;

all_data emp%ROWTYPE;

BEGIN

OPEN emp_c;

OPEN emp_c;

NULL;

CLOSE emp_c;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

END;

DROP TABLE emp;


-->-- OTHERS --<--

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

WHEN OTHERS THEN

dbms_output.put_line('Some other error ' || SQLERRM);

END;

User Defined Exception

**********************

A user-defined exception is an error that is defined by the programmer.

User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,

exceptions have a type EXCEPTION and scope.

DECLARE
v_gender CHAR := '&gender';

gender_ex EXCEPTION;

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE gender_ex;

END IF;

dbms_output.put_line('Gender : '||v_gender);

EXCEPTION

WHEN gender_ex THEN

dbms_output.put_line('Please Enter valid gender');

END;

create table test_insert (id NUMBER, Name VARCHAR2(30));

DECLARE

abort_ex EXCEPTION;

BEGIN

FOR i IN 1..100

LOOP

BEGIN

IF mod(i,10)=0 THEN

RAISE abort_ex;

END IF;

INSERT INTO test_insert VALUES(i, 'Name'||i);


EXCEPTION

WHEN abort_ex THEN

NULL;

END;

END LOOP;

COMMIT;

END;

SELECT * FROM test_insert;

DROP TABLE test_insert;

SQLERRM and SQLCODE

********************

SQLCODE returns the current error code, and SQLERRM returns the current error message
text;

For user-defined exception SQLCODE returns 1 and SQLERRM returns “user-defined


exception”.

SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.

CREATE TABLE test_tb (id NUMBER);

DECLARE
v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

dbms_output.put_line(v_id);

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('SQLERRM : ' || SQLERRM);

dbms_output.put_line('SQLCODE : ' || SQLCODE);

END;

/*sample output*/

SQLERRM : ORA-01403: no data found

SQLCODE : 100

DROP TABLE test_tb;

PRAGMA EXCEPTION_INIT

*********************

Using this you can associate a named exception with a particular oracle error.

This gives you the ability to trap this error specifically, rather than via an OTHERS handler.

Syntax:
PRAGMA EXCEPTION_INIT(exception_name, oracle_error_number);

DECLARE

v_result NUMBER;

PRAGMA EXCEPTION_INIT(Invalid, -1476);

BEGIN

SELECT 453 / 0 INTO v_result FROM dual;

dbms_output.put_line('Result : ' || v_result);

EXCEPTION

WHEN INVALID THEN

dbms_output.put_line('Invalid Exception');

END;

RAISE_APPLICATION_ERROR

************************

You can use this built-in function to create your own error messages, which can be more
descriptive than named exceptions.

Error Number :

Oracle Error Range : From -00000 to -19999


User Error Range : From -20000 to -20999

DECLARE

v_gender CHAR := '&gender';

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE_APPLICATION_ERROR(-20003, 'Enter valid gender');

END IF;

dbms_output.put_line('Gender : ' || v_gender);

END;

Posted 21st October 2014 by Unknown

1 View comments

Loading

Dynamic Views theme. Powered by Blogger.

Oracle sql & Pl/sql

search

Home Sql and pl/sql Sql Interview Questions


JUL

20

INLINE view in Oracle with 12c New Features

Named sub Query in FROM clause is call it as INLINE VIEW.

Oracle process a inline view faster than sub query

Inline View in Oracle

--Query to display all the employees who are all getting salary more than their department
average salary

SELECT First_name

, last_name

, salary

, department_id

FROM employees a , ( SELECT b.department_id

, AVG(b.salary) avg_sal

FROM employees b

GROUP BY b.department_id

)b

WHERE a.department_id = b.department_id

AND a.salary > b.avg_salary;


Display all the customer who have placed more number of orders by using INLINE view

CREATE TABLE customer_order_det_tb

( custm_id NUMBER ,

custm_nm VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

ttl_amt NUMBER(7,2)

);

BEGIN

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '11-Jul-15' , 45000.00);

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '14-Jul-15' , 27000.00);

INSERT INTO customer_order_det_tb VALUES(101, 'Raja' , '13-Jul-15' , 17000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 34000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 38000.00);

COMMIT;

END;

SELECT c.*

FROM customer_order_det_tb c;

--------------------------------------------

custm_id custm_nm order_dt ttl_amt

--------------------------------------------
100 Murugappan 7/11/2015 45000.00

100 Murugappan 7/14/2015 27000.00

101 Raja 7/13/2015 17000.00

102 Ramesh 7/15/2015 34000.00

102 Ramesh 7/15/2015 38000.00

--------------------------------------------

--Writing a Quer to display all the customer who have placed maximum number of order

--Query #1 for inline view

SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC;

--------------------------------

custm_id custm_nm total_odr

--------------------------------

100 Murugappan 2

102 Ramesh 2

101 Raja 1

--------------------------------

--Query #2 for inline view


SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm;

----------

total_odr

----------

----------

Inline view to find all the customers who have placed maximum number of orders

/****************************************

Syntax

SELECT * FROM <query1> x, <query2> y

WHERE contition;

****************************************/

SELECT query1.* FROM

( SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC


) query1,

( SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm

) query2

WHERE query1.total_odr = query2.total_odr;

-------------------------------

custm_id custm_nm total_odr

-------------------------------

100 Murugappan 2

102 Ramesh 2

-------------------------------

DROP TABLE customer_order_det_tb;

--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT

SELECT first_name, salary

FROM ( SELECT first_name, salary

FROM employees e

WHERE job_id NOT IN ('SALESMAN','PRESIDENT')

ORDER BY salary DESC

)
WHERE ROWNUM < 4;

New Oracle 12c Inline view Syntax

LATERAL clause for In-line views

Allows for columns in the inline view to be accessed!!

Example :

--in 11g

SELECT * FROM employees e, (

SELECT *

FROM departments d

WHERE e.department_id = d.department_id);

ORA-0090: "E"."DEPARTMENT_ID": Invalid Identifier

--in 12c

SELECT * FROM employees e, LATERAL(

SELECT *

FROM departments d

WHERE e.department_id = d.department_id


);

--in 11g

WITH t

AS

( SELECT LEVEL a

FROM dual

CONNECT BY LEVEL <= 30)

SELECT *

FROM t, (SELECT *

FROM employees

WHERE department_id = t.a

);

ORA-00904: "T"."A": invalid Identifier

--in 12c

WITH t

AS

(SELECT LEVEL a FROM dual CONNECT BY LEVEL <= 30)

SELECT * FROM t,

LATERAL(SELECT *

FROM employees

WHERE department_id = t.a);


Hope you have enjoyed this little article

Feed backs are always Welcome :) (:

Posted 20th July 2015 by Unknown

0 Add a comment

JAN

23

Salary Related Questions in Oracle

--creating table

CREATE TABLE employee_data

eid NUMBER(4),

ename VARCHAR2(30),

depno NUMBER(3),

salary NUMBER(8)

);
BEGIN

--Inserting records

INSERT INTO employee_data VALUES(1000,'Name01',90,30000);

INSERT INTO employee_data VALUES(1001,'Name02',90,6000);

INSERT INTO employee_data VALUES(1002,'Name03',90,23000);

INSERT INTO employee_data VALUES(1003,'Name04',60,35000);

INSERT INTO employee_data VALUES(1004,'Name05',60,60000);

INSERT INTO employee_data VALUES(1005,'Name06',60,30000);

INSERT INTO employee_data VALUES(1006,'Name07',80,36000);

INSERT INTO employee_data VALUES(1007,'Name08',80,29000);

INSERT INTO employee_data VALUES(1008,'Name09',80,37000);

INSERT INTO employee_data VALUES(1009,'Name10',80,41000);

COMMIT;

END;

SELECT * FROM employee_data

ORDER BY salary DESC;

--query to find maximum salary from employee_data table

SELECT MAX(salary) FROM employee_data;


--query to find minimum salary from employee_data table

SELECT MIN(salary) FROM employee_data;

--query to find second maximum salary from employee_data table

SELECT MAX(salary)

FROM employee_data

WHERE salary NOT IN (SELECT MAX(salary)

FROM employee_data);

--query to select 5th maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= 5);

--query to select nth maximum salary

SELECT MIN(salary)
FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= &n);

--query to select all the details of the employee whose getting nth maximum salary

SELECT *

FROM (SELECT emp.*,

rownum rn

FROM (SELECT *

FROM employee_data

ORDER BY salary DESC) emp)

WHERE rn = 9;

--same query using row_numbr( ) function

SELECT *

FROM (SELECT emp.*,

row_number() over(ORDER BY salary) rank

FROM employee_data emp)

WHERE rank = 9;
--same query using rank( ) function

SELECT *

FROM (SELECT emp.*,

rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--same query using dense_rank( ) function

SELECT *

FROM (SELECT emp.*,

dense_rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--query to display display maximum salary in all the department

SELECT e.depno "Department id",

MAX(salary) "Maximum Salary"

FROM employee_data e

GROUP BY e.depno;

--query to display all the employees who are all getting salary more than average salary of the
company
SELECT e.* FROM employee_data e

WHERE salary > (SELECT AVG(salary) FROM employee_data);

--query to display all the employees who are all getting salary more than their department
average salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE department_id = OUT.department_id);

--query to display all the employees who are all getting salary more than their manager salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE employee_id = OUT.manager_id);


Documented By : Murugappan Annamalai

Posted on : 23-Jan-15 16:34:00 IST.

Hope you have enjoyed this little article

Feed backs are always welcome :)

Posted 23rd January 2015 by Unknown

7 View comments

JAN

22

Why prefer COALESCE over NVL

Documented By : Nimish Garg

I prefer using "COALESCE" over "NVL" is some of the scenarios. Last week One of my friend
asked me what is the advantage of using "COALESCE" where we can simply use "NVL". I simply
gave him the reply from Oracle Docs i.e. NVL lets you replace null (returned as a blank) with a
string in the results of a query and COALESCE returns the first non-null expr in the expression list.
Oracle Database uses short-circuit evaluation with "COALESCE".
He replied that he knows the difference, he knows that "COALESCE" can take multiple arguments
and so on. He was more interested in understanding "short-circuit evaluation" of "COALESCE"
and the scenarios where I prefer using "COALESCE" over "NVL".

To make him understand I created following function which takes One second in every execution
and simply returns '--null--' and executed 2 very similar queries one with NVL and other with
COALESCE.

SQL> create or replace function f_null return varchar2

2 is

3 begin

4 dbms_lock.sleep(1);

5 return '--null--';

6 end;

7 /

Function created.

Following are the queries which I used to demonstrate that NVL evaluates both arguments even
if the second argument is not used and COALESCE uses short-circuit evaluation i.e. it only
evaluates the arguments only if they are needed.

SQL> select e.empno, e.ename ename, nvl(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME


---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.

Elapsed: 00:00:14.01

SQL> select e.empno, e.ename ename, coalesce(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME


---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.

Elapsed: 00:00:01.01

Here we can see easily that the first query with NVL took 14+ seconds, one second for each
record even if the "f_null" value was used only in one record. On the contrary as mentioned in
Oracle Documentation "COALESCE" uses its "short-circuit evaluation" and "f_null" was called
only once and so second query took only One Second. "COALESCE" is certainly use less resources
than NVL.

Posted 22nd January 2015 by Unknown


0 Add a comment

DEC

21

Constraints

It Enforce Rule On Table

We can create constraint at the time of Creating Table

1. Column Level Declaration

2. Table Level Declaration

1. We can provide own name.

Format : [part_of_project_name-table_name-column_name-constraint_type]

Example : gmind_emp_id_pk _uk _ck _f

2. system name name


Format : sys_cn

Example : SYS_C405323

We can create constraint after the table has been created

Types

Primary Key

Not allowed Null value

Not allowed you to enter duplicate value

Ex : Employee_id, Student_id

Unique Key

allowed Null value

Not allowed you to enter duplicate value

Ex : Contact_no, email

Foreign Key

It will allowed you to enter NULL and Duplicate value.


c1(pk) : 1 2 3

c2(f) : 1 1 2 3 4 Not allowed

Allowed you to enter duplicate value and null value

Not Null

It will not allowed you to enter null value

Check

You can check your own condition

Simple Table for understanding

------------------------------------

Duplicate NULL

------------------------------------

Primary Key X X

Unique Key X Allowed

Foreign Key Allowed Allowed

------------------------------------
creating table with all constraint type

Create table my_stu_details

S_id Number(2),

S_name Varchar2(30) Not Null, --SYS_Cn

s_mail Varchar2(30),

s_gender char(1),

s_did Number(3),

Constraint my_stu_sid_pk PRIMARY KEY (s_id),

constraint my_stu_mail_uk UNIQUE (s_mail) ,

Constraint my_stu_gen_ck CHECK (s_gender IN ('M', 'F', 'm', 'f')),

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

);

DESC my_stu_details;

------------------------------------

Name Type Nullable

------------------------------------

S_ID NUMBER(2)
S_NAME VARCHAR2(30)

S_MAIL VARCHAR2(30) Y

S_GENDER CHAR(1) Y

S_DID NUMBER(3) Y

------------------------------------

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name1' , 'name1@gmail.com' , 'm' , 60 );

Select * from my_stu_details;

Validating Primary Key

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-00001: unique constraint (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)


values (NULL, 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-01400: cannot insert NULL into (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (2 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

Validating NOT NULL Constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , NULL , 'name3@gmail.com' , 'F' , 80 );

ORA-01400: cannot insert NULL into ("HR"."MY_STU_DETAILS"."S_NAME")

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , 'Name3' , 'name3@gmail.com' , 'F' , 80 );

Select * from my_stu_details;


Validating Unique Key Constraint

--Duplicate Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , 'name3@gmail.com' , 'F' , 80 );

ORA-00001: unique constraint (HR.MY_STU_MAIL_UK) violated

--Null Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , null , 'M' , 70 );

Select * from my_stu_details;

Validating Check constraint


Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'j' , 70 );

ORA-02290: check constraint (HR.MY_STU_GEN_CK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'M' , 70 );

Select * from my_stu_details;

Validating Foreign Key

Select * from Departments;

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 3 );

ORA-02291: integrity constraint (HR.MY_STU_DID_FK) violated - parent key not found


Departments table : parent table

my_stu_details : Child table

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

--------------------------------------------------------

s_id s_name s_mail s_gender s_did

--------------------------------------------------------

1 name1 name1@gmail.com m 60

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 M 70

5 Name5 name5@gmail.com M 70

6 Name6 name6@gmail.com F 90

--------------------------------------------------------

Deleting the Primary key value which is referred by Foreign Key


Select * from Departments;

DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID

------------------------------------------------------------

60 IT 103 1400 <---- Delete

-- don't execute this query

--Delete From Departments

--Where Department_id = 60;

1) ON DELETE SET NULL

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

1 name1 name1@gmail.com m -

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------
2) ON DELETE SET CASCADE

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

Syntax

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE CASCADE

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE SET NULL

Constraint Related Data Dictionary Table information.


To view constraint Information

SELECT c.owner,

c.constraint_name,

c.constraint_type,

c.table_name,

c.r_constraint_name,

c.status

FROM user_constraints c

WHERE c.table_name = 'MY_STU_DETAILS';

------------------------------------------------------------------------------------

owner constraint_name constraint_type table_name r_constraint_name status

------------------------------------------------------------------------------------

HR SYS_C004023 C MY_STU_DETAILS ENABLED

HR MY_STU_GEN_CK C MY_STU_DETAILS ENABLED

HR MY_STU_SID_PK P MY_STU_DETAILS ENABLED

HR MY_STU_MAIL_UK U MY_STU_DETAILS ENABLED

HR MY_STU_DID_FK R MY_STU_DETAILS DEPT_ID_PK ENABLED

------------------------------------------------------------------------------------

To view constraint name with corresponding column name


SELECT * FROM user_cons_columns c

WHERE c.table_name = 'MY_STU_DETAILS';

-------------------------------------------------------------

owner constraint_name table_name column_name position

-------------------------------------------------------------

HR MY_STU_MAIL_UK MY_STU_DETAILS S_MAIL 1

HR MY_STU_SID_PK MY_STU_DETAILS S_ID 1

HR MY_STU_GEN_CK MY_STU_DETAILS S_GENDER

HR SYS_C004023 MY_STU_DETAILS S_NAME

HR MY_STU_DID_FK MY_STU_DETAILS S_DID 1

-------------------------------------------------------------

Creating Composite Primary Key

Creating Primary Key with more than one number of column

ALTER TABLE table_name

ADD CONSTRAINT constraint_name PRIMARY KEY(column1, column_2 , column3);

In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.
creating constraint after the table creation

ALTER TABLE table_name

ADD CONSTRAINT constraint_name CONSTRAINT_TYPE(column_name);

ALTER TABLE table_name

DROP CONSTRAINT constraint_name;

ALTER TABLE table_name

DROP PRIMARY KEY;

To drop related foreign key

ALTER TABLE table_name

DROP PRIMARY KEY CASCADE;

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name;

Disable constraint with related foreign key constraint


ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name CASCADE;

ALTER TABLE table_name

ENABLE CONSTRAINT constraint_name;

Interview Questions

What are all the type of constraint available in oracle?

Difference between PRIMARY KEY and UNIQUE key.

Difference between PRIMARY KEY ans FOREIGN KEY.

Difference between UNIQUE key and FOREIGN KEY.

Is it possible to create tow primary key in single table.

Write a syntax to create FOREIGN constraint.

How to create constraint after the table has been created?

How to enable and disable a constraint.

Which data dictionary table contains information about constraints?

Which Data Dictionary table contains information about constraint with corresponding column
name?

What is composite primary key?

Explain ON DELETE CASCADE and ON DELETE SET NULL option.


~Thanks For Reading~

Post your valuable feedback below

Posted 21st December 2014 by Unknown

1 View comments

UnknownMay 22, 2017 at 12:39 AM

good

Reply

DEC

listagg in Oracle 11g

Oracle 11gR2 listagg built-in function allows for many table columns to be displayed within a
single row, a non-first-normal form display

Syntax :
listagg(column_value,'delimiter') WITHIN GROUP(ORDER BY column_name)

--Example 1:

CREATE TABLE test_ins(empid NUMBER,product VARCHAR2(30));

BEGIN

INSERT INTO test_ins VALUES( 101,'pendrive');

INSERT INTO test_ins VALUES( 102,'toy');

INSERT INTO test_ins VALUES( 101,'ipod');

INSERT INTO test_ins VALUES( 102,'hat');

INSERT INTO test_ins VALUES( 103,'cpu');

INSERT INTO test_ins VALUES( 104,'pen');

INSERT INTO test_ins VALUES( 104,'car');

INSERT INTO test_ins VALUES( 104,'mat');

INSERT INTO test_ins VALUES( 105,'tv');

INSERT INTO test_ins VALUES( 106,'laptop');

commit;

END;

SELECT * FROM test_ins;

SELECT empid "Employee",

listagg(product,
',') within

GROUP (ORDER BY empid) "Products"

FROM test_ins

GROUP BY empid;

-->-- Result set --<--

DROP TABLE test_ins;

-->-- Example 2

select department_id "Department id", listagg(first_name,', ') WITHIN GROUP(ORDER BY


employee_id) "Employees"
FROM employees

WHERE department_id IN (10,20,30,60)

GROUP BY department_id;

-->-- Result set --<--

Posted 4th December 2014 by Unknown

0 Add a comment

NOV

Condition and Looping Statement

IF

IF ELSE

Multiple IF ELSE

LOOP

FOR LOOP

WHILE LOOP
create table test_udt(id NUMBER, salary NUMBER);

BEGIN

INSERT INTO test_udt VALUES(001,23000);

INSERT INTO test_udt VALUES(002,43000);

INSERT INTO test_udt VALUES(003,78000);

INSERT INTO test_udt VALUES(004,25000);

INSERT INTO test_udt VALUES(005,26000);

INSERT INTO test_udt VALUES(006,90000);

Commit;

END;

select * from test_udt;

IF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary
INTO v_id,v_salary

FROM test_udt

WHERE id = 1;

IF v_salary > 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

END IF;

commit;

END;

IF ELSE

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;
IF v_salary < 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

ELSE

UPDATE test_udt t

SET t.salary = v_salary+20007

WHERE t.id = v_id ;

END IF;

commit;

END;

--same example with less number of lines

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;
IF v_salary < 20000 THEN

v_salary := v_salary+10005;

ELSE

v_salary := v_salary+20007;

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

Multiple IF ELSIF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt
WHERE id = 3;

IF v_id = 1 THEN

v_salary := 1000;

dbms_output.put_line('1 inside');

ELSIF v_id = 2 THEN

v_salary := 2000;

dbms_output.put_line('2 inside');

ELSIF v_id = 3 THEN

v_salary := 3000;

dbms_output.put_line('3 inside');

ELSIF v_id = 4 THEN

v_salary := 4000;

dbms_output.put_line('4 inside');

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;


LOOP

--syntax

LOOP

--statements

--increment

--exit statement

END LOOP;

CREATE TABLE prod_details (pid VARCHAR2(3), pname VARCHAR2(30));

DECLARE

i NUMBER := 1;

x VARCHAR2(3);

BEGIN

LOOP

x := lpad(i,3,'0');

dbms_output.put_line('x value : '|| x);

INSERT INTO prod_details VALUES(i, 'Product '||i);

EXIT WHEN i >900;

i := i+1;
IF MOD(i,100) = 0 THEN

commit;

dbms_output.put_line('commit executed');

END IF;

END LOOP;

END;

SELECT * FROM prod_details ORDER BY 1;

DROP TABLE prod_details;

FOR LOOP

BEGIN

FOR I in 1..5

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

FOR LOOP - Reverse

BEGIN
FOR I in REVERSE 14..50

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

WHILE LOOP

DECLARE

i_val NUMBER:=0;

BEGIN

WHILE (i_val < 11)

LOOP

dbms_output.put_line('The value of I is '||i_val);

i_val := i_val + 1;

END LOOP;

END;

sample output:

The value of I is 0

The value of I is 1

The value of I is 2
The value of I is 3

The value of I is 4

The value of I is 5

The value of I is 6

The value of I is 7

The value of I is 8

The value of I is 9

The value of I is 10

Posted 8th November 2014 by Unknown

0 Add a comment

OCT

21

Bulk Collect

This is used for array fetches

With this you can retrieve multiple rows of data with a single round trip.

This reduces the number of context switches between the pl/sql and sql engines.

You can use bulk collect in both dynamic and static sql.

You can use bulk collect in select, fetch into and returning into clauses.

SQL engine automatically initializes and extends the collections you reference in the bulk
collect clause.

You can fetch into multiple collections with one column each.
You can use the limit clause of bulk collect to restrict the no of rows retrieved.

SELECT * FROM product_details;

-->-- Bulk collect in FETCH INTO --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

/
-->-- Bulk collect in SELECT clause --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

BEGIN

SELECT * BULK COLLECT INTO dta FROM product_details;

FOR i IN dta.FIRST .. dta.LAST LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- LIMIT in Bulk collect --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;
FETCH proddt_cur BULK COLLECT

INTO dta LIMIT 30;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Multiple fetches in INTO clause --<--

SELECT * FROM product_details;

DECLARE

TYPE alldata_typ1 IS TABLE OF product_details.p_id%TYPE;

TYPE alldata_typ2 IS TABLE OF product_details.p_name%TYPE;

dta1 alldata_typ1;

dta2 alldata_typ2;

CURSOR proddt_cur IS

SELECT p_id, p_name FROM product_details;

BEGIN

OPEN proddt_cur;
FETCH proddt_cur BULK COLLECT

INTO dta1, dta2;

CLOSE proddt_cur;

FOR i IN dta1.FIRST .. dta1.COUNT LOOP

dbms_output.put_line('Department Id : ' || dta1(i));

END LOOP;

FOR i IN dta2.FIRST .. dta2.COUNT LOOP

dbms_output.put_line('Department Name : ' || dta2(i));

END LOOP;

END;

DROP TABLE dep_details;

DROP TABLE product_details;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Ref Cursor
This is unconstrained cursor which will return different types depends upon the user input.

Ref cursors cannot be closed implicitly.

Ref cursor with return type is called strong cursor.

Ref cursor without return type is called weak cursor.

You can declare ref cursor type in package spec as well as body.

You can declare ref cursor types in local subprograms or anonymous blocks.

CREATE OR REPLACE PROCEDURE ref_c_sp(dep_det_c IN OUT SYS_REFCURSOR)

AS

BEGIN

OPEN dep_det_c

FOR

SELECT * FROM dep_details d;

END;

DECLARE

dep_det_c SYS_REFCURSOR;

tab_data dep_details%ROWTYPE;

BEGIN

ref_c_sp(dep_det_c);
LOOP

FETCH dep_det_c INTO tab_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department Name : '|| tab_data.d_name);

END LOOP;

CLOSE dep_det_c;

END;

/*sample output*/

Department Name : Admin

Department Name : HR

Department Name : Sales

Department Name : Marketing

DROP PROCEDURE ref_c_sp;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21
Cursor

SQL Private work Area where the query get passed and executed.

Types

******

Implicit(SQL)

Explicit

-->-- advanced cursor types --<--

Parametrized Cursor

Ref Cursor

Implicit

********

ORACLE implicitly opens a cursor to process each SQL statement not associated with an
explicitly declared cursor.

PL/SQL lets you refer to the most recent implicit cursor as the SQL” cursor. So, although you
cannot use the OPEN,

FETCH, and CLOSE statements to control an implicit cursor, you can still use cursor attributes to
access information

about the most recently executed SQL statement.

Cursor Stages
**************

OPEN cursor_name

FETCH (with in loop)

CLOSE cursor_name

Explicit

The set of rows returned by a query can consist of zero, one, or multiple rows,

depending on how many rows meet your search criteria. When a query returns multiple rows,

you can explicitly define a cursor to process the rows. You use three commands to control the
cursor

Cursor Attributes

*****************

%FOUND

%NOTFOUND

%ISOPEN

%ROWCOUNT

%BULK_ROWCOUNT --<-- used to handle error while using bulk collection.

%BULK_EXCEPTIONS --<-- used to handle error while using bulk collection.

Cursor Declaration

DECLARE
CURSOR <cursor_name>

IS

<SELECT statement>

BEGIN

--> some stmt

END;

Cursor Loop

Loop

While Loop

For Loop

Cursor Clauses

Return

For update

Where current of

Bulk collect

-->-- creating table

create table product_details

p_id NUMBER,

p_name VARCHAR2(30),
p_order_dt DATE

);

-->-- Inserting data

BEGIN

FOR i IN 1 .. 75 LOOP

INSERT INTO product_details VALUES (i, 'prod_name_' || i, SYSDATE + i);

END LOOP;

commit;

END;

-->-- selecting data

SELECT * FROM product_details;

---------------------------------------------

p_id p_name p_order_dt

---------------------------------------------

1 prod_name_1 10/11/2014 3:48:32 PM

2 prod_name_2 10/12/2014 3:48:32 PM

3 prod_name_3 10/13/2014 3:48:32 PM

4 prod_name_4 10/14/2014 3:48:32 PM


5 prod_name_5 10/15/2014 3:48:32 PM

6 prod_name_6 10/16/2014 3:48:32 PM

7 prod_name_7 10/17/2014 3:48:32 PM

8 prod_name_8 10/18/2014 3:48:32 PM

9 prod_name_9 10/19/2014 3:48:32 PM

10 prod_name_10 10/20/2014 3:48:32 PM

11 prod_name_11 10/21/2014 3:48:32 PM

12 prod_name_12 10/22/2014 3:48:32 PM

13 prod_name_13 10/23/2014 3:48:32 PM

14 prod_name_14 10/24/2014 3:48:32 PM

15 prod_name_15 10/25/2014 3:48:32 PM

16 prod_name_16 10/26/2014 3:48:32 PM

17 prod_name_17 10/27/2014 3:48:32 PM

18 prod_name_18 10/28/2014 3:48:32 PM

19 prod_name_19 10/29/2014 3:48:32 PM

20 prod_name_20 10/30/2014 3:48:32 PM

---------------------------------------------

----------------------------------------------

Implicit Cursor

----------------------------------------------

--will update soon


----------------------------------------------

Explicit Cursor

----------------------------------------------

**********************************************

Processing cursor data by using LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND; --<-- if next record not found means control will
come out from the loop

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;
END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||


' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

EXIT WHEN prod_detail_cur%FOUND; --<-- if next record found means control will come
out from the loop

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;


dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor Already closed


DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

-->-- CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE
dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor closed

**********************************************

Processing cursor data by using WHILE LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;
--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

OPEN prod_detail_cur;

FETCH prod_detail_cur

INTO all_data;

WHILE prod_detail_cur%FOUND LOOP

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

FETCH prod_detail_cur

INTO all_data;

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )


************************************************************

Processing cursor data by using FOR LOOP - CURSOR FOR LOOP

************************************************************

DECLARE

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

FOR i IN prod_detail_cur

LOOP

dbms_output.put_line('Product id : ' || i.p_id ||

' Product Name : ' || i.p_name ||

' ( Orderd on : ' || TRIM(i.p_order_dt) || ' )');

END LOOP;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )


Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

Parameterized Cursor

*********************

This was used when you are going to use the cursor in more than one place with different
values for the same where clause.

Cursor parameters must be in mode.

Cursor parameters may have default values.

The scope of cursor parameter is within the select statement.

CREATE TABLE dep_details(d_id NUMBER,d_name VARCHAR2(30), location_id NUMBER);

BEGIN

INSRT INTO dep_details VALUES(001,'Admin',1010);

INSRT INTO dep_details VALUES(002,'HR',1010);

INSRT INTO dep_details VALUES(003,'Sales',1020);

INSRT INTO dep_details VALUES(004,'Marketing',1020);

commit;

END;
SELECT * FROM dep_details;

----------------------------

d_id d_name location_id

----------------------------

1 Admin 1010

2 HR 1010

3 Sales 1020

4 Marketing 1020

----------------------------

DECLARE

-->--Declaring parameterized cursor

CURSOR dep_det_c(p_location_id NUMBER) IS

SELECT * FROM dep_details d WHERE d.location_id = p_location_id;

all_data dep_details%ROWTYPE;

BEGIN

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

OPEN dep_det_c(1010);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;


dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

-->-- opening same cursor with different input value

OPEN dep_det_c(1020);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

END;

/*sample output*/

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
Department id : 1 Department Name : Admin

Department id : 2 Department Name : HR

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 3 Department Name : Sales

Department id : 4 Department Name : Marketing

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Handling Exception

Error Handling in oracle

ERROR

Any departure from the expected behavior of the system or program,

which stops the working of the system is an error.

Types : compile time error

Run time error

EXCEPTION

Any error or problem which one can handle and continue to work normally.
Handling Exception

When exception is raised, control passes to the exception section of the block.

i.e. EXCEPTION

WHEN name_of_exception THEN

Types : Pre Defined Exceptions

User Defined Exceptions

Predefined Exception

*********************

Oracle has predefined several exceptions that correspond to the most common oracle errors.

------------------------------------------------------------------------

Exception Oracle Error SQL Code Value

------------------------------------------------------------------------

ZERO_DIVIDE ORA-01476 -1476

NO_DATA_FOUND ORA-01403 +100

DUP_VAL_ON_INDEX ORA-00001 -1

TOO_MANY_ROWS ORA-01422 -1422

VALUE_ERROR ORA-06502 -6502


CURSOR_ALREADY_OPEN ORA-06511 -6511

OTHERS

------------------------------------------------------------------------

-->-- ZERO_DIVIDE --<--

Your program attempts to divide a number by zero.

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN ZERO_DIVIDE THEN

dbms_output.put_line('Divisor is equal to zero');

END;

-->-- NO_DATA_FOUND --<--

Single row SELECT returned no rows or your program referenced a deleted element in a nested
table

or an uninitialized element in an associative array (index-by table).


CREATE TABLE test_tb(id NUMBER PRIMARY KEY);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN NO_DATA_FOUND THEN

dbms_output.put_line('There is no data inside the table');

END;

-->-- DUP_VAL_ON_INDEX --<--

A program attempted to insert duplicate values in a column that is constrained by a unique


index.

INSERT INTO test_tb VALUES (1);

INSERT INTO test_tb VALUES (2);

commit;

BEGIN

INSERT INTO test_tb VALUES (2);

EXCEPTION

WHEN DUP_VAL_ON_INDEX THEN


dbms_output.put_line('Duplicate values are not allowed');

END;

-->-- TOO_MANY_ROWS --<--

Single row SELECT returned multiple rows.

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN TOO_MANY_ROWS THEN

dbms_output.put_line('Query returning more than one row');

END;

DROP TABLE test_tb;

-->-- VALUE_ERROR --<--

An arithmetic, conversion, truncation, or size constraint error occurred.


DECLARE

num1 NUMBER(2);

BEGIN

num1 := 345;

EXCEPTION

WHEN VALUE_ERROR THEN

dbms_output.put_line('check the size of the variable');

END;

-->-- CURSOR_ALREADY_OPEN --<--

A program attempted to open an already opened cursor.

CREATE TABLE emp(id NUMBER, name VARCHAR2(30));

BEGIN

INSERT INTO emp VALUES(1,'Name1');

INSERT INTO emp VALUES(2,'Name2');

INSERT INTO emp VALUES(3,'Name3');

INSERT INTO emp VALUES(4,'Name4');

COMMIT;

END;
SELECT * FROM emp;

DECLARE

cursor emp_c IS

SELECT * FROM emp;

all_data emp%ROWTYPE;

BEGIN

OPEN emp_c;

OPEN emp_c;

NULL;

CLOSE emp_c;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

END;

DROP TABLE emp;

-->-- OTHERS --<--

DECLARE

v_result NUMBER;

BEGIN
SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

WHEN OTHERS THEN

dbms_output.put_line('Some other error ' || SQLERRM);

END;

User Defined Exception

**********************

A user-defined exception is an error that is defined by the programmer.

User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,

exceptions have a type EXCEPTION and scope.

DECLARE

v_gender CHAR := '&gender';

gender_ex EXCEPTION;

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE gender_ex;

END IF;
dbms_output.put_line('Gender : '||v_gender);

EXCEPTION

WHEN gender_ex THEN

dbms_output.put_line('Please Enter valid gender');

END;

create table test_insert (id NUMBER, Name VARCHAR2(30));

DECLARE

abort_ex EXCEPTION;

BEGIN

FOR i IN 1..100

LOOP

BEGIN

IF mod(i,10)=0 THEN

RAISE abort_ex;

END IF;

INSERT INTO test_insert VALUES(i, 'Name'||i);

EXCEPTION

WHEN abort_ex THEN

NULL;

END;

END LOOP;

COMMIT;
END;

SELECT * FROM test_insert;

DROP TABLE test_insert;

SQLERRM and SQLCODE

********************

SQLCODE returns the current error code, and SQLERRM returns the current error message
text;

For user-defined exception SQLCODE returns 1 and SQLERRM returns “user-defined


exception”.

SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.

CREATE TABLE test_tb (id NUMBER);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

dbms_output.put_line(v_id);

EXCEPTION

WHEN OTHERS THEN


dbms_output.put_line('SQLERRM : ' || SQLERRM);

dbms_output.put_line('SQLCODE : ' || SQLCODE);

END;

/*sample output*/

SQLERRM : ORA-01403: no data found

SQLCODE : 100

DROP TABLE test_tb;

PRAGMA EXCEPTION_INIT

*********************

Using this you can associate a named exception with a particular oracle error.

This gives you the ability to trap this error specifically, rather than via an OTHERS handler.

Syntax:

PRAGMA EXCEPTION_INIT(exception_name, oracle_error_number);

DECLARE

v_result NUMBER;

PRAGMA EXCEPTION_INIT(Invalid, -1476);


BEGIN

SELECT 453 / 0 INTO v_result FROM dual;

dbms_output.put_line('Result : ' || v_result);

EXCEPTION

WHEN INVALID THEN

dbms_output.put_line('Invalid Exception');

END;

RAISE_APPLICATION_ERROR

************************

You can use this built-in function to create your own error messages, which can be more
descriptive than named exceptions.

Error Number :

Oracle Error Range : From -00000 to -19999

User Error Range : From -20000 to -20999

DECLARE

v_gender CHAR := '&gender';

BEGIN
IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE_APPLICATION_ERROR(-20003, 'Enter valid gender');

END IF;

dbms_output.put_line('Gender : ' || v_gender);

END;

Posted 21st October 2014 by Unknown

1 View comments

Loading

Dynamic Views theme. Powered by Blogger.

Oracle sql & Pl/sql

search

Home Sql and pl/sql Sql Interview Questions

JUL

20

INLINE view in Oracle with 12c New Features

Named sub Query in FROM clause is call it as INLINE VIEW.


Oracle process a inline view faster than sub query

Inline View in Oracle

--Query to display all the employees who are all getting salary more than their department
average salary

SELECT First_name

, last_name

, salary

, department_id

FROM employees a , ( SELECT b.department_id

, AVG(b.salary) avg_sal

FROM employees b

GROUP BY b.department_id

)b

WHERE a.department_id = b.department_id

AND a.salary > b.avg_salary;

Display all the customer who have placed more number of orders by using INLINE view

CREATE TABLE customer_order_det_tb

( custm_id NUMBER ,

custm_nm VARCHAR2(30) ,
order_dt DATE DEFAULT SYSDATE ,

ttl_amt NUMBER(7,2)

);

BEGIN

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '11-Jul-15' , 45000.00);

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '14-Jul-15' , 27000.00);

INSERT INTO customer_order_det_tb VALUES(101, 'Raja' , '13-Jul-15' , 17000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 34000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 38000.00);

COMMIT;

END;

SELECT c.*

FROM customer_order_det_tb c;

--------------------------------------------

custm_id custm_nm order_dt ttl_amt

--------------------------------------------

100 Murugappan 7/11/2015 45000.00

100 Murugappan 7/14/2015 27000.00

101 Raja 7/13/2015 17000.00

102 Ramesh 7/15/2015 34000.00

102 Ramesh 7/15/2015 38000.00

--------------------------------------------
--Writing a Quer to display all the customer who have placed maximum number of order

--Query #1 for inline view

SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC;

--------------------------------

custm_id custm_nm total_odr

--------------------------------

100 Murugappan 2

102 Ramesh 2

101 Raja 1

--------------------------------

--Query #2 for inline view

SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm;

----------
total_odr

----------

----------

Inline view to find all the customers who have placed maximum number of orders

/****************************************

Syntax

SELECT * FROM <query1> x, <query2> y

WHERE contition;

****************************************/

SELECT query1.* FROM

( SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC

) query1,

( SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm

) query2

WHERE query1.total_odr = query2.total_odr;


-------------------------------

custm_id custm_nm total_odr

-------------------------------

100 Murugappan 2

102 Ramesh 2

-------------------------------

DROP TABLE customer_order_det_tb;

--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT

SELECT first_name, salary

FROM ( SELECT first_name, salary

FROM employees e

WHERE job_id NOT IN ('SALESMAN','PRESIDENT')

ORDER BY salary DESC

WHERE ROWNUM < 4;

New Oracle 12c Inline view Syntax


LATERAL clause for In-line views

Allows for columns in the inline view to be accessed!!

Example :

--in 11g

SELECT * FROM employees e, (

SELECT *

FROM departments d

WHERE e.department_id = d.department_id);

ORA-0090: "E"."DEPARTMENT_ID": Invalid Identifier

--in 12c

SELECT * FROM employees e, LATERAL(

SELECT *

FROM departments d

WHERE e.department_id = d.department_id

);

--in 11g

WITH t

AS
( SELECT LEVEL a

FROM dual

CONNECT BY LEVEL <= 30)

SELECT *

FROM t, (SELECT *

FROM employees

WHERE department_id = t.a

);

ORA-00904: "T"."A": invalid Identifier

--in 12c

WITH t

AS

(SELECT LEVEL a FROM dual CONNECT BY LEVEL <= 30)

SELECT * FROM t,

LATERAL(SELECT *

FROM employees

WHERE department_id = t.a);

Hope you have enjoyed this little article

Feed backs are always Welcome :) (:

Posted 20th July 2015 by Unknown


0 Add a comment

JAN

23

Salary Related Questions in Oracle

--creating table

CREATE TABLE employee_data

eid NUMBER(4),

ename VARCHAR2(30),

depno NUMBER(3),

salary NUMBER(8)

);

BEGIN

--Inserting records

INSERT INTO employee_data VALUES(1000,'Name01',90,30000);

INSERT INTO employee_data VALUES(1001,'Name02',90,6000);


INSERT INTO employee_data VALUES(1002,'Name03',90,23000);

INSERT INTO employee_data VALUES(1003,'Name04',60,35000);

INSERT INTO employee_data VALUES(1004,'Name05',60,60000);

INSERT INTO employee_data VALUES(1005,'Name06',60,30000);

INSERT INTO employee_data VALUES(1006,'Name07',80,36000);

INSERT INTO employee_data VALUES(1007,'Name08',80,29000);

INSERT INTO employee_data VALUES(1008,'Name09',80,37000);

INSERT INTO employee_data VALUES(1009,'Name10',80,41000);

COMMIT;

END;

SELECT * FROM employee_data

ORDER BY salary DESC;

--query to find maximum salary from employee_data table

SELECT MAX(salary) FROM employee_data;

--query to find minimum salary from employee_data table

SELECT MIN(salary) FROM employee_data;

--query to find second maximum salary from employee_data table


SELECT MAX(salary)

FROM employee_data

WHERE salary NOT IN (SELECT MAX(salary)

FROM employee_data);

--query to select 5th maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= 5);

--query to select nth maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= &n);


--query to select all the details of the employee whose getting nth maximum salary

SELECT *

FROM (SELECT emp.*,

rownum rn

FROM (SELECT *

FROM employee_data

ORDER BY salary DESC) emp)

WHERE rn = 9;

--same query using row_numbr( ) function

SELECT *

FROM (SELECT emp.*,

row_number() over(ORDER BY salary) rank

FROM employee_data emp)

WHERE rank = 9;

--same query using rank( ) function

SELECT *

FROM (SELECT emp.*,

rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)


WHERE rank = 4;

--same query using dense_rank( ) function

SELECT *

FROM (SELECT emp.*,

dense_rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--query to display display maximum salary in all the department

SELECT e.depno "Department id",

MAX(salary) "Maximum Salary"

FROM employee_data e

GROUP BY e.depno;

--query to display all the employees who are all getting salary more than average salary of the
company

SELECT e.* FROM employee_data e

WHERE salary > (SELECT AVG(salary) FROM employee_data);

--query to display all the employees who are all getting salary more than their department
average salary
SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE department_id = OUT.department_id);

--query to display all the employees who are all getting salary more than their manager salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE employee_id = OUT.manager_id);

Documented By : Murugappan Annamalai


Posted on : 23-Jan-15 16:34:00 IST.

Hope you have enjoyed this little article

Feed backs are always welcome :)

Posted 23rd January 2015 by Unknown

7 View comments

JAN

22

Why prefer COALESCE over NVL

Documented By : Nimish Garg

I prefer using "COALESCE" over "NVL" is some of the scenarios. Last week One of my friend
asked me what is the advantage of using "COALESCE" where we can simply use "NVL". I simply
gave him the reply from Oracle Docs i.e. NVL lets you replace null (returned as a blank) with a
string in the results of a query and COALESCE returns the first non-null expr in the expression list.
Oracle Database uses short-circuit evaluation with "COALESCE".

He replied that he knows the difference, he knows that "COALESCE" can take multiple arguments
and so on. He was more interested in understanding "short-circuit evaluation" of "COALESCE"
and the scenarios where I prefer using "COALESCE" over "NVL".

To make him understand I created following function which takes One second in every execution
and simply returns '--null--' and executed 2 very similar queries one with NVL and other with
COALESCE.
SQL> create or replace function f_null return varchar2

2 is

3 begin

4 dbms_lock.sleep(1);

5 return '--null--';

6 end;

7 /

Function created.

Following are the queries which I used to demonstrate that NVL evaluates both arguments even
if the second argument is not used and COALESCE uses short-circuit evaluation i.e. it only
evaluates the arguments only if they are needed.

SQL> select e.empno, e.ename ename, nvl(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE


7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.

Elapsed: 00:00:14.01

SQL> select e.empno, e.ename ename, coalesce(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE


7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.

Elapsed: 00:00:01.01

Here we can see easily that the first query with NVL took 14+ seconds, one second for each
record even if the "f_null" value was used only in one record. On the contrary as mentioned in
Oracle Documentation "COALESCE" uses its "short-circuit evaluation" and "f_null" was called
only once and so second query took only One Second. "COALESCE" is certainly use less resources
than NVL.

Posted 22nd January 2015 by Unknown

0 Add a comment

DEC
21

Constraints

It Enforce Rule On Table

We can create constraint at the time of Creating Table

1. Column Level Declaration

2. Table Level Declaration

1. We can provide own name.

Format : [part_of_project_name-table_name-column_name-constraint_type]

Example : gmind_emp_id_pk _uk _ck _f

2. system name name

Format : sys_cn

Example : SYS_C405323

We can create constraint after the table has been created


Types

Primary Key

Not allowed Null value

Not allowed you to enter duplicate value

Ex : Employee_id, Student_id

Unique Key

allowed Null value

Not allowed you to enter duplicate value

Ex : Contact_no, email

Foreign Key

It will allowed you to enter NULL and Duplicate value.

c1(pk) : 1 2 3

c2(f) : 1 1 2 3 4 Not allowed


Allowed you to enter duplicate value and null value

Not Null

It will not allowed you to enter null value

Check

You can check your own condition

Simple Table for understanding

------------------------------------

Duplicate NULL

------------------------------------

Primary Key X X

Unique Key X Allowed

Foreign Key Allowed Allowed

------------------------------------

creating table with all constraint type


Create table my_stu_details

S_id Number(2),

S_name Varchar2(30) Not Null, --SYS_Cn

s_mail Varchar2(30),

s_gender char(1),

s_did Number(3),

Constraint my_stu_sid_pk PRIMARY KEY (s_id),

constraint my_stu_mail_uk UNIQUE (s_mail) ,

Constraint my_stu_gen_ck CHECK (s_gender IN ('M', 'F', 'm', 'f')),

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

);

DESC my_stu_details;

------------------------------------

Name Type Nullable

------------------------------------

S_ID NUMBER(2)

S_NAME VARCHAR2(30)

S_MAIL VARCHAR2(30) Y

S_GENDER CHAR(1) Y

S_DID NUMBER(3) Y

------------------------------------
Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name1' , 'name1@gmail.com' , 'm' , 60 );

Select * from my_stu_details;

Validating Primary Key

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-00001: unique constraint (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (NULL, 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-01400: cannot insert NULL into (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)


values (2 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

Validating NOT NULL Constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , NULL , 'name3@gmail.com' , 'F' , 80 );

ORA-01400: cannot insert NULL into ("HR"."MY_STU_DETAILS"."S_NAME")

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , 'Name3' , 'name3@gmail.com' , 'F' , 80 );

Select * from my_stu_details;

Validating Unique Key Constraint

--Duplicate Check
Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , 'name3@gmail.com' , 'F' , 80 );

ORA-00001: unique constraint (HR.MY_STU_MAIL_UK) violated

--Null Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , null , 'M' , 70 );

Select * from my_stu_details;

Validating Check constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'j' , 70 );

ORA-02290: check constraint (HR.MY_STU_GEN_CK) violated


Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'M' , 70 );

Select * from my_stu_details;

Validating Foreign Key

Select * from Departments;

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 3 );

ORA-02291: integrity constraint (HR.MY_STU_DID_FK) violated - parent key not found

Departments table : parent table

my_stu_details : Child table

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)


values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

--------------------------------------------------------

s_id s_name s_mail s_gender s_did

--------------------------------------------------------

1 name1 name1@gmail.com m 60

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 M 70

5 Name5 name5@gmail.com M 70

6 Name6 name6@gmail.com F 90

--------------------------------------------------------

Deleting the Primary key value which is referred by Foreign Key

Select * from Departments;

DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID

------------------------------------------------------------
60 IT 103 1400 <---- Delete

-- don't execute this query

--Delete From Departments

--Where Department_id = 60;

1) ON DELETE SET NULL

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

1 name1 name1@gmail.com m -

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

2) ON DELETE SET CASCADE

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID


-------------------------------------------------

6 Name6 name6@gmail.com F 90

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

Syntax

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE CASCADE

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE SET NULL

Constraint Related Data Dictionary Table information.

To view constraint Information

SELECT c.owner,

c.constraint_name,

c.constraint_type,
c.table_name,

c.r_constraint_name,

c.status

FROM user_constraints c

WHERE c.table_name = 'MY_STU_DETAILS';

------------------------------------------------------------------------------------

owner constraint_name constraint_type table_name r_constraint_name status

------------------------------------------------------------------------------------

HR SYS_C004023 C MY_STU_DETAILS ENABLED

HR MY_STU_GEN_CK C MY_STU_DETAILS ENABLED

HR MY_STU_SID_PK P MY_STU_DETAILS ENABLED

HR MY_STU_MAIL_UK U MY_STU_DETAILS ENABLED

HR MY_STU_DID_FK R MY_STU_DETAILS DEPT_ID_PK ENABLED

------------------------------------------------------------------------------------

To view constraint name with corresponding column name

SELECT * FROM user_cons_columns c

WHERE c.table_name = 'MY_STU_DETAILS';

-------------------------------------------------------------
owner constraint_name table_name column_name position

-------------------------------------------------------------

HR MY_STU_MAIL_UK MY_STU_DETAILS S_MAIL 1

HR MY_STU_SID_PK MY_STU_DETAILS S_ID 1

HR MY_STU_GEN_CK MY_STU_DETAILS S_GENDER

HR SYS_C004023 MY_STU_DETAILS S_NAME

HR MY_STU_DID_FK MY_STU_DETAILS S_DID 1

-------------------------------------------------------------

Creating Composite Primary Key

Creating Primary Key with more than one number of column

ALTER TABLE table_name

ADD CONSTRAINT constraint_name PRIMARY KEY(column1, column_2 , column3);

In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.

creating constraint after the table creation

ALTER TABLE table_name


ADD CONSTRAINT constraint_name CONSTRAINT_TYPE(column_name);

ALTER TABLE table_name

DROP CONSTRAINT constraint_name;

ALTER TABLE table_name

DROP PRIMARY KEY;

To drop related foreign key

ALTER TABLE table_name

DROP PRIMARY KEY CASCADE;

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name;

Disable constraint with related foreign key constraint

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name CASCADE;


ALTER TABLE table_name

ENABLE CONSTRAINT constraint_name;

Interview Questions

What are all the type of constraint available in oracle?

Difference between PRIMARY KEY and UNIQUE key.

Difference between PRIMARY KEY ans FOREIGN KEY.

Difference between UNIQUE key and FOREIGN KEY.

Is it possible to create tow primary key in single table.

Write a syntax to create FOREIGN constraint.

How to create constraint after the table has been created?

How to enable and disable a constraint.

Which data dictionary table contains information about constraints?

Which Data Dictionary table contains information about constraint with corresponding column
name?

What is composite primary key?

Explain ON DELETE CASCADE and ON DELETE SET NULL option.

~Thanks For Reading~

Post your valuable feedback below


Posted 21st December 2014 by Unknown

1 View comments

UnknownMay 22, 2017 at 12:39 AM

good

Reply

DEC

listagg in Oracle 11g

Oracle 11gR2 listagg built-in function allows for many table columns to be displayed within a
single row, a non-first-normal form display

Syntax :

listagg(column_value,'delimiter') WITHIN GROUP(ORDER BY column_name)

--Example 1:
CREATE TABLE test_ins(empid NUMBER,product VARCHAR2(30));

BEGIN

INSERT INTO test_ins VALUES( 101,'pendrive');

INSERT INTO test_ins VALUES( 102,'toy');

INSERT INTO test_ins VALUES( 101,'ipod');

INSERT INTO test_ins VALUES( 102,'hat');

INSERT INTO test_ins VALUES( 103,'cpu');

INSERT INTO test_ins VALUES( 104,'pen');

INSERT INTO test_ins VALUES( 104,'car');

INSERT INTO test_ins VALUES( 104,'mat');

INSERT INTO test_ins VALUES( 105,'tv');

INSERT INTO test_ins VALUES( 106,'laptop');

commit;

END;

SELECT * FROM test_ins;

SELECT empid "Employee",

listagg(product,

',') within

GROUP (ORDER BY empid) "Products"

FROM test_ins

GROUP BY empid;
-->-- Result set --<--

DROP TABLE test_ins;

-->-- Example 2

select department_id "Department id", listagg(first_name,', ') WITHIN GROUP(ORDER BY


employee_id) "Employees"

FROM employees

WHERE department_id IN (10,20,30,60)

GROUP BY department_id;

-->-- Result set --<--


Posted 4th December 2014 by Unknown

0 Add a comment

NOV

Condition and Looping Statement

IF

IF ELSE

Multiple IF ELSE

LOOP

FOR LOOP

WHILE LOOP

create table test_udt(id NUMBER, salary NUMBER);


BEGIN

INSERT INTO test_udt VALUES(001,23000);

INSERT INTO test_udt VALUES(002,43000);

INSERT INTO test_udt VALUES(003,78000);

INSERT INTO test_udt VALUES(004,25000);

INSERT INTO test_udt VALUES(005,26000);

INSERT INTO test_udt VALUES(006,90000);

Commit;

END;

select * from test_udt;

IF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 1;
IF v_salary > 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

END IF;

commit;

END;

IF ELSE

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;


ELSE

UPDATE test_udt t

SET t.salary = v_salary+20007

WHERE t.id = v_id ;

END IF;

commit;

END;

--same example with less number of lines

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

v_salary := v_salary+10005;

ELSE

v_salary := v_salary+20007;
END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

Multiple IF ELSIF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 3;

IF v_id = 1 THEN

v_salary := 1000;
dbms_output.put_line('1 inside');

ELSIF v_id = 2 THEN

v_salary := 2000;

dbms_output.put_line('2 inside');

ELSIF v_id = 3 THEN

v_salary := 3000;

dbms_output.put_line('3 inside');

ELSIF v_id = 4 THEN

v_salary := 4000;

dbms_output.put_line('4 inside');

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

LOOP

--syntax
LOOP

--statements

--increment

--exit statement

END LOOP;

CREATE TABLE prod_details (pid VARCHAR2(3), pname VARCHAR2(30));

DECLARE

i NUMBER := 1;

x VARCHAR2(3);

BEGIN

LOOP

x := lpad(i,3,'0');

dbms_output.put_line('x value : '|| x);

INSERT INTO prod_details VALUES(i, 'Product '||i);

EXIT WHEN i >900;

i := i+1;

IF MOD(i,100) = 0 THEN

commit;

dbms_output.put_line('commit executed');

END IF;
END LOOP;

END;

SELECT * FROM prod_details ORDER BY 1;

DROP TABLE prod_details;

FOR LOOP

BEGIN

FOR I in 1..5

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

FOR LOOP - Reverse

BEGIN

FOR I in REVERSE 14..50

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;
END;

WHILE LOOP

DECLARE

i_val NUMBER:=0;

BEGIN

WHILE (i_val < 11)

LOOP

dbms_output.put_line('The value of I is '||i_val);

i_val := i_val + 1;

END LOOP;

END;

sample output:

The value of I is 0

The value of I is 1

The value of I is 2

The value of I is 3

The value of I is 4

The value of I is 5

The value of I is 6
The value of I is 7

The value of I is 8

The value of I is 9

The value of I is 10

Posted 8th November 2014 by Unknown

0 Add a comment

OCT

21

Bulk Collect

This is used for array fetches

With this you can retrieve multiple rows of data with a single round trip.

This reduces the number of context switches between the pl/sql and sql engines.

You can use bulk collect in both dynamic and static sql.

You can use bulk collect in select, fetch into and returning into clauses.

SQL engine automatically initializes and extends the collections you reference in the bulk
collect clause.

You can fetch into multiple collections with one column each.

You can use the limit clause of bulk collect to restrict the no of rows retrieved.
SELECT * FROM product_details;

-->-- Bulk collect in FETCH INTO --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Bulk collect in SELECT clause --<--


DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

BEGIN

SELECT * BULK COLLECT INTO dta FROM product_details;

FOR i IN dta.FIRST .. dta.LAST LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- LIMIT in Bulk collect --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta LIMIT 30;

CLOSE proddt_cur;
FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Multiple fetches in INTO clause --<--

SELECT * FROM product_details;

DECLARE

TYPE alldata_typ1 IS TABLE OF product_details.p_id%TYPE;

TYPE alldata_typ2 IS TABLE OF product_details.p_name%TYPE;

dta1 alldata_typ1;

dta2 alldata_typ2;

CURSOR proddt_cur IS

SELECT p_id, p_name FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta1, dta2;

CLOSE proddt_cur;
FOR i IN dta1.FIRST .. dta1.COUNT LOOP

dbms_output.put_line('Department Id : ' || dta1(i));

END LOOP;

FOR i IN dta2.FIRST .. dta2.COUNT LOOP

dbms_output.put_line('Department Name : ' || dta2(i));

END LOOP;

END;

DROP TABLE dep_details;

DROP TABLE product_details;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Ref Cursor

This is unconstrained cursor which will return different types depends upon the user input.

Ref cursors cannot be closed implicitly.


Ref cursor with return type is called strong cursor.

Ref cursor without return type is called weak cursor.

You can declare ref cursor type in package spec as well as body.

You can declare ref cursor types in local subprograms or anonymous blocks.

CREATE OR REPLACE PROCEDURE ref_c_sp(dep_det_c IN OUT SYS_REFCURSOR)

AS

BEGIN

OPEN dep_det_c

FOR

SELECT * FROM dep_details d;

END;

DECLARE

dep_det_c SYS_REFCURSOR;

tab_data dep_details%ROWTYPE;

BEGIN

ref_c_sp(dep_det_c);

LOOP

FETCH dep_det_c INTO tab_data;

EXIT WHEN dep_det_c%NOTFOUND;


dbms_output.put_line('Department Name : '|| tab_data.d_name);

END LOOP;

CLOSE dep_det_c;

END;

/*sample output*/

Department Name : Admin

Department Name : HR

Department Name : Sales

Department Name : Marketing

DROP PROCEDURE ref_c_sp;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Cursor
SQL Private work Area where the query get passed and executed.

Types

******

Implicit(SQL)

Explicit

-->-- advanced cursor types --<--

Parametrized Cursor

Ref Cursor

Implicit

********

ORACLE implicitly opens a cursor to process each SQL statement not associated with an
explicitly declared cursor.

PL/SQL lets you refer to the most recent implicit cursor as the SQL” cursor. So, although you
cannot use the OPEN,

FETCH, and CLOSE statements to control an implicit cursor, you can still use cursor attributes to
access information

about the most recently executed SQL statement.

Cursor Stages

**************

OPEN cursor_name

FETCH (with in loop)


CLOSE cursor_name

Explicit

The set of rows returned by a query can consist of zero, one, or multiple rows,

depending on how many rows meet your search criteria. When a query returns multiple rows,

you can explicitly define a cursor to process the rows. You use three commands to control the
cursor

Cursor Attributes

*****************

%FOUND

%NOTFOUND

%ISOPEN

%ROWCOUNT

%BULK_ROWCOUNT --<-- used to handle error while using bulk collection.

%BULK_EXCEPTIONS --<-- used to handle error while using bulk collection.

Cursor Declaration

DECLARE

CURSOR <cursor_name>

IS

<SELECT statement>

BEGIN
--> some stmt

END;

Cursor Loop

Loop

While Loop

For Loop

Cursor Clauses

Return

For update

Where current of

Bulk collect

-->-- creating table

create table product_details

p_id NUMBER,

p_name VARCHAR2(30),

p_order_dt DATE

);
-->-- Inserting data

BEGIN

FOR i IN 1 .. 75 LOOP

INSERT INTO product_details VALUES (i, 'prod_name_' || i, SYSDATE + i);

END LOOP;

commit;

END;

-->-- selecting data

SELECT * FROM product_details;

---------------------------------------------

p_id p_name p_order_dt

---------------------------------------------

1 prod_name_1 10/11/2014 3:48:32 PM

2 prod_name_2 10/12/2014 3:48:32 PM

3 prod_name_3 10/13/2014 3:48:32 PM

4 prod_name_4 10/14/2014 3:48:32 PM

5 prod_name_5 10/15/2014 3:48:32 PM

6 prod_name_6 10/16/2014 3:48:32 PM

7 prod_name_7 10/17/2014 3:48:32 PM

8 prod_name_8 10/18/2014 3:48:32 PM


9 prod_name_9 10/19/2014 3:48:32 PM

10 prod_name_10 10/20/2014 3:48:32 PM

11 prod_name_11 10/21/2014 3:48:32 PM

12 prod_name_12 10/22/2014 3:48:32 PM

13 prod_name_13 10/23/2014 3:48:32 PM

14 prod_name_14 10/24/2014 3:48:32 PM

15 prod_name_15 10/25/2014 3:48:32 PM

16 prod_name_16 10/26/2014 3:48:32 PM

17 prod_name_17 10/27/2014 3:48:32 PM

18 prod_name_18 10/28/2014 3:48:32 PM

19 prod_name_19 10/29/2014 3:48:32 PM

20 prod_name_20 10/30/2014 3:48:32 PM

---------------------------------------------

----------------------------------------------

Implicit Cursor

----------------------------------------------

--will update soon

----------------------------------------------

Explicit Cursor

----------------------------------------------
**********************************************

Processing cursor data by using LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND; --<-- if next record not found means control will
come out from the loop

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/
Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

EXIT WHEN prod_detail_cur%FOUND; --<-- if next record found means control will come
out from the loop

END LOOP;

CLOSE prod_detail_cur;
END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;
CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor Already closed

DECLARE
all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

-->-- CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;
/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor closed

**********************************************

Processing cursor data by using WHILE LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN
OPEN prod_detail_cur;

FETCH prod_detail_cur

INTO all_data;

WHILE prod_detail_cur%FOUND LOOP

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

FETCH prod_detail_cur

INTO all_data;

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

************************************************************

Processing cursor data by using FOR LOOP - CURSOR FOR LOOP


************************************************************

DECLARE

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

FOR i IN prod_detail_cur

LOOP

dbms_output.put_line('Product id : ' || i.p_id ||

' Product Name : ' || i.p_name ||

' ( Orderd on : ' || TRIM(i.p_order_dt) || ' )');

END LOOP;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )


Parameterized Cursor

*********************

This was used when you are going to use the cursor in more than one place with different
values for the same where clause.

Cursor parameters must be in mode.

Cursor parameters may have default values.

The scope of cursor parameter is within the select statement.

CREATE TABLE dep_details(d_id NUMBER,d_name VARCHAR2(30), location_id NUMBER);

BEGIN

INSRT INTO dep_details VALUES(001,'Admin',1010);

INSRT INTO dep_details VALUES(002,'HR',1010);

INSRT INTO dep_details VALUES(003,'Sales',1020);

INSRT INTO dep_details VALUES(004,'Marketing',1020);

commit;

END;

SELECT * FROM dep_details;

----------------------------

d_id d_name location_id


----------------------------

1 Admin 1010

2 HR 1010

3 Sales 1020

4 Marketing 1020

----------------------------

DECLARE

-->--Declaring parameterized cursor

CURSOR dep_det_c(p_location_id NUMBER) IS

SELECT * FROM dep_details d WHERE d.location_id = p_location_id;

all_data dep_details%ROWTYPE;

BEGIN

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

OPEN dep_det_c(1010);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

-->-- opening same cursor with different input value

OPEN dep_det_c(1020);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

END;

/*sample output*/

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 1 Department Name : Admin

Department id : 2 Department Name : HR

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 3 Department Name : Sales


Department id : 4 Department Name : Marketing

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Handling Exception

Error Handling in oracle

ERROR

Any departure from the expected behavior of the system or program,

which stops the working of the system is an error.

Types : compile time error

Run time error

EXCEPTION

Any error or problem which one can handle and continue to work normally.

Handling Exception

When exception is raised, control passes to the exception section of the block.
i.e. EXCEPTION

WHEN name_of_exception THEN

Types : Pre Defined Exceptions

User Defined Exceptions

Predefined Exception

*********************

Oracle has predefined several exceptions that correspond to the most common oracle errors.

------------------------------------------------------------------------

Exception Oracle Error SQL Code Value

------------------------------------------------------------------------

ZERO_DIVIDE ORA-01476 -1476

NO_DATA_FOUND ORA-01403 +100

DUP_VAL_ON_INDEX ORA-00001 -1

TOO_MANY_ROWS ORA-01422 -1422

VALUE_ERROR ORA-06502 -6502

CURSOR_ALREADY_OPEN ORA-06511 -6511

OTHERS

------------------------------------------------------------------------
-->-- ZERO_DIVIDE --<--

Your program attempts to divide a number by zero.

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN ZERO_DIVIDE THEN

dbms_output.put_line('Divisor is equal to zero');

END;

-->-- NO_DATA_FOUND --<--

Single row SELECT returned no rows or your program referenced a deleted element in a nested
table

or an uninitialized element in an associative array (index-by table).

CREATE TABLE test_tb(id NUMBER PRIMARY KEY);

DECLARE

v_id NUMBER;
BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN NO_DATA_FOUND THEN

dbms_output.put_line('There is no data inside the table');

END;

-->-- DUP_VAL_ON_INDEX --<--

A program attempted to insert duplicate values in a column that is constrained by a unique


index.

INSERT INTO test_tb VALUES (1);

INSERT INTO test_tb VALUES (2);

commit;

BEGIN

INSERT INTO test_tb VALUES (2);

EXCEPTION

WHEN DUP_VAL_ON_INDEX THEN

dbms_output.put_line('Duplicate values are not allowed');

END;
-->-- TOO_MANY_ROWS --<--

Single row SELECT returned multiple rows.

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN TOO_MANY_ROWS THEN

dbms_output.put_line('Query returning more than one row');

END;

DROP TABLE test_tb;

-->-- VALUE_ERROR --<--

An arithmetic, conversion, truncation, or size constraint error occurred.

DECLARE

num1 NUMBER(2);

BEGIN

num1 := 345;
EXCEPTION

WHEN VALUE_ERROR THEN

dbms_output.put_line('check the size of the variable');

END;

-->-- CURSOR_ALREADY_OPEN --<--

A program attempted to open an already opened cursor.

CREATE TABLE emp(id NUMBER, name VARCHAR2(30));

BEGIN

INSERT INTO emp VALUES(1,'Name1');

INSERT INTO emp VALUES(2,'Name2');

INSERT INTO emp VALUES(3,'Name3');

INSERT INTO emp VALUES(4,'Name4');

COMMIT;

END;

SELECT * FROM emp;

DECLARE
cursor emp_c IS

SELECT * FROM emp;

all_data emp%ROWTYPE;

BEGIN

OPEN emp_c;

OPEN emp_c;

NULL;

CLOSE emp_c;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

END;

DROP TABLE emp;

-->-- OTHERS --<--

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');


WHEN OTHERS THEN

dbms_output.put_line('Some other error ' || SQLERRM);

END;

User Defined Exception

**********************

A user-defined exception is an error that is defined by the programmer.

User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,

exceptions have a type EXCEPTION and scope.

DECLARE

v_gender CHAR := '&gender';

gender_ex EXCEPTION;

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE gender_ex;

END IF;

dbms_output.put_line('Gender : '||v_gender);

EXCEPTION

WHEN gender_ex THEN

dbms_output.put_line('Please Enter valid gender');


END;

create table test_insert (id NUMBER, Name VARCHAR2(30));

DECLARE

abort_ex EXCEPTION;

BEGIN

FOR i IN 1..100

LOOP

BEGIN

IF mod(i,10)=0 THEN

RAISE abort_ex;

END IF;

INSERT INTO test_insert VALUES(i, 'Name'||i);

EXCEPTION

WHEN abort_ex THEN

NULL;

END;

END LOOP;

COMMIT;

END;

SELECT * FROM test_insert;


DROP TABLE test_insert;

SQLERRM and SQLCODE

********************

SQLCODE returns the current error code, and SQLERRM returns the current error message
text;

For user-defined exception SQLCODE returns 1 and SQLERRM returns “user-defined


exception”.

SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.

CREATE TABLE test_tb (id NUMBER);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

dbms_output.put_line(v_id);

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('SQLERRM : ' || SQLERRM);

dbms_output.put_line('SQLCODE : ' || SQLCODE);

END;
/*sample output*/

SQLERRM : ORA-01403: no data found

SQLCODE : 100

DROP TABLE test_tb;

PRAGMA EXCEPTION_INIT

*********************

Using this you can associate a named exception with a particular oracle error.

This gives you the ability to trap this error specifically, rather than via an OTHERS handler.

Syntax:

PRAGMA EXCEPTION_INIT(exception_name, oracle_error_number);

DECLARE

v_result NUMBER;

PRAGMA EXCEPTION_INIT(Invalid, -1476);

BEGIN

SELECT 453 / 0 INTO v_result FROM dual;

dbms_output.put_line('Result : ' || v_result);

EXCEPTION
WHEN INVALID THEN

dbms_output.put_line('Invalid Exception');

END;

RAISE_APPLICATION_ERROR

************************

You can use this built-in function to create your own error messages, which can be more
descriptive than named exceptions.

Error Number :

Oracle Error Range : From -00000 to -19999

User Error Range : From -20000 to -20999

DECLARE

v_gender CHAR := '&gender';

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE_APPLICATION_ERROR(-20003, 'Enter valid gender');

END IF;

dbms_output.put_line('Gender : ' || v_gender);


END;

Posted 21st October 2014 by Unknown

1 View comments

Loading

Dynamic Views theme. Powered by Blogger.

Oracle sql & Pl/sql

search

Home Sql and pl/sql Sql Interview Questions

JUL

20

INLINE view in Oracle with 12c New Features

Named sub Query in FROM clause is call it as INLINE VIEW.

Oracle process a inline view faster than sub query

Inline View in Oracle


--Query to display all the employees who are all getting salary more than their department
average salary

SELECT First_name

, last_name

, salary

, department_id

FROM employees a , ( SELECT b.department_id

, AVG(b.salary) avg_sal

FROM employees b

GROUP BY b.department_id

)b

WHERE a.department_id = b.department_id

AND a.salary > b.avg_salary;

Display all the customer who have placed more number of orders by using INLINE view

CREATE TABLE customer_order_det_tb

( custm_id NUMBER ,

custm_nm VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

ttl_amt NUMBER(7,2)

);

BEGIN
INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '11-Jul-15' , 45000.00);

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '14-Jul-15' , 27000.00);

INSERT INTO customer_order_det_tb VALUES(101, 'Raja' , '13-Jul-15' , 17000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 34000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 38000.00);

COMMIT;

END;

SELECT c.*

FROM customer_order_det_tb c;

--------------------------------------------

custm_id custm_nm order_dt ttl_amt

--------------------------------------------

100 Murugappan 7/11/2015 45000.00

100 Murugappan 7/14/2015 27000.00

101 Raja 7/13/2015 17000.00

102 Ramesh 7/15/2015 34000.00

102 Ramesh 7/15/2015 38000.00

--------------------------------------------

--Writing a Quer to display all the customer who have placed maximum number of order

--Query #1 for inline view


SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC;

--------------------------------

custm_id custm_nm total_odr

--------------------------------

100 Murugappan 2

102 Ramesh 2

101 Raja 1

--------------------------------

--Query #2 for inline view

SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm;

----------

total_odr

----------

----------
Inline view to find all the customers who have placed maximum number of orders

/****************************************

Syntax

SELECT * FROM <query1> x, <query2> y

WHERE contition;

****************************************/

SELECT query1.* FROM

( SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC

) query1,

( SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm

) query2

WHERE query1.total_odr = query2.total_odr;

-------------------------------

custm_id custm_nm total_odr

-------------------------------
100 Murugappan 2

102 Ramesh 2

-------------------------------

DROP TABLE customer_order_det_tb;

--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT

SELECT first_name, salary

FROM ( SELECT first_name, salary

FROM employees e

WHERE job_id NOT IN ('SALESMAN','PRESIDENT')

ORDER BY salary DESC

WHERE ROWNUM < 4;

New Oracle 12c Inline view Syntax

LATERAL clause for In-line views

Allows for columns in the inline view to be accessed!!

Example :
--in 11g

SELECT * FROM employees e, (

SELECT *

FROM departments d

WHERE e.department_id = d.department_id);

ORA-0090: "E"."DEPARTMENT_ID": Invalid Identifier

--in 12c

SELECT * FROM employees e, LATERAL(

SELECT *

FROM departments d

WHERE e.department_id = d.department_id

);

--in 11g

WITH t

AS

( SELECT LEVEL a

FROM dual

CONNECT BY LEVEL <= 30)

SELECT *
FROM t, (SELECT *

FROM employees

WHERE department_id = t.a

);

ORA-00904: "T"."A": invalid Identifier

--in 12c

WITH t

AS

(SELECT LEVEL a FROM dual CONNECT BY LEVEL <= 30)

SELECT * FROM t,

LATERAL(SELECT *

FROM employees

WHERE department_id = t.a);

Hope you have enjoyed this little article

Feed backs are always Welcome :) (:

Posted 20th July 2015 by Unknown

0 Add a comment

JAN

23

Salary Related Questions in Oracle


--creating table

CREATE TABLE employee_data

eid NUMBER(4),

ename VARCHAR2(30),

depno NUMBER(3),

salary NUMBER(8)

);

BEGIN

--Inserting records

INSERT INTO employee_data VALUES(1000,'Name01',90,30000);

INSERT INTO employee_data VALUES(1001,'Name02',90,6000);

INSERT INTO employee_data VALUES(1002,'Name03',90,23000);

INSERT INTO employee_data VALUES(1003,'Name04',60,35000);

INSERT INTO employee_data VALUES(1004,'Name05',60,60000);

INSERT INTO employee_data VALUES(1005,'Name06',60,30000);


INSERT INTO employee_data VALUES(1006,'Name07',80,36000);

INSERT INTO employee_data VALUES(1007,'Name08',80,29000);

INSERT INTO employee_data VALUES(1008,'Name09',80,37000);

INSERT INTO employee_data VALUES(1009,'Name10',80,41000);

COMMIT;

END;

SELECT * FROM employee_data

ORDER BY salary DESC;

--query to find maximum salary from employee_data table

SELECT MAX(salary) FROM employee_data;

--query to find minimum salary from employee_data table

SELECT MIN(salary) FROM employee_data;

--query to find second maximum salary from employee_data table

SELECT MAX(salary)

FROM employee_data

WHERE salary NOT IN (SELECT MAX(salary)


FROM employee_data);

--query to select 5th maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= 5);

--query to select nth maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= &n);

--query to select all the details of the employee whose getting nth maximum salary

SELECT *
FROM (SELECT emp.*,

rownum rn

FROM (SELECT *

FROM employee_data

ORDER BY salary DESC) emp)

WHERE rn = 9;

--same query using row_numbr( ) function

SELECT *

FROM (SELECT emp.*,

row_number() over(ORDER BY salary) rank

FROM employee_data emp)

WHERE rank = 9;

--same query using rank( ) function

SELECT *

FROM (SELECT emp.*,

rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--same query using dense_rank( ) function


SELECT *

FROM (SELECT emp.*,

dense_rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--query to display display maximum salary in all the department

SELECT e.depno "Department id",

MAX(salary) "Maximum Salary"

FROM employee_data e

GROUP BY e.depno;

--query to display all the employees who are all getting salary more than average salary of the
company

SELECT e.* FROM employee_data e

WHERE salary > (SELECT AVG(salary) FROM employee_data);

--query to display all the employees who are all getting salary more than their department
average salary

SELECT employee_id,

first_name,
salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE department_id = OUT.department_id);

--query to display all the employees who are all getting salary more than their manager salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE employee_id = OUT.manager_id);

Documented By : Murugappan Annamalai

Posted on : 23-Jan-15 16:34:00 IST.

Hope you have enjoyed this little article


Feed backs are always welcome :)

Posted 23rd January 2015 by Unknown

7 View comments

JAN

22

Why prefer COALESCE over NVL

Documented By : Nimish Garg

I prefer using "COALESCE" over "NVL" is some of the scenarios. Last week One of my friend
asked me what is the advantage of using "COALESCE" where we can simply use "NVL". I simply
gave him the reply from Oracle Docs i.e. NVL lets you replace null (returned as a blank) with a
string in the results of a query and COALESCE returns the first non-null expr in the expression list.
Oracle Database uses short-circuit evaluation with "COALESCE".

He replied that he knows the difference, he knows that "COALESCE" can take multiple arguments
and so on. He was more interested in understanding "short-circuit evaluation" of "COALESCE"
and the scenarios where I prefer using "COALESCE" over "NVL".

To make him understand I created following function which takes One second in every execution
and simply returns '--null--' and executed 2 very similar queries one with NVL and other with
COALESCE.

SQL> create or replace function f_null return varchar2

2 is

3 begin
4 dbms_lock.sleep(1);

5 return '--null--';

6 end;

7 /

Function created.

Following are the queries which I used to demonstrate that NVL evaluates both arguments even
if the second argument is not used and COALESCE uses short-circuit evaluation i.e. it only
evaluates the arguments only if they are needed.

SQL> select e.empno, e.ename ename, nvl(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK


7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.

Elapsed: 00:00:14.01

SQL> select e.empno, e.ename ename, coalesce(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK


7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.

Elapsed: 00:00:01.01

Here we can see easily that the first query with NVL took 14+ seconds, one second for each
record even if the "f_null" value was used only in one record. On the contrary as mentioned in
Oracle Documentation "COALESCE" uses its "short-circuit evaluation" and "f_null" was called
only once and so second query took only One Second. "COALESCE" is certainly use less resources
than NVL.

Posted 22nd January 2015 by Unknown

0 Add a comment

DEC

21

Constraints

It Enforce Rule On Table


We can create constraint at the time of Creating Table

1. Column Level Declaration

2. Table Level Declaration

1. We can provide own name.

Format : [part_of_project_name-table_name-column_name-constraint_type]

Example : gmind_emp_id_pk _uk _ck _f

2. system name name

Format : sys_cn

Example : SYS_C405323

We can create constraint after the table has been created

Types
Primary Key

Not allowed Null value

Not allowed you to enter duplicate value

Ex : Employee_id, Student_id

Unique Key

allowed Null value

Not allowed you to enter duplicate value

Ex : Contact_no, email

Foreign Key

It will allowed you to enter NULL and Duplicate value.

c1(pk) : 1 2 3

c2(f) : 1 1 2 3 4 Not allowed

Allowed you to enter duplicate value and null value

Not Null
It will not allowed you to enter null value

Check

You can check your own condition

Simple Table for understanding

------------------------------------

Duplicate NULL

------------------------------------

Primary Key X X

Unique Key X Allowed

Foreign Key Allowed Allowed

------------------------------------

creating table with all constraint type

Create table my_stu_details

S_id Number(2),

S_name Varchar2(30) Not Null, --SYS_Cn


s_mail Varchar2(30),

s_gender char(1),

s_did Number(3),

Constraint my_stu_sid_pk PRIMARY KEY (s_id),

constraint my_stu_mail_uk UNIQUE (s_mail) ,

Constraint my_stu_gen_ck CHECK (s_gender IN ('M', 'F', 'm', 'f')),

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

);

DESC my_stu_details;

------------------------------------

Name Type Nullable

------------------------------------

S_ID NUMBER(2)

S_NAME VARCHAR2(30)

S_MAIL VARCHAR2(30) Y

S_GENDER CHAR(1) Y

S_DID NUMBER(3) Y

------------------------------------

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name1' , 'name1@gmail.com' , 'm' , 60 );


Select * from my_stu_details;

Validating Primary Key

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-00001: unique constraint (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (NULL, 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-01400: cannot insert NULL into (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (2 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

Select * from my_stu_details;


Validating NOT NULL Constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , NULL , 'name3@gmail.com' , 'F' , 80 );

ORA-01400: cannot insert NULL into ("HR"."MY_STU_DETAILS"."S_NAME")

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , 'Name3' , 'name3@gmail.com' , 'F' , 80 );

Select * from my_stu_details;

Validating Unique Key Constraint

--Duplicate Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)


values (4 , 'Name4' , 'name3@gmail.com' , 'F' , 80 );

ORA-00001: unique constraint (HR.MY_STU_MAIL_UK) violated

--Null Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , null , 'M' , 70 );

Select * from my_stu_details;

Validating Check constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'j' , 70 );

ORA-02290: check constraint (HR.MY_STU_GEN_CK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'M' , 70 );


Select * from my_stu_details;

Validating Foreign Key

Select * from Departments;

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 3 );

ORA-02291: integrity constraint (HR.MY_STU_DID_FK) violated - parent key not found

Departments table : parent table

my_stu_details : Child table

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 90 );

Select * from my_stu_details;


--------------------------------------------------------

s_id s_name s_mail s_gender s_did

--------------------------------------------------------

1 name1 name1@gmail.com m 60

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 M 70

5 Name5 name5@gmail.com M 70

6 Name6 name6@gmail.com F 90

--------------------------------------------------------

Deleting the Primary key value which is referred by Foreign Key

Select * from Departments;

DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID

------------------------------------------------------------

60 IT 103 1400 <---- Delete

-- don't execute this query


--Delete From Departments

--Where Department_id = 60;

1) ON DELETE SET NULL

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

1 name1 name1@gmail.com m -

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

2) ON DELETE SET CASCADE

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80
4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

Syntax

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE CASCADE

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE SET NULL

Constraint Related Data Dictionary Table information.

To view constraint Information

SELECT c.owner,

c.constraint_name,

c.constraint_type,

c.table_name,

c.r_constraint_name,

c.status

FROM user_constraints c
WHERE c.table_name = 'MY_STU_DETAILS';

------------------------------------------------------------------------------------

owner constraint_name constraint_type table_name r_constraint_name status

------------------------------------------------------------------------------------

HR SYS_C004023 C MY_STU_DETAILS ENABLED

HR MY_STU_GEN_CK C MY_STU_DETAILS ENABLED

HR MY_STU_SID_PK P MY_STU_DETAILS ENABLED

HR MY_STU_MAIL_UK U MY_STU_DETAILS ENABLED

HR MY_STU_DID_FK R MY_STU_DETAILS DEPT_ID_PK ENABLED

------------------------------------------------------------------------------------

To view constraint name with corresponding column name

SELECT * FROM user_cons_columns c

WHERE c.table_name = 'MY_STU_DETAILS';

-------------------------------------------------------------

owner constraint_name table_name column_name position

-------------------------------------------------------------

HR MY_STU_MAIL_UK MY_STU_DETAILS S_MAIL 1

HR MY_STU_SID_PK MY_STU_DETAILS S_ID 1


HR MY_STU_GEN_CK MY_STU_DETAILS S_GENDER

HR SYS_C004023 MY_STU_DETAILS S_NAME

HR MY_STU_DID_FK MY_STU_DETAILS S_DID 1

-------------------------------------------------------------

Creating Composite Primary Key

Creating Primary Key with more than one number of column

ALTER TABLE table_name

ADD CONSTRAINT constraint_name PRIMARY KEY(column1, column_2 , column3);

In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.

creating constraint after the table creation

ALTER TABLE table_name

ADD CONSTRAINT constraint_name CONSTRAINT_TYPE(column_name);

ALTER TABLE table_name

DROP CONSTRAINT constraint_name;


ALTER TABLE table_name

DROP PRIMARY KEY;

To drop related foreign key

ALTER TABLE table_name

DROP PRIMARY KEY CASCADE;

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name;

Disable constraint with related foreign key constraint

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name CASCADE;

ALTER TABLE table_name

ENABLE CONSTRAINT constraint_name;


Interview Questions

What are all the type of constraint available in oracle?

Difference between PRIMARY KEY and UNIQUE key.

Difference between PRIMARY KEY ans FOREIGN KEY.

Difference between UNIQUE key and FOREIGN KEY.

Is it possible to create tow primary key in single table.

Write a syntax to create FOREIGN constraint.

How to create constraint after the table has been created?

How to enable and disable a constraint.

Which data dictionary table contains information about constraints?

Which Data Dictionary table contains information about constraint with corresponding column
name?

What is composite primary key?

Explain ON DELETE CASCADE and ON DELETE SET NULL option.

~Thanks For Reading~

Post your valuable feedback below

Posted 21st December 2014 by Unknown


1 View comments

UnknownMay 22, 2017 at 12:39 AM

good

Reply

DEC

listagg in Oracle 11g

Oracle 11gR2 listagg built-in function allows for many table columns to be displayed within a
single row, a non-first-normal form display

Syntax :

listagg(column_value,'delimiter') WITHIN GROUP(ORDER BY column_name)

--Example 1:

CREATE TABLE test_ins(empid NUMBER,product VARCHAR2(30));

BEGIN

INSERT INTO test_ins VALUES( 101,'pendrive');


INSERT INTO test_ins VALUES( 102,'toy');

INSERT INTO test_ins VALUES( 101,'ipod');

INSERT INTO test_ins VALUES( 102,'hat');

INSERT INTO test_ins VALUES( 103,'cpu');

INSERT INTO test_ins VALUES( 104,'pen');

INSERT INTO test_ins VALUES( 104,'car');

INSERT INTO test_ins VALUES( 104,'mat');

INSERT INTO test_ins VALUES( 105,'tv');

INSERT INTO test_ins VALUES( 106,'laptop');

commit;

END;

SELECT * FROM test_ins;

SELECT empid "Employee",

listagg(product,

',') within

GROUP (ORDER BY empid) "Products"

FROM test_ins

GROUP BY empid;

-->-- Result set --<--


DROP TABLE test_ins;

-->-- Example 2

select department_id "Department id", listagg(first_name,', ') WITHIN GROUP(ORDER BY


employee_id) "Employees"

FROM employees

WHERE department_id IN (10,20,30,60)

GROUP BY department_id;

-->-- Result set --<--


Posted 4th December 2014 by Unknown

0 Add a comment

NOV

Condition and Looping Statement

IF

IF ELSE

Multiple IF ELSE

LOOP

FOR LOOP

WHILE LOOP

create table test_udt(id NUMBER, salary NUMBER);

BEGIN

INSERT INTO test_udt VALUES(001,23000);

INSERT INTO test_udt VALUES(002,43000);

INSERT INTO test_udt VALUES(003,78000);


INSERT INTO test_udt VALUES(004,25000);

INSERT INTO test_udt VALUES(005,26000);

INSERT INTO test_udt VALUES(006,90000);

Commit;

END;

select * from test_udt;

IF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 1;

IF v_salary > 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;


END IF;

commit;

END;

IF ELSE

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

ELSE

UPDATE test_udt t

SET t.salary = v_salary+20007

WHERE t.id = v_id ;


END IF;

commit;

END;

--same example with less number of lines

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

v_salary := v_salary+10005;

ELSE

v_salary := v_salary+20007;

END IF;

UPDATE test_udt t

SET t.salary = v_salary


WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

Multiple IF ELSIF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 3;

IF v_id = 1 THEN

v_salary := 1000;

dbms_output.put_line('1 inside');

ELSIF v_id = 2 THEN

v_salary := 2000;

dbms_output.put_line('2 inside');
ELSIF v_id = 3 THEN

v_salary := 3000;

dbms_output.put_line('3 inside');

ELSIF v_id = 4 THEN

v_salary := 4000;

dbms_output.put_line('4 inside');

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

LOOP

--syntax

LOOP

--statements

--increment
--exit statement

END LOOP;

CREATE TABLE prod_details (pid VARCHAR2(3), pname VARCHAR2(30));

DECLARE

i NUMBER := 1;

x VARCHAR2(3);

BEGIN

LOOP

x := lpad(i,3,'0');

dbms_output.put_line('x value : '|| x);

INSERT INTO prod_details VALUES(i, 'Product '||i);

EXIT WHEN i >900;

i := i+1;

IF MOD(i,100) = 0 THEN

commit;

dbms_output.put_line('commit executed');

END IF;

END LOOP;

END;
SELECT * FROM prod_details ORDER BY 1;

DROP TABLE prod_details;

FOR LOOP

BEGIN

FOR I in 1..5

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

FOR LOOP - Reverse

BEGIN

FOR I in REVERSE 14..50

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

WHILE LOOP
DECLARE

i_val NUMBER:=0;

BEGIN

WHILE (i_val < 11)

LOOP

dbms_output.put_line('The value of I is '||i_val);

i_val := i_val + 1;

END LOOP;

END;

sample output:

The value of I is 0

The value of I is 1

The value of I is 2

The value of I is 3

The value of I is 4

The value of I is 5

The value of I is 6

The value of I is 7

The value of I is 8

The value of I is 9

The value of I is 10
Posted 8th November 2014 by Unknown

0 Add a comment

OCT

21

Bulk Collect

This is used for array fetches

With this you can retrieve multiple rows of data with a single round trip.

This reduces the number of context switches between the pl/sql and sql engines.

You can use bulk collect in both dynamic and static sql.

You can use bulk collect in select, fetch into and returning into clauses.

SQL engine automatically initializes and extends the collections you reference in the bulk
collect clause.

You can fetch into multiple collections with one column each.

You can use the limit clause of bulk collect to restrict the no of rows retrieved.

SELECT * FROM product_details;

-->-- Bulk collect in FETCH INTO --<--


DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Bulk collect in SELECT clause --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;
BEGIN

SELECT * BULK COLLECT INTO dta FROM product_details;

FOR i IN dta.FIRST .. dta.LAST LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- LIMIT in Bulk collect --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta LIMIT 30;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;
END;

-->-- Multiple fetches in INTO clause --<--

SELECT * FROM product_details;

DECLARE

TYPE alldata_typ1 IS TABLE OF product_details.p_id%TYPE;

TYPE alldata_typ2 IS TABLE OF product_details.p_name%TYPE;

dta1 alldata_typ1;

dta2 alldata_typ2;

CURSOR proddt_cur IS

SELECT p_id, p_name FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta1, dta2;

CLOSE proddt_cur;

FOR i IN dta1.FIRST .. dta1.COUNT LOOP

dbms_output.put_line('Department Id : ' || dta1(i));

END LOOP;
FOR i IN dta2.FIRST .. dta2.COUNT LOOP

dbms_output.put_line('Department Name : ' || dta2(i));

END LOOP;

END;

DROP TABLE dep_details;

DROP TABLE product_details;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Ref Cursor

This is unconstrained cursor which will return different types depends upon the user input.

Ref cursors cannot be closed implicitly.

Ref cursor with return type is called strong cursor.

Ref cursor without return type is called weak cursor.

You can declare ref cursor type in package spec as well as body.
You can declare ref cursor types in local subprograms or anonymous blocks.

CREATE OR REPLACE PROCEDURE ref_c_sp(dep_det_c IN OUT SYS_REFCURSOR)

AS

BEGIN

OPEN dep_det_c

FOR

SELECT * FROM dep_details d;

END;

DECLARE

dep_det_c SYS_REFCURSOR;

tab_data dep_details%ROWTYPE;

BEGIN

ref_c_sp(dep_det_c);

LOOP

FETCH dep_det_c INTO tab_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department Name : '|| tab_data.d_name);

END LOOP;

CLOSE dep_det_c;
END;

/*sample output*/

Department Name : Admin

Department Name : HR

Department Name : Sales

Department Name : Marketing

DROP PROCEDURE ref_c_sp;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Cursor

SQL Private work Area where the query get passed and executed.

Types
******

Implicit(SQL)

Explicit

-->-- advanced cursor types --<--

Parametrized Cursor

Ref Cursor

Implicit

********

ORACLE implicitly opens a cursor to process each SQL statement not associated with an
explicitly declared cursor.

PL/SQL lets you refer to the most recent implicit cursor as the SQL” cursor. So, although you
cannot use the OPEN,

FETCH, and CLOSE statements to control an implicit cursor, you can still use cursor attributes to
access information

about the most recently executed SQL statement.

Cursor Stages

**************

OPEN cursor_name

FETCH (with in loop)

CLOSE cursor_name

Explicit
The set of rows returned by a query can consist of zero, one, or multiple rows,

depending on how many rows meet your search criteria. When a query returns multiple rows,

you can explicitly define a cursor to process the rows. You use three commands to control the
cursor

Cursor Attributes

*****************

%FOUND

%NOTFOUND

%ISOPEN

%ROWCOUNT

%BULK_ROWCOUNT --<-- used to handle error while using bulk collection.

%BULK_EXCEPTIONS --<-- used to handle error while using bulk collection.

Cursor Declaration

DECLARE

CURSOR <cursor_name>

IS

<SELECT statement>

BEGIN

--> some stmt

END;

/
Cursor Loop

Loop

While Loop

For Loop

Cursor Clauses

Return

For update

Where current of

Bulk collect

-->-- creating table

create table product_details

p_id NUMBER,

p_name VARCHAR2(30),

p_order_dt DATE

);

-->-- Inserting data

BEGIN
FOR i IN 1 .. 75 LOOP

INSERT INTO product_details VALUES (i, 'prod_name_' || i, SYSDATE + i);

END LOOP;

commit;

END;

-->-- selecting data

SELECT * FROM product_details;

---------------------------------------------

p_id p_name p_order_dt

---------------------------------------------

1 prod_name_1 10/11/2014 3:48:32 PM

2 prod_name_2 10/12/2014 3:48:32 PM

3 prod_name_3 10/13/2014 3:48:32 PM

4 prod_name_4 10/14/2014 3:48:32 PM

5 prod_name_5 10/15/2014 3:48:32 PM

6 prod_name_6 10/16/2014 3:48:32 PM

7 prod_name_7 10/17/2014 3:48:32 PM

8 prod_name_8 10/18/2014 3:48:32 PM

9 prod_name_9 10/19/2014 3:48:32 PM

10 prod_name_10 10/20/2014 3:48:32 PM

11 prod_name_11 10/21/2014 3:48:32 PM


12 prod_name_12 10/22/2014 3:48:32 PM

13 prod_name_13 10/23/2014 3:48:32 PM

14 prod_name_14 10/24/2014 3:48:32 PM

15 prod_name_15 10/25/2014 3:48:32 PM

16 prod_name_16 10/26/2014 3:48:32 PM

17 prod_name_17 10/27/2014 3:48:32 PM

18 prod_name_18 10/28/2014 3:48:32 PM

19 prod_name_19 10/29/2014 3:48:32 PM

20 prod_name_20 10/30/2014 3:48:32 PM

---------------------------------------------

----------------------------------------------

Implicit Cursor

----------------------------------------------

--will update soon

----------------------------------------------

Explicit Cursor

----------------------------------------------

**********************************************

Processing cursor data by using LOOP

**********************************************
DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND; --<-- if next record not found means control will
come out from the loop

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )


Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

EXIT WHEN prod_detail_cur%FOUND; --<-- if next record found means control will come
out from the loop

END LOOP;

CLOSE prod_detail_cur;

END;
/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor Already closed

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS
SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

-->-- CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/
Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor closed

**********************************************

Processing cursor data by using WHILE LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

OPEN prod_detail_cur;

FETCH prod_detail_cur

INTO all_data;
WHILE prod_detail_cur%FOUND LOOP

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

FETCH prod_detail_cur

INTO all_data;

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

************************************************************

Processing cursor data by using FOR LOOP - CURSOR FOR LOOP

************************************************************

DECLARE
--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

FOR i IN prod_detail_cur

LOOP

dbms_output.put_line('Product id : ' || i.p_id ||

' Product Name : ' || i.p_name ||

' ( Orderd on : ' || TRIM(i.p_order_dt) || ' )');

END LOOP;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

Parameterized Cursor

*********************
This was used when you are going to use the cursor in more than one place with different
values for the same where clause.

Cursor parameters must be in mode.

Cursor parameters may have default values.

The scope of cursor parameter is within the select statement.

CREATE TABLE dep_details(d_id NUMBER,d_name VARCHAR2(30), location_id NUMBER);

BEGIN

INSRT INTO dep_details VALUES(001,'Admin',1010);

INSRT INTO dep_details VALUES(002,'HR',1010);

INSRT INTO dep_details VALUES(003,'Sales',1020);

INSRT INTO dep_details VALUES(004,'Marketing',1020);

commit;

END;

SELECT * FROM dep_details;

----------------------------

d_id d_name location_id

----------------------------

1 Admin 1010

2 HR 1010
3 Sales 1020

4 Marketing 1020

----------------------------

DECLARE

-->--Declaring parameterized cursor

CURSOR dep_det_c(p_location_id NUMBER) IS

SELECT * FROM dep_details d WHERE d.location_id = p_location_id;

all_data dep_details%ROWTYPE;

BEGIN

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

OPEN dep_det_c(1010);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

-->-- opening same cursor with different input value


OPEN dep_det_c(1020);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

END;

/*sample output*/

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 1 Department Name : Admin

Department id : 2 Department Name : HR

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 3 Department Name : Sales

Department id : 4 Department Name : Marketing

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Posted 21st October 2014 by Unknown


0 Add a comment

OCT

21

Handling Exception

Error Handling in oracle

ERROR

Any departure from the expected behavior of the system or program,

which stops the working of the system is an error.

Types : compile time error

Run time error

EXCEPTION

Any error or problem which one can handle and continue to work normally.

Handling Exception

When exception is raised, control passes to the exception section of the block.

i.e. EXCEPTION

WHEN name_of_exception THEN


Types : Pre Defined Exceptions

User Defined Exceptions

Predefined Exception

*********************

Oracle has predefined several exceptions that correspond to the most common oracle errors.

------------------------------------------------------------------------

Exception Oracle Error SQL Code Value

------------------------------------------------------------------------

ZERO_DIVIDE ORA-01476 -1476

NO_DATA_FOUND ORA-01403 +100

DUP_VAL_ON_INDEX ORA-00001 -1

TOO_MANY_ROWS ORA-01422 -1422

VALUE_ERROR ORA-06502 -6502

CURSOR_ALREADY_OPEN ORA-06511 -6511

OTHERS

------------------------------------------------------------------------

-->-- ZERO_DIVIDE --<--


Your program attempts to divide a number by zero.

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN ZERO_DIVIDE THEN

dbms_output.put_line('Divisor is equal to zero');

END;

-->-- NO_DATA_FOUND --<--

Single row SELECT returned no rows or your program referenced a deleted element in a nested
table

or an uninitialized element in an associative array (index-by table).

CREATE TABLE test_tb(id NUMBER PRIMARY KEY);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION
WHEN NO_DATA_FOUND THEN

dbms_output.put_line('There is no data inside the table');

END;

-->-- DUP_VAL_ON_INDEX --<--

A program attempted to insert duplicate values in a column that is constrained by a unique


index.

INSERT INTO test_tb VALUES (1);

INSERT INTO test_tb VALUES (2);

commit;

BEGIN

INSERT INTO test_tb VALUES (2);

EXCEPTION

WHEN DUP_VAL_ON_INDEX THEN

dbms_output.put_line('Duplicate values are not allowed');

END;

-->-- TOO_MANY_ROWS --<--


Single row SELECT returned multiple rows.

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN TOO_MANY_ROWS THEN

dbms_output.put_line('Query returning more than one row');

END;

DROP TABLE test_tb;

-->-- VALUE_ERROR --<--

An arithmetic, conversion, truncation, or size constraint error occurred.

DECLARE

num1 NUMBER(2);

BEGIN

num1 := 345;

EXCEPTION

WHEN VALUE_ERROR THEN

dbms_output.put_line('check the size of the variable');


END;

-->-- CURSOR_ALREADY_OPEN --<--

A program attempted to open an already opened cursor.

CREATE TABLE emp(id NUMBER, name VARCHAR2(30));

BEGIN

INSERT INTO emp VALUES(1,'Name1');

INSERT INTO emp VALUES(2,'Name2');

INSERT INTO emp VALUES(3,'Name3');

INSERT INTO emp VALUES(4,'Name4');

COMMIT;

END;

SELECT * FROM emp;

DECLARE

cursor emp_c IS

SELECT * FROM emp;

all_data emp%ROWTYPE;
BEGIN

OPEN emp_c;

OPEN emp_c;

NULL;

CLOSE emp_c;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

END;

DROP TABLE emp;

-->-- OTHERS --<--

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

WHEN OTHERS THEN

dbms_output.put_line('Some other error ' || SQLERRM);

END;
User Defined Exception

**********************

A user-defined exception is an error that is defined by the programmer.

User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,

exceptions have a type EXCEPTION and scope.

DECLARE

v_gender CHAR := '&gender';

gender_ex EXCEPTION;

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE gender_ex;

END IF;

dbms_output.put_line('Gender : '||v_gender);

EXCEPTION

WHEN gender_ex THEN

dbms_output.put_line('Please Enter valid gender');

END;
create table test_insert (id NUMBER, Name VARCHAR2(30));

DECLARE

abort_ex EXCEPTION;

BEGIN

FOR i IN 1..100

LOOP

BEGIN

IF mod(i,10)=0 THEN

RAISE abort_ex;

END IF;

INSERT INTO test_insert VALUES(i, 'Name'||i);

EXCEPTION

WHEN abort_ex THEN

NULL;

END;

END LOOP;

COMMIT;

END;

SELECT * FROM test_insert;

DROP TABLE test_insert;


SQLERRM and SQLCODE

********************

SQLCODE returns the current error code, and SQLERRM returns the current error message
text;

For user-defined exception SQLCODE returns 1 and SQLERRM returns “user-defined


exception”.

SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.

CREATE TABLE test_tb (id NUMBER);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

dbms_output.put_line(v_id);

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('SQLERRM : ' || SQLERRM);

dbms_output.put_line('SQLCODE : ' || SQLCODE);

END;

/*sample output*/

SQLERRM : ORA-01403: no data found


SQLCODE : 100

DROP TABLE test_tb;

PRAGMA EXCEPTION_INIT

*********************

Using this you can associate a named exception with a particular oracle error.

This gives you the ability to trap this error specifically, rather than via an OTHERS handler.

Syntax:

PRAGMA EXCEPTION_INIT(exception_name, oracle_error_number);

DECLARE

v_result NUMBER;

PRAGMA EXCEPTION_INIT(Invalid, -1476);

BEGIN

SELECT 453 / 0 INTO v_result FROM dual;

dbms_output.put_line('Result : ' || v_result);

EXCEPTION

WHEN INVALID THEN

dbms_output.put_line('Invalid Exception');

END;
RAISE_APPLICATION_ERROR

************************

You can use this built-in function to create your own error messages, which can be more
descriptive than named exceptions.

Error Number :

Oracle Error Range : From -00000 to -19999

User Error Range : From -20000 to -20999

DECLARE

v_gender CHAR := '&gender';

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE_APPLICATION_ERROR(-20003, 'Enter valid gender');

END IF;

dbms_output.put_line('Gender : ' || v_gender);

END;
Posted 21st October 2014 by Unknown

1 View comments

Loading

Dynamic Views theme. Powered by Blogger.

Oracle sql & Pl/sql

search

Home Sql and pl/sql Sql Interview Questions

JUL

20

INLINE view in Oracle with 12c New Features

Named sub Query in FROM clause is call it as INLINE VIEW.

Oracle process a inline view faster than sub query

Inline View in Oracle

--Query to display all the employees who are all getting salary more than their department
average salary

SELECT First_name
, last_name

, salary

, department_id

FROM employees a , ( SELECT b.department_id

, AVG(b.salary) avg_sal

FROM employees b

GROUP BY b.department_id

)b

WHERE a.department_id = b.department_id

AND a.salary > b.avg_salary;

Display all the customer who have placed more number of orders by using INLINE view

CREATE TABLE customer_order_det_tb

( custm_id NUMBER ,

custm_nm VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

ttl_amt NUMBER(7,2)

);

BEGIN

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '11-Jul-15' , 45000.00);

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '14-Jul-15' , 27000.00);

INSERT INTO customer_order_det_tb VALUES(101, 'Raja' , '13-Jul-15' , 17000.00);


INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 34000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 38000.00);

COMMIT;

END;

SELECT c.*

FROM customer_order_det_tb c;

--------------------------------------------

custm_id custm_nm order_dt ttl_amt

--------------------------------------------

100 Murugappan 7/11/2015 45000.00

100 Murugappan 7/14/2015 27000.00

101 Raja 7/13/2015 17000.00

102 Ramesh 7/15/2015 34000.00

102 Ramesh 7/15/2015 38000.00

--------------------------------------------

--Writing a Quer to display all the customer who have placed maximum number of order

--Query #1 for inline view

SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC;

--------------------------------

custm_id custm_nm total_odr

--------------------------------

100 Murugappan 2

102 Ramesh 2

101 Raja 1

--------------------------------

--Query #2 for inline view

SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm;

----------

total_odr

----------

----------

Inline view to find all the customers who have placed maximum number of orders
/****************************************

Syntax

SELECT * FROM <query1> x, <query2> y

WHERE contition;

****************************************/

SELECT query1.* FROM

( SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC

) query1,

( SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm

) query2

WHERE query1.total_odr = query2.total_odr;

-------------------------------

custm_id custm_nm total_odr

-------------------------------

100 Murugappan 2

102 Ramesh 2

-------------------------------
DROP TABLE customer_order_det_tb;

--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT

SELECT first_name, salary

FROM ( SELECT first_name, salary

FROM employees e

WHERE job_id NOT IN ('SALESMAN','PRESIDENT')

ORDER BY salary DESC

WHERE ROWNUM < 4;

New Oracle 12c Inline view Syntax

LATERAL clause for In-line views

Allows for columns in the inline view to be accessed!!

Example :

--in 11g

SELECT * FROM employees e, (


SELECT *

FROM departments d

WHERE e.department_id = d.department_id);

ORA-0090: "E"."DEPARTMENT_ID": Invalid Identifier

--in 12c

SELECT * FROM employees e, LATERAL(

SELECT *

FROM departments d

WHERE e.department_id = d.department_id

);

--in 11g

WITH t

AS

( SELECT LEVEL a

FROM dual

CONNECT BY LEVEL <= 30)

SELECT *

FROM t, (SELECT *

FROM employees

WHERE department_id = t.a


);

ORA-00904: "T"."A": invalid Identifier

--in 12c

WITH t

AS

(SELECT LEVEL a FROM dual CONNECT BY LEVEL <= 30)

SELECT * FROM t,

LATERAL(SELECT *

FROM employees

WHERE department_id = t.a);

Hope you have enjoyed this little article

Feed backs are always Welcome :) (:

Posted 20th July 2015 by Unknown

0 Add a comment

JAN

23

Salary Related Questions in Oracle


--creating table

CREATE TABLE employee_data

eid NUMBER(4),

ename VARCHAR2(30),

depno NUMBER(3),

salary NUMBER(8)

);

BEGIN

--Inserting records

INSERT INTO employee_data VALUES(1000,'Name01',90,30000);

INSERT INTO employee_data VALUES(1001,'Name02',90,6000);

INSERT INTO employee_data VALUES(1002,'Name03',90,23000);

INSERT INTO employee_data VALUES(1003,'Name04',60,35000);

INSERT INTO employee_data VALUES(1004,'Name05',60,60000);

INSERT INTO employee_data VALUES(1005,'Name06',60,30000);

INSERT INTO employee_data VALUES(1006,'Name07',80,36000);

INSERT INTO employee_data VALUES(1007,'Name08',80,29000);

INSERT INTO employee_data VALUES(1008,'Name09',80,37000);


INSERT INTO employee_data VALUES(1009,'Name10',80,41000);

COMMIT;

END;

SELECT * FROM employee_data

ORDER BY salary DESC;

--query to find maximum salary from employee_data table

SELECT MAX(salary) FROM employee_data;

--query to find minimum salary from employee_data table

SELECT MIN(salary) FROM employee_data;

--query to find second maximum salary from employee_data table

SELECT MAX(salary)

FROM employee_data

WHERE salary NOT IN (SELECT MAX(salary)

FROM employee_data);

--query to select 5th maximum salary


SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= 5);

--query to select nth maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= &n);

--query to select all the details of the employee whose getting nth maximum salary

SELECT *

FROM (SELECT emp.*,

rownum rn

FROM (SELECT *
FROM employee_data

ORDER BY salary DESC) emp)

WHERE rn = 9;

--same query using row_numbr( ) function

SELECT *

FROM (SELECT emp.*,

row_number() over(ORDER BY salary) rank

FROM employee_data emp)

WHERE rank = 9;

--same query using rank( ) function

SELECT *

FROM (SELECT emp.*,

rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--same query using dense_rank( ) function

SELECT *

FROM (SELECT emp.*,


dense_rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--query to display display maximum salary in all the department

SELECT e.depno "Department id",

MAX(salary) "Maximum Salary"

FROM employee_data e

GROUP BY e.depno;

--query to display all the employees who are all getting salary more than average salary of the
company

SELECT e.* FROM employee_data e

WHERE salary > (SELECT AVG(salary) FROM employee_data);

--query to display all the employees who are all getting salary more than their department
average salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)


FROM employees

WHERE department_id = OUT.department_id);

--query to display all the employees who are all getting salary more than their manager salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE employee_id = OUT.manager_id);

Documented By : Murugappan Annamalai

Posted on : 23-Jan-15 16:34:00 IST.

Hope you have enjoyed this little article

Feed backs are always welcome :)

Posted 23rd January 2015 by Unknown


7 View comments

JAN

22

Why prefer COALESCE over NVL

Documented By : Nimish Garg

I prefer using "COALESCE" over "NVL" is some of the scenarios. Last week One of my friend
asked me what is the advantage of using "COALESCE" where we can simply use "NVL". I simply
gave him the reply from Oracle Docs i.e. NVL lets you replace null (returned as a blank) with a
string in the results of a query and COALESCE returns the first non-null expr in the expression list.
Oracle Database uses short-circuit evaluation with "COALESCE".

He replied that he knows the difference, he knows that "COALESCE" can take multiple arguments
and so on. He was more interested in understanding "short-circuit evaluation" of "COALESCE"
and the scenarios where I prefer using "COALESCE" over "NVL".

To make him understand I created following function which takes One second in every execution
and simply returns '--null--' and executed 2 very similar queries one with NVL and other with
COALESCE.

SQL> create or replace function f_null return varchar2

2 is

3 begin

4 dbms_lock.sleep(1);

5 return '--null--';

6 end;
7 /

Function created.

Following are the queries which I used to demonstrate that NVL evaluates both arguments even
if the second argument is not used and COALESCE uses short-circuit evaluation i.e. it only
evaluates the arguments only if they are needed.

SQL> select e.empno, e.ename ename, nvl(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING


7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.

Elapsed: 00:00:14.01

SQL> select e.empno, e.ename ename, coalesce(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING


7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.

Elapsed: 00:00:01.01

Here we can see easily that the first query with NVL took 14+ seconds, one second for each
record even if the "f_null" value was used only in one record. On the contrary as mentioned in
Oracle Documentation "COALESCE" uses its "short-circuit evaluation" and "f_null" was called
only once and so second query took only One Second. "COALESCE" is certainly use less resources
than NVL.

Posted 22nd January 2015 by Unknown

0 Add a comment

DEC

21

Constraints

It Enforce Rule On Table


We can create constraint at the time of Creating Table

1. Column Level Declaration

2. Table Level Declaration

1. We can provide own name.

Format : [part_of_project_name-table_name-column_name-constraint_type]

Example : gmind_emp_id_pk _uk _ck _f

2. system name name

Format : sys_cn

Example : SYS_C405323

We can create constraint after the table has been created

Types

Primary Key
Not allowed Null value

Not allowed you to enter duplicate value

Ex : Employee_id, Student_id

Unique Key

allowed Null value

Not allowed you to enter duplicate value

Ex : Contact_no, email

Foreign Key

It will allowed you to enter NULL and Duplicate value.

c1(pk) : 1 2 3

c2(f) : 1 1 2 3 4 Not allowed

Allowed you to enter duplicate value and null value

Not Null

It will not allowed you to enter null value

Check
You can check your own condition

Simple Table for understanding

------------------------------------

Duplicate NULL

------------------------------------

Primary Key X X

Unique Key X Allowed

Foreign Key Allowed Allowed

------------------------------------

creating table with all constraint type

Create table my_stu_details

S_id Number(2),

S_name Varchar2(30) Not Null, --SYS_Cn

s_mail Varchar2(30),

s_gender char(1),

s_did Number(3),
Constraint my_stu_sid_pk PRIMARY KEY (s_id),

constraint my_stu_mail_uk UNIQUE (s_mail) ,

Constraint my_stu_gen_ck CHECK (s_gender IN ('M', 'F', 'm', 'f')),

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

);

DESC my_stu_details;

------------------------------------

Name Type Nullable

------------------------------------

S_ID NUMBER(2)

S_NAME VARCHAR2(30)

S_MAIL VARCHAR2(30) Y

S_GENDER CHAR(1) Y

S_DID NUMBER(3) Y

------------------------------------

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name1' , 'name1@gmail.com' , 'm' , 60 );


Select * from my_stu_details;

Validating Primary Key

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-00001: unique constraint (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (NULL, 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-01400: cannot insert NULL into (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (2 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

Validating NOT NULL Constraint


Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , NULL , 'name3@gmail.com' , 'F' , 80 );

ORA-01400: cannot insert NULL into ("HR"."MY_STU_DETAILS"."S_NAME")

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , 'Name3' , 'name3@gmail.com' , 'F' , 80 );

Select * from my_stu_details;

Validating Unique Key Constraint

--Duplicate Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , 'name3@gmail.com' , 'F' , 80 );

ORA-00001: unique constraint (HR.MY_STU_MAIL_UK) violated


--Null Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , null , 'M' , 70 );

Select * from my_stu_details;

Validating Check constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'j' , 70 );

ORA-02290: check constraint (HR.MY_STU_GEN_CK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'M' , 70 );

Select * from my_stu_details;


Validating Foreign Key

Select * from Departments;

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 3 );

ORA-02291: integrity constraint (HR.MY_STU_DID_FK) violated - parent key not found

Departments table : parent table

my_stu_details : Child table

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

--------------------------------------------------------

s_id s_name s_mail s_gender s_did


--------------------------------------------------------

1 name1 name1@gmail.com m 60

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 M 70

5 Name5 name5@gmail.com M 70

6 Name6 name6@gmail.com F 90

--------------------------------------------------------

Deleting the Primary key value which is referred by Foreign Key

Select * from Departments;

DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID

------------------------------------------------------------

60 IT 103 1400 <---- Delete

-- don't execute this query

--Delete From Departments

--Where Department_id = 60;


1) ON DELETE SET NULL

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

1 name1 name1@gmail.com m -

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

2) ON DELETE SET CASCADE

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------
Syntax

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE CASCADE

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE SET NULL

Constraint Related Data Dictionary Table information.

To view constraint Information

SELECT c.owner,

c.constraint_name,

c.constraint_type,

c.table_name,

c.r_constraint_name,

c.status

FROM user_constraints c

WHERE c.table_name = 'MY_STU_DETAILS';


------------------------------------------------------------------------------------

owner constraint_name constraint_type table_name r_constraint_name status

------------------------------------------------------------------------------------

HR SYS_C004023 C MY_STU_DETAILS ENABLED

HR MY_STU_GEN_CK C MY_STU_DETAILS ENABLED

HR MY_STU_SID_PK P MY_STU_DETAILS ENABLED

HR MY_STU_MAIL_UK U MY_STU_DETAILS ENABLED

HR MY_STU_DID_FK R MY_STU_DETAILS DEPT_ID_PK ENABLED

------------------------------------------------------------------------------------

To view constraint name with corresponding column name

SELECT * FROM user_cons_columns c

WHERE c.table_name = 'MY_STU_DETAILS';

-------------------------------------------------------------

owner constraint_name table_name column_name position

-------------------------------------------------------------

HR MY_STU_MAIL_UK MY_STU_DETAILS S_MAIL 1

HR MY_STU_SID_PK MY_STU_DETAILS S_ID 1

HR MY_STU_GEN_CK MY_STU_DETAILS S_GENDER

HR SYS_C004023 MY_STU_DETAILS S_NAME

HR MY_STU_DID_FK MY_STU_DETAILS S_DID 1


-------------------------------------------------------------

Creating Composite Primary Key

Creating Primary Key with more than one number of column

ALTER TABLE table_name

ADD CONSTRAINT constraint_name PRIMARY KEY(column1, column_2 , column3);

In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.

creating constraint after the table creation

ALTER TABLE table_name

ADD CONSTRAINT constraint_name CONSTRAINT_TYPE(column_name);

ALTER TABLE table_name

DROP CONSTRAINT constraint_name;

ALTER TABLE table_name

DROP PRIMARY KEY;


To drop related foreign key

ALTER TABLE table_name

DROP PRIMARY KEY CASCADE;

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name;

Disable constraint with related foreign key constraint

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name CASCADE;

ALTER TABLE table_name

ENABLE CONSTRAINT constraint_name;

Interview Questions
What are all the type of constraint available in oracle?

Difference between PRIMARY KEY and UNIQUE key.

Difference between PRIMARY KEY ans FOREIGN KEY.

Difference between UNIQUE key and FOREIGN KEY.

Is it possible to create tow primary key in single table.

Write a syntax to create FOREIGN constraint.

How to create constraint after the table has been created?

How to enable and disable a constraint.

Which data dictionary table contains information about constraints?

Which Data Dictionary table contains information about constraint with corresponding column
name?

What is composite primary key?

Explain ON DELETE CASCADE and ON DELETE SET NULL option.

~Thanks For Reading~

Post your valuable feedback below

Posted 21st December 2014 by Unknown

1 View comments
UnknownMay 22, 2017 at 12:39 AM

good

Reply

DEC

listagg in Oracle 11g

Oracle 11gR2 listagg built-in function allows for many table columns to be displayed within a
single row, a non-first-normal form display

Syntax :

listagg(column_value,'delimiter') WITHIN GROUP(ORDER BY column_name)

--Example 1:

CREATE TABLE test_ins(empid NUMBER,product VARCHAR2(30));

BEGIN

INSERT INTO test_ins VALUES( 101,'pendrive');

INSERT INTO test_ins VALUES( 102,'toy');

INSERT INTO test_ins VALUES( 101,'ipod');

INSERT INTO test_ins VALUES( 102,'hat');


INSERT INTO test_ins VALUES( 103,'cpu');

INSERT INTO test_ins VALUES( 104,'pen');

INSERT INTO test_ins VALUES( 104,'car');

INSERT INTO test_ins VALUES( 104,'mat');

INSERT INTO test_ins VALUES( 105,'tv');

INSERT INTO test_ins VALUES( 106,'laptop');

commit;

END;

SELECT * FROM test_ins;

SELECT empid "Employee",

listagg(product,

',') within

GROUP (ORDER BY empid) "Products"

FROM test_ins

GROUP BY empid;

-->-- Result set --<--


DROP TABLE test_ins;

-->-- Example 2

select department_id "Department id", listagg(first_name,', ') WITHIN GROUP(ORDER BY


employee_id) "Employees"

FROM employees

WHERE department_id IN (10,20,30,60)

GROUP BY department_id;

-->-- Result set --<--

Posted 4th December 2014 by Unknown

0 Add a comment
NOV

Condition and Looping Statement

IF

IF ELSE

Multiple IF ELSE

LOOP

FOR LOOP

WHILE LOOP

create table test_udt(id NUMBER, salary NUMBER);

BEGIN

INSERT INTO test_udt VALUES(001,23000);

INSERT INTO test_udt VALUES(002,43000);

INSERT INTO test_udt VALUES(003,78000);

INSERT INTO test_udt VALUES(004,25000);

INSERT INTO test_udt VALUES(005,26000);

INSERT INTO test_udt VALUES(006,90000);


Commit;

END;

select * from test_udt;

IF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 1;

IF v_salary > 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

END IF;

commit;
END;

IF ELSE

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

ELSE

UPDATE test_udt t

SET t.salary = v_salary+20007

WHERE t.id = v_id ;

END IF;

commit;

END;
/

--same example with less number of lines

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

v_salary := v_salary+10005;

ELSE

v_salary := v_salary+20007;

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;
/

select * from test_udt;

Multiple IF ELSIF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 3;

IF v_id = 1 THEN

v_salary := 1000;

dbms_output.put_line('1 inside');

ELSIF v_id = 2 THEN

v_salary := 2000;

dbms_output.put_line('2 inside');

ELSIF v_id = 3 THEN

v_salary := 3000;

dbms_output.put_line('3 inside');
ELSIF v_id = 4 THEN

v_salary := 4000;

dbms_output.put_line('4 inside');

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

LOOP

--syntax

LOOP

--statements

--increment

--exit statement

END LOOP;
CREATE TABLE prod_details (pid VARCHAR2(3), pname VARCHAR2(30));

DECLARE

i NUMBER := 1;

x VARCHAR2(3);

BEGIN

LOOP

x := lpad(i,3,'0');

dbms_output.put_line('x value : '|| x);

INSERT INTO prod_details VALUES(i, 'Product '||i);

EXIT WHEN i >900;

i := i+1;

IF MOD(i,100) = 0 THEN

commit;

dbms_output.put_line('commit executed');

END IF;

END LOOP;

END;

SELECT * FROM prod_details ORDER BY 1;

DROP TABLE prod_details;


FOR LOOP

BEGIN

FOR I in 1..5

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

FOR LOOP - Reverse

BEGIN

FOR I in REVERSE 14..50

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

WHILE LOOP

DECLARE

i_val NUMBER:=0;
BEGIN

WHILE (i_val < 11)

LOOP

dbms_output.put_line('The value of I is '||i_val);

i_val := i_val + 1;

END LOOP;

END;

sample output:

The value of I is 0

The value of I is 1

The value of I is 2

The value of I is 3

The value of I is 4

The value of I is 5

The value of I is 6

The value of I is 7

The value of I is 8

The value of I is 9

The value of I is 10

Posted 8th November 2014 by Unknown


0 Add a comment

OCT

21

Bulk Collect

This is used for array fetches

With this you can retrieve multiple rows of data with a single round trip.

This reduces the number of context switches between the pl/sql and sql engines.

You can use bulk collect in both dynamic and static sql.

You can use bulk collect in select, fetch into and returning into clauses.

SQL engine automatically initializes and extends the collections you reference in the bulk
collect clause.

You can fetch into multiple collections with one column each.

You can use the limit clause of bulk collect to restrict the no of rows retrieved.

SELECT * FROM product_details;

-->-- Bulk collect in FETCH INTO --<--

DECLARE
TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Bulk collect in SELECT clause --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

BEGIN

SELECT * BULK COLLECT INTO dta FROM product_details;

FOR i IN dta.FIRST .. dta.LAST LOOP


dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- LIMIT in Bulk collect --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta LIMIT 30;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

/
-->-- Multiple fetches in INTO clause --<--

SELECT * FROM product_details;

DECLARE

TYPE alldata_typ1 IS TABLE OF product_details.p_id%TYPE;

TYPE alldata_typ2 IS TABLE OF product_details.p_name%TYPE;

dta1 alldata_typ1;

dta2 alldata_typ2;

CURSOR proddt_cur IS

SELECT p_id, p_name FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta1, dta2;

CLOSE proddt_cur;

FOR i IN dta1.FIRST .. dta1.COUNT LOOP

dbms_output.put_line('Department Id : ' || dta1(i));

END LOOP;

FOR i IN dta2.FIRST .. dta2.COUNT LOOP

dbms_output.put_line('Department Name : ' || dta2(i));


END LOOP;

END;

DROP TABLE dep_details;

DROP TABLE product_details;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Ref Cursor

This is unconstrained cursor which will return different types depends upon the user input.

Ref cursors cannot be closed implicitly.

Ref cursor with return type is called strong cursor.

Ref cursor without return type is called weak cursor.

You can declare ref cursor type in package spec as well as body.

You can declare ref cursor types in local subprograms or anonymous blocks.
CREATE OR REPLACE PROCEDURE ref_c_sp(dep_det_c IN OUT SYS_REFCURSOR)

AS

BEGIN

OPEN dep_det_c

FOR

SELECT * FROM dep_details d;

END;

DECLARE

dep_det_c SYS_REFCURSOR;

tab_data dep_details%ROWTYPE;

BEGIN

ref_c_sp(dep_det_c);

LOOP

FETCH dep_det_c INTO tab_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department Name : '|| tab_data.d_name);

END LOOP;

CLOSE dep_det_c;

END;
/*sample output*/

Department Name : Admin

Department Name : HR

Department Name : Sales

Department Name : Marketing

DROP PROCEDURE ref_c_sp;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Cursor

SQL Private work Area where the query get passed and executed.

Types

******

Implicit(SQL)

Explicit
-->-- advanced cursor types --<--

Parametrized Cursor

Ref Cursor

Implicit

********

ORACLE implicitly opens a cursor to process each SQL statement not associated with an
explicitly declared cursor.

PL/SQL lets you refer to the most recent implicit cursor as the SQL” cursor. So, although you
cannot use the OPEN,

FETCH, and CLOSE statements to control an implicit cursor, you can still use cursor attributes to
access information

about the most recently executed SQL statement.

Cursor Stages

**************

OPEN cursor_name

FETCH (with in loop)

CLOSE cursor_name

Explicit

The set of rows returned by a query can consist of zero, one, or multiple rows,

depending on how many rows meet your search criteria. When a query returns multiple rows,
you can explicitly define a cursor to process the rows. You use three commands to control the
cursor

Cursor Attributes

*****************

%FOUND

%NOTFOUND

%ISOPEN

%ROWCOUNT

%BULK_ROWCOUNT --<-- used to handle error while using bulk collection.

%BULK_EXCEPTIONS --<-- used to handle error while using bulk collection.

Cursor Declaration

DECLARE

CURSOR <cursor_name>

IS

<SELECT statement>

BEGIN

--> some stmt

END;

Cursor Loop

Loop
While Loop

For Loop

Cursor Clauses

Return

For update

Where current of

Bulk collect

-->-- creating table

create table product_details

p_id NUMBER,

p_name VARCHAR2(30),

p_order_dt DATE

);

-->-- Inserting data

BEGIN

FOR i IN 1 .. 75 LOOP

INSERT INTO product_details VALUES (i, 'prod_name_' || i, SYSDATE + i);

END LOOP;
commit;

END;

-->-- selecting data

SELECT * FROM product_details;

---------------------------------------------

p_id p_name p_order_dt

---------------------------------------------

1 prod_name_1 10/11/2014 3:48:32 PM

2 prod_name_2 10/12/2014 3:48:32 PM

3 prod_name_3 10/13/2014 3:48:32 PM

4 prod_name_4 10/14/2014 3:48:32 PM

5 prod_name_5 10/15/2014 3:48:32 PM

6 prod_name_6 10/16/2014 3:48:32 PM

7 prod_name_7 10/17/2014 3:48:32 PM

8 prod_name_8 10/18/2014 3:48:32 PM

9 prod_name_9 10/19/2014 3:48:32 PM

10 prod_name_10 10/20/2014 3:48:32 PM

11 prod_name_11 10/21/2014 3:48:32 PM

12 prod_name_12 10/22/2014 3:48:32 PM

13 prod_name_13 10/23/2014 3:48:32 PM

14 prod_name_14 10/24/2014 3:48:32 PM


15 prod_name_15 10/25/2014 3:48:32 PM

16 prod_name_16 10/26/2014 3:48:32 PM

17 prod_name_17 10/27/2014 3:48:32 PM

18 prod_name_18 10/28/2014 3:48:32 PM

19 prod_name_19 10/29/2014 3:48:32 PM

20 prod_name_20 10/30/2014 3:48:32 PM

---------------------------------------------

----------------------------------------------

Implicit Cursor

----------------------------------------------

--will update soon

----------------------------------------------

Explicit Cursor

----------------------------------------------

**********************************************

Processing cursor data by using LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;
--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND; --<-- if next record not found means control will
come out from the loop

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )


DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

EXIT WHEN prod_detail_cur%FOUND; --<-- if next record found means control will come
out from the loop

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )


DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE
dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor Already closed

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN
OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

-->-- CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )


Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor closed

**********************************************

Processing cursor data by using WHILE LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

OPEN prod_detail_cur;

FETCH prod_detail_cur

INTO all_data;

WHILE prod_detail_cur%FOUND LOOP

dbms_output.put_line('Product id : ' || all_data.p_id ||


' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

FETCH prod_detail_cur

INTO all_data;

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

************************************************************

Processing cursor data by using FOR LOOP - CURSOR FOR LOOP

************************************************************

DECLARE

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;


BEGIN

FOR i IN prod_detail_cur

LOOP

dbms_output.put_line('Product id : ' || i.p_id ||

' Product Name : ' || i.p_name ||

' ( Orderd on : ' || TRIM(i.p_order_dt) || ' )');

END LOOP;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

Parameterized Cursor

*********************

This was used when you are going to use the cursor in more than one place with different
values for the same where clause.

Cursor parameters must be in mode.


Cursor parameters may have default values.

The scope of cursor parameter is within the select statement.

CREATE TABLE dep_details(d_id NUMBER,d_name VARCHAR2(30), location_id NUMBER);

BEGIN

INSRT INTO dep_details VALUES(001,'Admin',1010);

INSRT INTO dep_details VALUES(002,'HR',1010);

INSRT INTO dep_details VALUES(003,'Sales',1020);

INSRT INTO dep_details VALUES(004,'Marketing',1020);

commit;

END;

SELECT * FROM dep_details;

----------------------------

d_id d_name location_id

----------------------------

1 Admin 1010

2 HR 1010

3 Sales 1020

4 Marketing 1020

----------------------------
DECLARE

-->--Declaring parameterized cursor

CURSOR dep_det_c(p_location_id NUMBER) IS

SELECT * FROM dep_details d WHERE d.location_id = p_location_id;

all_data dep_details%ROWTYPE;

BEGIN

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

OPEN dep_det_c(1010);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

-->-- opening same cursor with different input value

OPEN dep_det_c(1020);

LOOP
FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

END;

/*sample output*/

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 1 Department Name : Admin

Department id : 2 Department Name : HR

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 3 Department Name : Sales

Department id : 4 Department Name : Marketing

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Posted 21st October 2014 by Unknown

0 Add a comment
OCT

21

Handling Exception

Error Handling in oracle

ERROR

Any departure from the expected behavior of the system or program,

which stops the working of the system is an error.

Types : compile time error

Run time error

EXCEPTION

Any error or problem which one can handle and continue to work normally.

Handling Exception

When exception is raised, control passes to the exception section of the block.

i.e. EXCEPTION

WHEN name_of_exception THEN

Types : Pre Defined Exceptions

User Defined Exceptions


Predefined Exception

*********************

Oracle has predefined several exceptions that correspond to the most common oracle errors.

------------------------------------------------------------------------

Exception Oracle Error SQL Code Value

------------------------------------------------------------------------

ZERO_DIVIDE ORA-01476 -1476

NO_DATA_FOUND ORA-01403 +100

DUP_VAL_ON_INDEX ORA-00001 -1

TOO_MANY_ROWS ORA-01422 -1422

VALUE_ERROR ORA-06502 -6502

CURSOR_ALREADY_OPEN ORA-06511 -6511

OTHERS

------------------------------------------------------------------------

-->-- ZERO_DIVIDE --<--

Your program attempts to divide a number by zero.

DECLARE
v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN ZERO_DIVIDE THEN

dbms_output.put_line('Divisor is equal to zero');

END;

-->-- NO_DATA_FOUND --<--

Single row SELECT returned no rows or your program referenced a deleted element in a nested
table

or an uninitialized element in an associative array (index-by table).

CREATE TABLE test_tb(id NUMBER PRIMARY KEY);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN NO_DATA_FOUND THEN

dbms_output.put_line('There is no data inside the table');

END;
-->-- DUP_VAL_ON_INDEX --<--

A program attempted to insert duplicate values in a column that is constrained by a unique


index.

INSERT INTO test_tb VALUES (1);

INSERT INTO test_tb VALUES (2);

commit;

BEGIN

INSERT INTO test_tb VALUES (2);

EXCEPTION

WHEN DUP_VAL_ON_INDEX THEN

dbms_output.put_line('Duplicate values are not allowed');

END;

-->-- TOO_MANY_ROWS --<--

Single row SELECT returned multiple rows.

DECLARE
v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN TOO_MANY_ROWS THEN

dbms_output.put_line('Query returning more than one row');

END;

DROP TABLE test_tb;

-->-- VALUE_ERROR --<--

An arithmetic, conversion, truncation, or size constraint error occurred.

DECLARE

num1 NUMBER(2);

BEGIN

num1 := 345;

EXCEPTION

WHEN VALUE_ERROR THEN

dbms_output.put_line('check the size of the variable');

END;
-->-- CURSOR_ALREADY_OPEN --<--

A program attempted to open an already opened cursor.

CREATE TABLE emp(id NUMBER, name VARCHAR2(30));

BEGIN

INSERT INTO emp VALUES(1,'Name1');

INSERT INTO emp VALUES(2,'Name2');

INSERT INTO emp VALUES(3,'Name3');

INSERT INTO emp VALUES(4,'Name4');

COMMIT;

END;

SELECT * FROM emp;

DECLARE

cursor emp_c IS

SELECT * FROM emp;

all_data emp%ROWTYPE;

BEGIN

OPEN emp_c;

OPEN emp_c;
NULL;

CLOSE emp_c;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

END;

DROP TABLE emp;

-->-- OTHERS --<--

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

WHEN OTHERS THEN

dbms_output.put_line('Some other error ' || SQLERRM);

END;

User Defined Exception


**********************

A user-defined exception is an error that is defined by the programmer.

User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,

exceptions have a type EXCEPTION and scope.

DECLARE

v_gender CHAR := '&gender';

gender_ex EXCEPTION;

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE gender_ex;

END IF;

dbms_output.put_line('Gender : '||v_gender);

EXCEPTION

WHEN gender_ex THEN

dbms_output.put_line('Please Enter valid gender');

END;

create table test_insert (id NUMBER, Name VARCHAR2(30));

DECLARE
abort_ex EXCEPTION;

BEGIN

FOR i IN 1..100

LOOP

BEGIN

IF mod(i,10)=0 THEN

RAISE abort_ex;

END IF;

INSERT INTO test_insert VALUES(i, 'Name'||i);

EXCEPTION

WHEN abort_ex THEN

NULL;

END;

END LOOP;

COMMIT;

END;

SELECT * FROM test_insert;

DROP TABLE test_insert;

SQLERRM and SQLCODE

********************
SQLCODE returns the current error code, and SQLERRM returns the current error message
text;

For user-defined exception SQLCODE returns 1 and SQLERRM returns “user-defined


exception”.

SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.

CREATE TABLE test_tb (id NUMBER);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

dbms_output.put_line(v_id);

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('SQLERRM : ' || SQLERRM);

dbms_output.put_line('SQLCODE : ' || SQLCODE);

END;

/*sample output*/

SQLERRM : ORA-01403: no data found

SQLCODE : 100

DROP TABLE test_tb;


PRAGMA EXCEPTION_INIT

*********************

Using this you can associate a named exception with a particular oracle error.

This gives you the ability to trap this error specifically, rather than via an OTHERS handler.

Syntax:

PRAGMA EXCEPTION_INIT(exception_name, oracle_error_number);

DECLARE

v_result NUMBER;

PRAGMA EXCEPTION_INIT(Invalid, -1476);

BEGIN

SELECT 453 / 0 INTO v_result FROM dual;

dbms_output.put_line('Result : ' || v_result);

EXCEPTION

WHEN INVALID THEN

dbms_output.put_line('Invalid Exception');

END;
RAISE_APPLICATION_ERROR

************************

You can use this built-in function to create your own error messages, which can be more
descriptive than named exceptions.

Error Number :

Oracle Error Range : From -00000 to -19999

User Error Range : From -20000 to -20999

DECLARE

v_gender CHAR := '&gender';

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE_APPLICATION_ERROR(-20003, 'Enter valid gender');

END IF;

dbms_output.put_line('Gender : ' || v_gender);

END;

Posted 21st October 2014 by Unknown

1 View comments
Loading

Dynamic Views theme. Powered by Blogger.

Oracle sql & Pl/sql

search

Home Sql and pl/sql Sql Interview Questions

JUL

20

INLINE view in Oracle with 12c New Features

Named sub Query in FROM clause is call it as INLINE VIEW.

Oracle process a inline view faster than sub query

Inline View in Oracle

--Query to display all the employees who are all getting salary more than their department
average salary

SELECT First_name

, last_name

, salary

, department_id
FROM employees a , ( SELECT b.department_id

, AVG(b.salary) avg_sal

FROM employees b

GROUP BY b.department_id

)b

WHERE a.department_id = b.department_id

AND a.salary > b.avg_salary;

Display all the customer who have placed more number of orders by using INLINE view

CREATE TABLE customer_order_det_tb

( custm_id NUMBER ,

custm_nm VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

ttl_amt NUMBER(7,2)

);

BEGIN

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '11-Jul-15' , 45000.00);

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '14-Jul-15' , 27000.00);

INSERT INTO customer_order_det_tb VALUES(101, 'Raja' , '13-Jul-15' , 17000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 34000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 38000.00);

COMMIT;
END;

SELECT c.*

FROM customer_order_det_tb c;

--------------------------------------------

custm_id custm_nm order_dt ttl_amt

--------------------------------------------

100 Murugappan 7/11/2015 45000.00

100 Murugappan 7/14/2015 27000.00

101 Raja 7/13/2015 17000.00

102 Ramesh 7/15/2015 34000.00

102 Ramesh 7/15/2015 38000.00

--------------------------------------------

--Writing a Quer to display all the customer who have placed maximum number of order

--Query #1 for inline view

SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC;


--------------------------------

custm_id custm_nm total_odr

--------------------------------

100 Murugappan 2

102 Ramesh 2

101 Raja 1

--------------------------------

--Query #2 for inline view

SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm;

----------

total_odr

----------

----------

Inline view to find all the customers who have placed maximum number of orders

/****************************************

Syntax
SELECT * FROM <query1> x, <query2> y

WHERE contition;

****************************************/

SELECT query1.* FROM

( SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC

) query1,

( SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm

) query2

WHERE query1.total_odr = query2.total_odr;

-------------------------------

custm_id custm_nm total_odr

-------------------------------

100 Murugappan 2

102 Ramesh 2

-------------------------------

DROP TABLE customer_order_det_tb;


--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT

SELECT first_name, salary

FROM ( SELECT first_name, salary

FROM employees e

WHERE job_id NOT IN ('SALESMAN','PRESIDENT')

ORDER BY salary DESC

WHERE ROWNUM < 4;

New Oracle 12c Inline view Syntax

LATERAL clause for In-line views

Allows for columns in the inline view to be accessed!!

Example :

--in 11g

SELECT * FROM employees e, (

SELECT *

FROM departments d

WHERE e.department_id = d.department_id);


ORA-0090: "E"."DEPARTMENT_ID": Invalid Identifier

--in 12c

SELECT * FROM employees e, LATERAL(

SELECT *

FROM departments d

WHERE e.department_id = d.department_id

);

--in 11g

WITH t

AS

( SELECT LEVEL a

FROM dual

CONNECT BY LEVEL <= 30)

SELECT *

FROM t, (SELECT *

FROM employees

WHERE department_id = t.a

);

ORA-00904: "T"."A": invalid Identifier


--in 12c

WITH t

AS

(SELECT LEVEL a FROM dual CONNECT BY LEVEL <= 30)

SELECT * FROM t,

LATERAL(SELECT *

FROM employees

WHERE department_id = t.a);

Hope you have enjoyed this little article

Feed backs are always Welcome :) (:

Posted 20th July 2015 by Unknown

0 Add a comment

JAN

23

Salary Related Questions in Oracle

--creating table
CREATE TABLE employee_data

eid NUMBER(4),

ename VARCHAR2(30),

depno NUMBER(3),

salary NUMBER(8)

);

BEGIN

--Inserting records

INSERT INTO employee_data VALUES(1000,'Name01',90,30000);

INSERT INTO employee_data VALUES(1001,'Name02',90,6000);

INSERT INTO employee_data VALUES(1002,'Name03',90,23000);

INSERT INTO employee_data VALUES(1003,'Name04',60,35000);

INSERT INTO employee_data VALUES(1004,'Name05',60,60000);

INSERT INTO employee_data VALUES(1005,'Name06',60,30000);

INSERT INTO employee_data VALUES(1006,'Name07',80,36000);

INSERT INTO employee_data VALUES(1007,'Name08',80,29000);

INSERT INTO employee_data VALUES(1008,'Name09',80,37000);

INSERT INTO employee_data VALUES(1009,'Name10',80,41000);

COMMIT;

END;
/

SELECT * FROM employee_data

ORDER BY salary DESC;

--query to find maximum salary from employee_data table

SELECT MAX(salary) FROM employee_data;

--query to find minimum salary from employee_data table

SELECT MIN(salary) FROM employee_data;

--query to find second maximum salary from employee_data table

SELECT MAX(salary)

FROM employee_data

WHERE salary NOT IN (SELECT MAX(salary)

FROM employee_data);

--query to select 5th maximum salary

SELECT MIN(salary)

FROM (SELECT salary


FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= 5);

--query to select nth maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= &n);

--query to select all the details of the employee whose getting nth maximum salary

SELECT *

FROM (SELECT emp.*,

rownum rn

FROM (SELECT *

FROM employee_data

ORDER BY salary DESC) emp)

WHERE rn = 9;
--same query using row_numbr( ) function

SELECT *

FROM (SELECT emp.*,

row_number() over(ORDER BY salary) rank

FROM employee_data emp)

WHERE rank = 9;

--same query using rank( ) function

SELECT *

FROM (SELECT emp.*,

rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--same query using dense_rank( ) function

SELECT *

FROM (SELECT emp.*,

dense_rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;
--query to display display maximum salary in all the department

SELECT e.depno "Department id",

MAX(salary) "Maximum Salary"

FROM employee_data e

GROUP BY e.depno;

--query to display all the employees who are all getting salary more than average salary of the
company

SELECT e.* FROM employee_data e

WHERE salary > (SELECT AVG(salary) FROM employee_data);

--query to display all the employees who are all getting salary more than their department
average salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE department_id = OUT.department_id);


--query to display all the employees who are all getting salary more than their manager salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE employee_id = OUT.manager_id);

Documented By : Murugappan Annamalai

Posted on : 23-Jan-15 16:34:00 IST.

Hope you have enjoyed this little article

Feed backs are always welcome :)

Posted 23rd January 2015 by Unknown

7 View comments

JAN
22

Why prefer COALESCE over NVL

Documented By : Nimish Garg

I prefer using "COALESCE" over "NVL" is some of the scenarios. Last week One of my friend
asked me what is the advantage of using "COALESCE" where we can simply use "NVL". I simply
gave him the reply from Oracle Docs i.e. NVL lets you replace null (returned as a blank) with a
string in the results of a query and COALESCE returns the first non-null expr in the expression list.
Oracle Database uses short-circuit evaluation with "COALESCE".

He replied that he knows the difference, he knows that "COALESCE" can take multiple arguments
and so on. He was more interested in understanding "short-circuit evaluation" of "COALESCE"
and the scenarios where I prefer using "COALESCE" over "NVL".

To make him understand I created following function which takes One second in every execution
and simply returns '--null--' and executed 2 very similar queries one with NVL and other with
COALESCE.

SQL> create or replace function f_null return varchar2

2 is

3 begin

4 dbms_lock.sleep(1);

5 return '--null--';

6 end;

7 /

Function created.
Following are the queries which I used to demonstrate that NVL evaluates both arguments even
if the second argument is not used and COALESCE uses short-circuit evaluation i.e. it only
evaluates the arguments only if they are needed.

SQL> select e.empno, e.ename ename, nvl(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--


14 rows selected.

Elapsed: 00:00:14.01

SQL> select e.empno, e.ename ename, coalesce(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--


14 rows selected.

Elapsed: 00:00:01.01

Here we can see easily that the first query with NVL took 14+ seconds, one second for each
record even if the "f_null" value was used only in one record. On the contrary as mentioned in
Oracle Documentation "COALESCE" uses its "short-circuit evaluation" and "f_null" was called
only once and so second query took only One Second. "COALESCE" is certainly use less resources
than NVL.

Posted 22nd January 2015 by Unknown

0 Add a comment

DEC

21

Constraints

It Enforce Rule On Table

We can create constraint at the time of Creating Table


1. Column Level Declaration

2. Table Level Declaration

1. We can provide own name.

Format : [part_of_project_name-table_name-column_name-constraint_type]

Example : gmind_emp_id_pk _uk _ck _f

2. system name name

Format : sys_cn

Example : SYS_C405323

We can create constraint after the table has been created

Types

Primary Key

Not allowed Null value

Not allowed you to enter duplicate value

Ex : Employee_id, Student_id
Unique Key

allowed Null value

Not allowed you to enter duplicate value

Ex : Contact_no, email

Foreign Key

It will allowed you to enter NULL and Duplicate value.

c1(pk) : 1 2 3

c2(f) : 1 1 2 3 4 Not allowed

Allowed you to enter duplicate value and null value

Not Null

It will not allowed you to enter null value

Check

You can check your own condition


Simple Table for understanding

------------------------------------

Duplicate NULL

------------------------------------

Primary Key X X

Unique Key X Allowed

Foreign Key Allowed Allowed

------------------------------------

creating table with all constraint type

Create table my_stu_details

S_id Number(2),

S_name Varchar2(30) Not Null, --SYS_Cn

s_mail Varchar2(30),

s_gender char(1),

s_did Number(3),

Constraint my_stu_sid_pk PRIMARY KEY (s_id),

constraint my_stu_mail_uk UNIQUE (s_mail) ,

Constraint my_stu_gen_ck CHECK (s_gender IN ('M', 'F', 'm', 'f')),


Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

);

DESC my_stu_details;

------------------------------------

Name Type Nullable

------------------------------------

S_ID NUMBER(2)

S_NAME VARCHAR2(30)

S_MAIL VARCHAR2(30) Y

S_GENDER CHAR(1) Y

S_DID NUMBER(3) Y

------------------------------------

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name1' , 'name1@gmail.com' , 'm' , 60 );

Select * from my_stu_details;


Validating Primary Key

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-00001: unique constraint (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (NULL, 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-01400: cannot insert NULL into (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (2 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

Validating NOT NULL Constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)


values (3 , NULL , 'name3@gmail.com' , 'F' , 80 );

ORA-01400: cannot insert NULL into ("HR"."MY_STU_DETAILS"."S_NAME")

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , 'Name3' , 'name3@gmail.com' , 'F' , 80 );

Select * from my_stu_details;

Validating Unique Key Constraint

--Duplicate Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , 'name3@gmail.com' , 'F' , 80 );

ORA-00001: unique constraint (HR.MY_STU_MAIL_UK) violated

--Null Check
Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , null , 'M' , 70 );

Select * from my_stu_details;

Validating Check constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'j' , 70 );

ORA-02290: check constraint (HR.MY_STU_GEN_CK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'M' , 70 );

Select * from my_stu_details;

Validating Foreign Key


Select * from Departments;

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 3 );

ORA-02291: integrity constraint (HR.MY_STU_DID_FK) violated - parent key not found

Departments table : parent table

my_stu_details : Child table

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

--------------------------------------------------------

s_id s_name s_mail s_gender s_did

--------------------------------------------------------

1 name1 name1@gmail.com m 60

2 name2 name2@gmail.com F 90
3 Name3 name3@gmail.com F 80

4 Name4 M 70

5 Name5 name5@gmail.com M 70

6 Name6 name6@gmail.com F 90

--------------------------------------------------------

Deleting the Primary key value which is referred by Foreign Key

Select * from Departments;

DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID

------------------------------------------------------------

60 IT 103 1400 <---- Delete

-- don't execute this query

--Delete From Departments

--Where Department_id = 60;

1) ON DELETE SET NULL


-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

1 name1 name1@gmail.com m -

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

2) ON DELETE SET CASCADE

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

Syntax
Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE CASCADE

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE SET NULL

Constraint Related Data Dictionary Table information.

To view constraint Information

SELECT c.owner,

c.constraint_name,

c.constraint_type,

c.table_name,

c.r_constraint_name,

c.status

FROM user_constraints c

WHERE c.table_name = 'MY_STU_DETAILS';

------------------------------------------------------------------------------------

owner constraint_name constraint_type table_name r_constraint_name status

------------------------------------------------------------------------------------
HR SYS_C004023 C MY_STU_DETAILS ENABLED

HR MY_STU_GEN_CK C MY_STU_DETAILS ENABLED

HR MY_STU_SID_PK P MY_STU_DETAILS ENABLED

HR MY_STU_MAIL_UK U MY_STU_DETAILS ENABLED

HR MY_STU_DID_FK R MY_STU_DETAILS DEPT_ID_PK ENABLED

------------------------------------------------------------------------------------

To view constraint name with corresponding column name

SELECT * FROM user_cons_columns c

WHERE c.table_name = 'MY_STU_DETAILS';

-------------------------------------------------------------

owner constraint_name table_name column_name position

-------------------------------------------------------------

HR MY_STU_MAIL_UK MY_STU_DETAILS S_MAIL 1

HR MY_STU_SID_PK MY_STU_DETAILS S_ID 1

HR MY_STU_GEN_CK MY_STU_DETAILS S_GENDER

HR SYS_C004023 MY_STU_DETAILS S_NAME

HR MY_STU_DID_FK MY_STU_DETAILS S_DID 1

-------------------------------------------------------------
Creating Composite Primary Key

Creating Primary Key with more than one number of column

ALTER TABLE table_name

ADD CONSTRAINT constraint_name PRIMARY KEY(column1, column_2 , column3);

In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.

creating constraint after the table creation

ALTER TABLE table_name

ADD CONSTRAINT constraint_name CONSTRAINT_TYPE(column_name);

ALTER TABLE table_name

DROP CONSTRAINT constraint_name;

ALTER TABLE table_name

DROP PRIMARY KEY;

To drop related foreign key


ALTER TABLE table_name

DROP PRIMARY KEY CASCADE;

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name;

Disable constraint with related foreign key constraint

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name CASCADE;

ALTER TABLE table_name

ENABLE CONSTRAINT constraint_name;

Interview Questions

What are all the type of constraint available in oracle?

Difference between PRIMARY KEY and UNIQUE key.


Difference between PRIMARY KEY ans FOREIGN KEY.

Difference between UNIQUE key and FOREIGN KEY.

Is it possible to create tow primary key in single table.

Write a syntax to create FOREIGN constraint.

How to create constraint after the table has been created?

How to enable and disable a constraint.

Which data dictionary table contains information about constraints?

Which Data Dictionary table contains information about constraint with corresponding column
name?

What is composite primary key?

Explain ON DELETE CASCADE and ON DELETE SET NULL option.

~Thanks For Reading~

Post your valuable feedback below

Posted 21st December 2014 by Unknown

1 View comments

UnknownMay 22, 2017 at 12:39 AM

good
Reply

DEC

listagg in Oracle 11g

Oracle 11gR2 listagg built-in function allows for many table columns to be displayed within a
single row, a non-first-normal form display

Syntax :

listagg(column_value,'delimiter') WITHIN GROUP(ORDER BY column_name)

--Example 1:

CREATE TABLE test_ins(empid NUMBER,product VARCHAR2(30));

BEGIN

INSERT INTO test_ins VALUES( 101,'pendrive');

INSERT INTO test_ins VALUES( 102,'toy');

INSERT INTO test_ins VALUES( 101,'ipod');

INSERT INTO test_ins VALUES( 102,'hat');

INSERT INTO test_ins VALUES( 103,'cpu');

INSERT INTO test_ins VALUES( 104,'pen');

INSERT INTO test_ins VALUES( 104,'car');


INSERT INTO test_ins VALUES( 104,'mat');

INSERT INTO test_ins VALUES( 105,'tv');

INSERT INTO test_ins VALUES( 106,'laptop');

commit;

END;

SELECT * FROM test_ins;

SELECT empid "Employee",

listagg(product,

',') within

GROUP (ORDER BY empid) "Products"

FROM test_ins

GROUP BY empid;

-->-- Result set --<--


DROP TABLE test_ins;

-->-- Example 2

select department_id "Department id", listagg(first_name,', ') WITHIN GROUP(ORDER BY


employee_id) "Employees"

FROM employees

WHERE department_id IN (10,20,30,60)

GROUP BY department_id;

-->-- Result set --<--

Posted 4th December 2014 by Unknown

0 Add a comment

NOV

8
Condition and Looping Statement

IF

IF ELSE

Multiple IF ELSE

LOOP

FOR LOOP

WHILE LOOP

create table test_udt(id NUMBER, salary NUMBER);

BEGIN

INSERT INTO test_udt VALUES(001,23000);

INSERT INTO test_udt VALUES(002,43000);

INSERT INTO test_udt VALUES(003,78000);

INSERT INTO test_udt VALUES(004,25000);

INSERT INTO test_udt VALUES(005,26000);

INSERT INTO test_udt VALUES(006,90000);

Commit;

END;
select * from test_udt;

IF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 1;

IF v_salary > 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

END IF;

commit;

END;

/
IF ELSE

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

ELSE

UPDATE test_udt t

SET t.salary = v_salary+20007

WHERE t.id = v_id ;

END IF;

commit;

END;

/
--same example with less number of lines

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

v_salary := v_salary+10005;

ELSE

v_salary := v_salary+20007;

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

/
select * from test_udt;

Multiple IF ELSIF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 3;

IF v_id = 1 THEN

v_salary := 1000;

dbms_output.put_line('1 inside');

ELSIF v_id = 2 THEN

v_salary := 2000;

dbms_output.put_line('2 inside');

ELSIF v_id = 3 THEN

v_salary := 3000;

dbms_output.put_line('3 inside');

ELSIF v_id = 4 THEN

v_salary := 4000;

dbms_output.put_line('4 inside');
END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

LOOP

--syntax

LOOP

--statements

--increment

--exit statement

END LOOP;

CREATE TABLE prod_details (pid VARCHAR2(3), pname VARCHAR2(30));


DECLARE

i NUMBER := 1;

x VARCHAR2(3);

BEGIN

LOOP

x := lpad(i,3,'0');

dbms_output.put_line('x value : '|| x);

INSERT INTO prod_details VALUES(i, 'Product '||i);

EXIT WHEN i >900;

i := i+1;

IF MOD(i,100) = 0 THEN

commit;

dbms_output.put_line('commit executed');

END IF;

END LOOP;

END;

SELECT * FROM prod_details ORDER BY 1;

DROP TABLE prod_details;

FOR LOOP
BEGIN

FOR I in 1..5

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

FOR LOOP - Reverse

BEGIN

FOR I in REVERSE 14..50

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

WHILE LOOP

DECLARE

i_val NUMBER:=0;

BEGIN

WHILE (i_val < 11)

LOOP
dbms_output.put_line('The value of I is '||i_val);

i_val := i_val + 1;

END LOOP;

END;

sample output:

The value of I is 0

The value of I is 1

The value of I is 2

The value of I is 3

The value of I is 4

The value of I is 5

The value of I is 6

The value of I is 7

The value of I is 8

The value of I is 9

The value of I is 10

Posted 8th November 2014 by Unknown

0 Add a comment
OCT

21

Bulk Collect

This is used for array fetches

With this you can retrieve multiple rows of data with a single round trip.

This reduces the number of context switches between the pl/sql and sql engines.

You can use bulk collect in both dynamic and static sql.

You can use bulk collect in select, fetch into and returning into clauses.

SQL engine automatically initializes and extends the collections you reference in the bulk
collect clause.

You can fetch into multiple collections with one column each.

You can use the limit clause of bulk collect to restrict the no of rows retrieved.

SELECT * FROM product_details;

-->-- Bulk collect in FETCH INTO --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS
SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Bulk collect in SELECT clause --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

BEGIN

SELECT * BULK COLLECT INTO dta FROM product_details;

FOR i IN dta.FIRST .. dta.LAST LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;
-->-- LIMIT in Bulk collect --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta LIMIT 30;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Multiple fetches in INTO clause --<--


SELECT * FROM product_details;

DECLARE

TYPE alldata_typ1 IS TABLE OF product_details.p_id%TYPE;

TYPE alldata_typ2 IS TABLE OF product_details.p_name%TYPE;

dta1 alldata_typ1;

dta2 alldata_typ2;

CURSOR proddt_cur IS

SELECT p_id, p_name FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta1, dta2;

CLOSE proddt_cur;

FOR i IN dta1.FIRST .. dta1.COUNT LOOP

dbms_output.put_line('Department Id : ' || dta1(i));

END LOOP;

FOR i IN dta2.FIRST .. dta2.COUNT LOOP

dbms_output.put_line('Department Name : ' || dta2(i));

END LOOP;

END;
/

DROP TABLE dep_details;

DROP TABLE product_details;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Ref Cursor

This is unconstrained cursor which will return different types depends upon the user input.

Ref cursors cannot be closed implicitly.

Ref cursor with return type is called strong cursor.

Ref cursor without return type is called weak cursor.

You can declare ref cursor type in package spec as well as body.

You can declare ref cursor types in local subprograms or anonymous blocks.

CREATE OR REPLACE PROCEDURE ref_c_sp(dep_det_c IN OUT SYS_REFCURSOR)

AS

BEGIN
OPEN dep_det_c

FOR

SELECT * FROM dep_details d;

END;

DECLARE

dep_det_c SYS_REFCURSOR;

tab_data dep_details%ROWTYPE;

BEGIN

ref_c_sp(dep_det_c);

LOOP

FETCH dep_det_c INTO tab_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department Name : '|| tab_data.d_name);

END LOOP;

CLOSE dep_det_c;

END;

/*sample output*/

Department Name : Admin


Department Name : HR

Department Name : Sales

Department Name : Marketing

DROP PROCEDURE ref_c_sp;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Cursor

SQL Private work Area where the query get passed and executed.

Types

******

Implicit(SQL)

Explicit

-->-- advanced cursor types --<--

Parametrized Cursor

Ref Cursor
Implicit

********

ORACLE implicitly opens a cursor to process each SQL statement not associated with an
explicitly declared cursor.

PL/SQL lets you refer to the most recent implicit cursor as the SQL” cursor. So, although you
cannot use the OPEN,

FETCH, and CLOSE statements to control an implicit cursor, you can still use cursor attributes to
access information

about the most recently executed SQL statement.

Cursor Stages

**************

OPEN cursor_name

FETCH (with in loop)

CLOSE cursor_name

Explicit

The set of rows returned by a query can consist of zero, one, or multiple rows,

depending on how many rows meet your search criteria. When a query returns multiple rows,

you can explicitly define a cursor to process the rows. You use three commands to control the
cursor
Cursor Attributes

*****************

%FOUND

%NOTFOUND

%ISOPEN

%ROWCOUNT

%BULK_ROWCOUNT --<-- used to handle error while using bulk collection.

%BULK_EXCEPTIONS --<-- used to handle error while using bulk collection.

Cursor Declaration

DECLARE

CURSOR <cursor_name>

IS

<SELECT statement>

BEGIN

--> some stmt

END;

Cursor Loop

Loop

While Loop

For Loop
Cursor Clauses

Return

For update

Where current of

Bulk collect

-->-- creating table

create table product_details

p_id NUMBER,

p_name VARCHAR2(30),

p_order_dt DATE

);

-->-- Inserting data

BEGIN

FOR i IN 1 .. 75 LOOP

INSERT INTO product_details VALUES (i, 'prod_name_' || i, SYSDATE + i);

END LOOP;

commit;

END;
-->-- selecting data

SELECT * FROM product_details;

---------------------------------------------

p_id p_name p_order_dt

---------------------------------------------

1 prod_name_1 10/11/2014 3:48:32 PM

2 prod_name_2 10/12/2014 3:48:32 PM

3 prod_name_3 10/13/2014 3:48:32 PM

4 prod_name_4 10/14/2014 3:48:32 PM

5 prod_name_5 10/15/2014 3:48:32 PM

6 prod_name_6 10/16/2014 3:48:32 PM

7 prod_name_7 10/17/2014 3:48:32 PM

8 prod_name_8 10/18/2014 3:48:32 PM

9 prod_name_9 10/19/2014 3:48:32 PM

10 prod_name_10 10/20/2014 3:48:32 PM

11 prod_name_11 10/21/2014 3:48:32 PM

12 prod_name_12 10/22/2014 3:48:32 PM

13 prod_name_13 10/23/2014 3:48:32 PM

14 prod_name_14 10/24/2014 3:48:32 PM

15 prod_name_15 10/25/2014 3:48:32 PM

16 prod_name_16 10/26/2014 3:48:32 PM


17 prod_name_17 10/27/2014 3:48:32 PM

18 prod_name_18 10/28/2014 3:48:32 PM

19 prod_name_19 10/29/2014 3:48:32 PM

20 prod_name_20 10/30/2014 3:48:32 PM

---------------------------------------------

----------------------------------------------

Implicit Cursor

----------------------------------------------

--will update soon

----------------------------------------------

Explicit Cursor

----------------------------------------------

**********************************************

Processing cursor data by using LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS
SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND; --<-- if next record not found means control will
come out from the loop

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )


DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

EXIT WHEN prod_detail_cur%FOUND; --<-- if next record found means control will come
out from the loop

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )


DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;
END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor Already closed

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP
FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

-->-- CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )


Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor closed

**********************************************

Processing cursor data by using WHILE LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

OPEN prod_detail_cur;

FETCH prod_detail_cur

INTO all_data;

WHILE prod_detail_cur%FOUND LOOP

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');


FETCH prod_detail_cur

INTO all_data;

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

************************************************************

Processing cursor data by using FOR LOOP - CURSOR FOR LOOP

************************************************************

DECLARE

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

FOR i IN prod_detail_cur
LOOP

dbms_output.put_line('Product id : ' || i.p_id ||

' Product Name : ' || i.p_name ||

' ( Orderd on : ' || TRIM(i.p_order_dt) || ' )');

END LOOP;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

Parameterized Cursor

*********************

This was used when you are going to use the cursor in more than one place with different
values for the same where clause.

Cursor parameters must be in mode.

Cursor parameters may have default values.

The scope of cursor parameter is within the select statement.


CREATE TABLE dep_details(d_id NUMBER,d_name VARCHAR2(30), location_id NUMBER);

BEGIN

INSRT INTO dep_details VALUES(001,'Admin',1010);

INSRT INTO dep_details VALUES(002,'HR',1010);

INSRT INTO dep_details VALUES(003,'Sales',1020);

INSRT INTO dep_details VALUES(004,'Marketing',1020);

commit;

END;

SELECT * FROM dep_details;

----------------------------

d_id d_name location_id

----------------------------

1 Admin 1010

2 HR 1010

3 Sales 1020

4 Marketing 1020

----------------------------
DECLARE

-->--Declaring parameterized cursor

CURSOR dep_det_c(p_location_id NUMBER) IS

SELECT * FROM dep_details d WHERE d.location_id = p_location_id;

all_data dep_details%ROWTYPE;

BEGIN

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

OPEN dep_det_c(1010);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

-->-- opening same cursor with different input value

OPEN dep_det_c(1020);

LOOP

FETCH dep_det_c

INTO all_data;
EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

END;

/*sample output*/

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 1 Department Name : Admin

Department id : 2 Department Name : HR

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 3 Department Name : Sales

Department id : 4 Department Name : Marketing

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Posted 21st October 2014 by Unknown

0 Add a comment

OCT
21

Handling Exception

Error Handling in oracle

ERROR

Any departure from the expected behavior of the system or program,

which stops the working of the system is an error.

Types : compile time error

Run time error

EXCEPTION

Any error or problem which one can handle and continue to work normally.

Handling Exception

When exception is raised, control passes to the exception section of the block.

i.e. EXCEPTION

WHEN name_of_exception THEN

Types : Pre Defined Exceptions

User Defined Exceptions


Predefined Exception

*********************

Oracle has predefined several exceptions that correspond to the most common oracle errors.

------------------------------------------------------------------------

Exception Oracle Error SQL Code Value

------------------------------------------------------------------------

ZERO_DIVIDE ORA-01476 -1476

NO_DATA_FOUND ORA-01403 +100

DUP_VAL_ON_INDEX ORA-00001 -1

TOO_MANY_ROWS ORA-01422 -1422

VALUE_ERROR ORA-06502 -6502

CURSOR_ALREADY_OPEN ORA-06511 -6511

OTHERS

------------------------------------------------------------------------

-->-- ZERO_DIVIDE --<--

Your program attempts to divide a number by zero.

DECLARE

v_result NUMBER;

BEGIN
SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN ZERO_DIVIDE THEN

dbms_output.put_line('Divisor is equal to zero');

END;

-->-- NO_DATA_FOUND --<--

Single row SELECT returned no rows or your program referenced a deleted element in a nested
table

or an uninitialized element in an associative array (index-by table).

CREATE TABLE test_tb(id NUMBER PRIMARY KEY);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN NO_DATA_FOUND THEN

dbms_output.put_line('There is no data inside the table');

END;
-->-- DUP_VAL_ON_INDEX --<--

A program attempted to insert duplicate values in a column that is constrained by a unique


index.

INSERT INTO test_tb VALUES (1);

INSERT INTO test_tb VALUES (2);

commit;

BEGIN

INSERT INTO test_tb VALUES (2);

EXCEPTION

WHEN DUP_VAL_ON_INDEX THEN

dbms_output.put_line('Duplicate values are not allowed');

END;

-->-- TOO_MANY_ROWS --<--

Single row SELECT returned multiple rows.

DECLARE

v_id NUMBER;

BEGIN
SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN TOO_MANY_ROWS THEN

dbms_output.put_line('Query returning more than one row');

END;

DROP TABLE test_tb;

-->-- VALUE_ERROR --<--

An arithmetic, conversion, truncation, or size constraint error occurred.

DECLARE

num1 NUMBER(2);

BEGIN

num1 := 345;

EXCEPTION

WHEN VALUE_ERROR THEN

dbms_output.put_line('check the size of the variable');

END;

-->-- CURSOR_ALREADY_OPEN --<--


A program attempted to open an already opened cursor.

CREATE TABLE emp(id NUMBER, name VARCHAR2(30));

BEGIN

INSERT INTO emp VALUES(1,'Name1');

INSERT INTO emp VALUES(2,'Name2');

INSERT INTO emp VALUES(3,'Name3');

INSERT INTO emp VALUES(4,'Name4');

COMMIT;

END;

SELECT * FROM emp;

DECLARE

cursor emp_c IS

SELECT * FROM emp;

all_data emp%ROWTYPE;

BEGIN

OPEN emp_c;

OPEN emp_c;

NULL;

CLOSE emp_c;
EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

END;

DROP TABLE emp;

-->-- OTHERS --<--

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

WHEN OTHERS THEN

dbms_output.put_line('Some other error ' || SQLERRM);

END;

User Defined Exception

**********************
A user-defined exception is an error that is defined by the programmer.

User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,

exceptions have a type EXCEPTION and scope.

DECLARE

v_gender CHAR := '&gender';

gender_ex EXCEPTION;

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE gender_ex;

END IF;

dbms_output.put_line('Gender : '||v_gender);

EXCEPTION

WHEN gender_ex THEN

dbms_output.put_line('Please Enter valid gender');

END;

create table test_insert (id NUMBER, Name VARCHAR2(30));

DECLARE

abort_ex EXCEPTION;

BEGIN
FOR i IN 1..100

LOOP

BEGIN

IF mod(i,10)=0 THEN

RAISE abort_ex;

END IF;

INSERT INTO test_insert VALUES(i, 'Name'||i);

EXCEPTION

WHEN abort_ex THEN

NULL;

END;

END LOOP;

COMMIT;

END;

SELECT * FROM test_insert;

DROP TABLE test_insert;

SQLERRM and SQLCODE

********************

SQLCODE returns the current error code, and SQLERRM returns the current error message
text;

For user-defined exception SQLCODE returns 1 and SQLERRM returns “user-defined


exception”.

SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.

CREATE TABLE test_tb (id NUMBER);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

dbms_output.put_line(v_id);

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('SQLERRM : ' || SQLERRM);

dbms_output.put_line('SQLCODE : ' || SQLCODE);

END;

/*sample output*/

SQLERRM : ORA-01403: no data found

SQLCODE : 100

DROP TABLE test_tb;


PRAGMA EXCEPTION_INIT

*********************

Using this you can associate a named exception with a particular oracle error.

This gives you the ability to trap this error specifically, rather than via an OTHERS handler.

Syntax:

PRAGMA EXCEPTION_INIT(exception_name, oracle_error_number);

DECLARE

v_result NUMBER;

PRAGMA EXCEPTION_INIT(Invalid, -1476);

BEGIN

SELECT 453 / 0 INTO v_result FROM dual;

dbms_output.put_line('Result : ' || v_result);

EXCEPTION

WHEN INVALID THEN

dbms_output.put_line('Invalid Exception');

END;

RAISE_APPLICATION_ERROR

************************
You can use this built-in function to create your own error messages, which can be more
descriptive than named exceptions.

Error Number :

Oracle Error Range : From -00000 to -19999

User Error Range : From -20000 to -20999

DECLARE

v_gender CHAR := '&gender';

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE_APPLICATION_ERROR(-20003, 'Enter valid gender');

END IF;

dbms_output.put_line('Gender : ' || v_gender);

END;

Posted 21st October 2014 by Unknown

1 View comments
Loading

Dynamic Views theme. Powered by Blogger.

Oracle sql & Pl/sql

search

Home Sql and pl/sql Sql Interview Questions

JUL

20

INLINE view in Oracle with 12c New Features

Named sub Query in FROM clause is call it as INLINE VIEW.

Oracle process a inline view faster than sub query

Inline View in Oracle

--Query to display all the employees who are all getting salary more than their department
average salary

SELECT First_name

, last_name

, salary

, department_id

FROM employees a , ( SELECT b.department_id

, AVG(b.salary) avg_sal
FROM employees b

GROUP BY b.department_id

)b

WHERE a.department_id = b.department_id

AND a.salary > b.avg_salary;

Display all the customer who have placed more number of orders by using INLINE view

CREATE TABLE customer_order_det_tb

( custm_id NUMBER ,

custm_nm VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

ttl_amt NUMBER(7,2)

);

BEGIN

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '11-Jul-15' , 45000.00);

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '14-Jul-15' , 27000.00);

INSERT INTO customer_order_det_tb VALUES(101, 'Raja' , '13-Jul-15' , 17000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 34000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 38000.00);

COMMIT;

END;
SELECT c.*

FROM customer_order_det_tb c;

--------------------------------------------

custm_id custm_nm order_dt ttl_amt

--------------------------------------------

100 Murugappan 7/11/2015 45000.00

100 Murugappan 7/14/2015 27000.00

101 Raja 7/13/2015 17000.00

102 Ramesh 7/15/2015 34000.00

102 Ramesh 7/15/2015 38000.00

--------------------------------------------

--Writing a Quer to display all the customer who have placed maximum number of order

--Query #1 for inline view

SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC;

--------------------------------

custm_id custm_nm total_odr


--------------------------------

100 Murugappan 2

102 Ramesh 2

101 Raja 1

--------------------------------

--Query #2 for inline view

SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm;

----------

total_odr

----------

----------

Inline view to find all the customers who have placed maximum number of orders

/****************************************

Syntax

SELECT * FROM <query1> x, <query2> y

WHERE contition;
****************************************/

SELECT query1.* FROM

( SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC

) query1,

( SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm

) query2

WHERE query1.total_odr = query2.total_odr;

-------------------------------

custm_id custm_nm total_odr

-------------------------------

100 Murugappan 2

102 Ramesh 2

-------------------------------

DROP TABLE customer_order_det_tb;

--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT
SELECT first_name, salary

FROM ( SELECT first_name, salary

FROM employees e

WHERE job_id NOT IN ('SALESMAN','PRESIDENT')

ORDER BY salary DESC

WHERE ROWNUM < 4;

New Oracle 12c Inline view Syntax

LATERAL clause for In-line views

Allows for columns in the inline view to be accessed!!

Example :

--in 11g

SELECT * FROM employees e, (

SELECT *

FROM departments d

WHERE e.department_id = d.department_id);

ORA-0090: "E"."DEPARTMENT_ID": Invalid Identifier


--in 12c

SELECT * FROM employees e, LATERAL(

SELECT *

FROM departments d

WHERE e.department_id = d.department_id

);

--in 11g

WITH t

AS

( SELECT LEVEL a

FROM dual

CONNECT BY LEVEL <= 30)

SELECT *

FROM t, (SELECT *

FROM employees

WHERE department_id = t.a

);

ORA-00904: "T"."A": invalid Identifier

--in 12c
WITH t

AS

(SELECT LEVEL a FROM dual CONNECT BY LEVEL <= 30)

SELECT * FROM t,

LATERAL(SELECT *

FROM employees

WHERE department_id = t.a);

Hope you have enjoyed this little article

Feed backs are always Welcome :) (:

Posted 20th July 2015 by Unknown

0 Add a comment

JAN

23

Salary Related Questions in Oracle

--creating table

CREATE TABLE employee_data


(

eid NUMBER(4),

ename VARCHAR2(30),

depno NUMBER(3),

salary NUMBER(8)

);

BEGIN

--Inserting records

INSERT INTO employee_data VALUES(1000,'Name01',90,30000);

INSERT INTO employee_data VALUES(1001,'Name02',90,6000);

INSERT INTO employee_data VALUES(1002,'Name03',90,23000);

INSERT INTO employee_data VALUES(1003,'Name04',60,35000);

INSERT INTO employee_data VALUES(1004,'Name05',60,60000);

INSERT INTO employee_data VALUES(1005,'Name06',60,30000);

INSERT INTO employee_data VALUES(1006,'Name07',80,36000);

INSERT INTO employee_data VALUES(1007,'Name08',80,29000);

INSERT INTO employee_data VALUES(1008,'Name09',80,37000);

INSERT INTO employee_data VALUES(1009,'Name10',80,41000);

COMMIT;

END;

/
SELECT * FROM employee_data

ORDER BY salary DESC;

--query to find maximum salary from employee_data table

SELECT MAX(salary) FROM employee_data;

--query to find minimum salary from employee_data table

SELECT MIN(salary) FROM employee_data;

--query to find second maximum salary from employee_data table

SELECT MAX(salary)

FROM employee_data

WHERE salary NOT IN (SELECT MAX(salary)

FROM employee_data);

--query to select 5th maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data
ORDER BY salary DESC)

WHERE rownum <= 5);

--query to select nth maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= &n);

--query to select all the details of the employee whose getting nth maximum salary

SELECT *

FROM (SELECT emp.*,

rownum rn

FROM (SELECT *

FROM employee_data

ORDER BY salary DESC) emp)

WHERE rn = 9;

--same query using row_numbr( ) function


SELECT *

FROM (SELECT emp.*,

row_number() over(ORDER BY salary) rank

FROM employee_data emp)

WHERE rank = 9;

--same query using rank( ) function

SELECT *

FROM (SELECT emp.*,

rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--same query using dense_rank( ) function

SELECT *

FROM (SELECT emp.*,

dense_rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--query to display display maximum salary in all the department


SELECT e.depno "Department id",

MAX(salary) "Maximum Salary"

FROM employee_data e

GROUP BY e.depno;

--query to display all the employees who are all getting salary more than average salary of the
company

SELECT e.* FROM employee_data e

WHERE salary > (SELECT AVG(salary) FROM employee_data);

--query to display all the employees who are all getting salary more than their department
average salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE department_id = OUT.department_id);

--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE employee_id = OUT.manager_id);

Documented By : Murugappan Annamalai

Posted on : 23-Jan-15 16:34:00 IST.

Hope you have enjoyed this little article

Feed backs are always welcome :)

Posted 23rd January 2015 by Unknown

7 View comments

JAN

22

Why prefer COALESCE over NVL


Documented By : Nimish Garg

I prefer using "COALESCE" over "NVL" is some of the scenarios. Last week One of my friend
asked me what is the advantage of using "COALESCE" where we can simply use "NVL". I simply
gave him the reply from Oracle Docs i.e. NVL lets you replace null (returned as a blank) with a
string in the results of a query and COALESCE returns the first non-null expr in the expression list.
Oracle Database uses short-circuit evaluation with "COALESCE".

He replied that he knows the difference, he knows that "COALESCE" can take multiple arguments
and so on. He was more interested in understanding "short-circuit evaluation" of "COALESCE"
and the scenarios where I prefer using "COALESCE" over "NVL".

To make him understand I created following function which takes One second in every execution
and simply returns '--null--' and executed 2 very similar queries one with NVL and other with
COALESCE.

SQL> create or replace function f_null return varchar2

2 is

3 begin

4 dbms_lock.sleep(1);

5 return '--null--';

6 end;

7 /

Function created.

Following are the queries which I used to demonstrate that NVL evaluates both arguments even
if the second argument is not used and COALESCE uses short-circuit evaluation i.e. it only
evaluates the arguments only if they are needed.

SQL> select e.empno, e.ename ename, nvl(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.
Elapsed: 00:00:14.01

SQL> select e.empno, e.ename ename, coalesce(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.
Elapsed: 00:00:01.01

Here we can see easily that the first query with NVL took 14+ seconds, one second for each
record even if the "f_null" value was used only in one record. On the contrary as mentioned in
Oracle Documentation "COALESCE" uses its "short-circuit evaluation" and "f_null" was called
only once and so second query took only One Second. "COALESCE" is certainly use less resources
than NVL.

Posted 22nd January 2015 by Unknown

0 Add a comment

DEC

21

Constraints

It Enforce Rule On Table

We can create constraint at the time of Creating Table

1. Column Level Declaration

2. Table Level Declaration


1. We can provide own name.

Format : [part_of_project_name-table_name-column_name-constraint_type]

Example : gmind_emp_id_pk _uk _ck _f

2. system name name

Format : sys_cn

Example : SYS_C405323

We can create constraint after the table has been created

Types

Primary Key

Not allowed Null value

Not allowed you to enter duplicate value

Ex : Employee_id, Student_id

Unique Key
allowed Null value

Not allowed you to enter duplicate value

Ex : Contact_no, email

Foreign Key

It will allowed you to enter NULL and Duplicate value.

c1(pk) : 1 2 3

c2(f) : 1 1 2 3 4 Not allowed

Allowed you to enter duplicate value and null value

Not Null

It will not allowed you to enter null value

Check

You can check your own condition

Simple Table for understanding


------------------------------------

Duplicate NULL

------------------------------------

Primary Key X X

Unique Key X Allowed

Foreign Key Allowed Allowed

------------------------------------

creating table with all constraint type

Create table my_stu_details

S_id Number(2),

S_name Varchar2(30) Not Null, --SYS_Cn

s_mail Varchar2(30),

s_gender char(1),

s_did Number(3),

Constraint my_stu_sid_pk PRIMARY KEY (s_id),

constraint my_stu_mail_uk UNIQUE (s_mail) ,

Constraint my_stu_gen_ck CHECK (s_gender IN ('M', 'F', 'm', 'f')),

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

);
DESC my_stu_details;

------------------------------------

Name Type Nullable

------------------------------------

S_ID NUMBER(2)

S_NAME VARCHAR2(30)

S_MAIL VARCHAR2(30) Y

S_GENDER CHAR(1) Y

S_DID NUMBER(3) Y

------------------------------------

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name1' , 'name1@gmail.com' , 'm' , 60 );

Select * from my_stu_details;

Validating Primary Key


Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-00001: unique constraint (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (NULL, 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-01400: cannot insert NULL into (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (2 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

Validating NOT NULL Constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , NULL , 'name3@gmail.com' , 'F' , 80 );


ORA-01400: cannot insert NULL into ("HR"."MY_STU_DETAILS"."S_NAME")

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , 'Name3' , 'name3@gmail.com' , 'F' , 80 );

Select * from my_stu_details;

Validating Unique Key Constraint

--Duplicate Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , 'name3@gmail.com' , 'F' , 80 );

ORA-00001: unique constraint (HR.MY_STU_MAIL_UK) violated

--Null Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , null , 'M' , 70 );


Select * from my_stu_details;

Validating Check constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'j' , 70 );

ORA-02290: check constraint (HR.MY_STU_GEN_CK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'M' , 70 );

Select * from my_stu_details;

Validating Foreign Key

Select * from Departments;


Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 3 );

ORA-02291: integrity constraint (HR.MY_STU_DID_FK) violated - parent key not found

Departments table : parent table

my_stu_details : Child table

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

--------------------------------------------------------

s_id s_name s_mail s_gender s_did

--------------------------------------------------------

1 name1 name1@gmail.com m 60

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 M 70
5 Name5 name5@gmail.com M 70

6 Name6 name6@gmail.com F 90

--------------------------------------------------------

Deleting the Primary key value which is referred by Foreign Key

Select * from Departments;

DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID

------------------------------------------------------------

60 IT 103 1400 <---- Delete

-- don't execute this query

--Delete From Departments

--Where Department_id = 60;

1) ON DELETE SET NULL

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID


-------------------------------------------------

6 Name6 name6@gmail.com F 90

1 name1 name1@gmail.com m -

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

2) ON DELETE SET CASCADE

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

Syntax

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE CASCADE
Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE SET NULL

Constraint Related Data Dictionary Table information.

To view constraint Information

SELECT c.owner,

c.constraint_name,

c.constraint_type,

c.table_name,

c.r_constraint_name,

c.status

FROM user_constraints c

WHERE c.table_name = 'MY_STU_DETAILS';

------------------------------------------------------------------------------------

owner constraint_name constraint_type table_name r_constraint_name status

------------------------------------------------------------------------------------

HR SYS_C004023 C MY_STU_DETAILS ENABLED

HR MY_STU_GEN_CK C MY_STU_DETAILS ENABLED


HR MY_STU_SID_PK P MY_STU_DETAILS ENABLED

HR MY_STU_MAIL_UK U MY_STU_DETAILS ENABLED

HR MY_STU_DID_FK R MY_STU_DETAILS DEPT_ID_PK ENABLED

------------------------------------------------------------------------------------

To view constraint name with corresponding column name

SELECT * FROM user_cons_columns c

WHERE c.table_name = 'MY_STU_DETAILS';

-------------------------------------------------------------

owner constraint_name table_name column_name position

-------------------------------------------------------------

HR MY_STU_MAIL_UK MY_STU_DETAILS S_MAIL 1

HR MY_STU_SID_PK MY_STU_DETAILS S_ID 1

HR MY_STU_GEN_CK MY_STU_DETAILS S_GENDER

HR SYS_C004023 MY_STU_DETAILS S_NAME

HR MY_STU_DID_FK MY_STU_DETAILS S_DID 1

-------------------------------------------------------------

Creating Composite Primary Key


Creating Primary Key with more than one number of column

ALTER TABLE table_name

ADD CONSTRAINT constraint_name PRIMARY KEY(column1, column_2 , column3);

In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.

creating constraint after the table creation

ALTER TABLE table_name

ADD CONSTRAINT constraint_name CONSTRAINT_TYPE(column_name);

ALTER TABLE table_name

DROP CONSTRAINT constraint_name;

ALTER TABLE table_name

DROP PRIMARY KEY;

To drop related foreign key


ALTER TABLE table_name

DROP PRIMARY KEY CASCADE;

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name;

Disable constraint with related foreign key constraint

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name CASCADE;

ALTER TABLE table_name

ENABLE CONSTRAINT constraint_name;

Interview Questions

What are all the type of constraint available in oracle?

Difference between PRIMARY KEY and UNIQUE key.

Difference between PRIMARY KEY ans FOREIGN KEY.

Difference between UNIQUE key and FOREIGN KEY.


Is it possible to create tow primary key in single table.

Write a syntax to create FOREIGN constraint.

How to create constraint after the table has been created?

How to enable and disable a constraint.

Which data dictionary table contains information about constraints?

Which Data Dictionary table contains information about constraint with corresponding column
name?

What is composite primary key?

Explain ON DELETE CASCADE and ON DELETE SET NULL option.

~Thanks For Reading~

Post your valuable feedback below

Posted 21st December 2014 by Unknown

1 View comments

UnknownMay 22, 2017 at 12:39 AM

good

Reply
DEC

listagg in Oracle 11g

Oracle 11gR2 listagg built-in function allows for many table columns to be displayed within a
single row, a non-first-normal form display

Syntax :

listagg(column_value,'delimiter') WITHIN GROUP(ORDER BY column_name)

--Example 1:

CREATE TABLE test_ins(empid NUMBER,product VARCHAR2(30));

BEGIN

INSERT INTO test_ins VALUES( 101,'pendrive');

INSERT INTO test_ins VALUES( 102,'toy');

INSERT INTO test_ins VALUES( 101,'ipod');

INSERT INTO test_ins VALUES( 102,'hat');

INSERT INTO test_ins VALUES( 103,'cpu');

INSERT INTO test_ins VALUES( 104,'pen');

INSERT INTO test_ins VALUES( 104,'car');

INSERT INTO test_ins VALUES( 104,'mat');

INSERT INTO test_ins VALUES( 105,'tv');


INSERT INTO test_ins VALUES( 106,'laptop');

commit;

END;

SELECT * FROM test_ins;

SELECT empid "Employee",

listagg(product,

',') within

GROUP (ORDER BY empid) "Products"

FROM test_ins

GROUP BY empid;

-->-- Result set --<--


DROP TABLE test_ins;

-->-- Example 2

select department_id "Department id", listagg(first_name,', ') WITHIN GROUP(ORDER BY


employee_id) "Employees"

FROM employees

WHERE department_id IN (10,20,30,60)

GROUP BY department_id;

-->-- Result set --<--

Posted 4th December 2014 by Unknown

0 Add a comment

NOV

Condition and Looping Statement


IF

IF ELSE

Multiple IF ELSE

LOOP

FOR LOOP

WHILE LOOP

create table test_udt(id NUMBER, salary NUMBER);

BEGIN

INSERT INTO test_udt VALUES(001,23000);

INSERT INTO test_udt VALUES(002,43000);

INSERT INTO test_udt VALUES(003,78000);

INSERT INTO test_udt VALUES(004,25000);

INSERT INTO test_udt VALUES(005,26000);

INSERT INTO test_udt VALUES(006,90000);

Commit;

END;

select * from test_udt;


IF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 1;

IF v_salary > 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

END IF;

commit;

END;

IF ELSE
DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

ELSE

UPDATE test_udt t

SET t.salary = v_salary+20007

WHERE t.id = v_id ;

END IF;

commit;

END;

--same example with less number of lines


DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

v_salary := v_salary+10005;

ELSE

v_salary := v_salary+20007;

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;


Multiple IF ELSIF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 3;

IF v_id = 1 THEN

v_salary := 1000;

dbms_output.put_line('1 inside');

ELSIF v_id = 2 THEN

v_salary := 2000;

dbms_output.put_line('2 inside');

ELSIF v_id = 3 THEN

v_salary := 3000;

dbms_output.put_line('3 inside');

ELSIF v_id = 4 THEN

v_salary := 4000;

dbms_output.put_line('4 inside');

END IF;
UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

LOOP

--syntax

LOOP

--statements

--increment

--exit statement

END LOOP;

CREATE TABLE prod_details (pid VARCHAR2(3), pname VARCHAR2(30));

DECLARE

i NUMBER := 1;
x VARCHAR2(3);

BEGIN

LOOP

x := lpad(i,3,'0');

dbms_output.put_line('x value : '|| x);

INSERT INTO prod_details VALUES(i, 'Product '||i);

EXIT WHEN i >900;

i := i+1;

IF MOD(i,100) = 0 THEN

commit;

dbms_output.put_line('commit executed');

END IF;

END LOOP;

END;

SELECT * FROM prod_details ORDER BY 1;

DROP TABLE prod_details;

FOR LOOP

BEGIN

FOR I in 1..5
LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

FOR LOOP - Reverse

BEGIN

FOR I in REVERSE 14..50

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

WHILE LOOP

DECLARE

i_val NUMBER:=0;

BEGIN

WHILE (i_val < 11)

LOOP

dbms_output.put_line('The value of I is '||i_val);

i_val := i_val + 1;
END LOOP;

END;

sample output:

The value of I is 0

The value of I is 1

The value of I is 2

The value of I is 3

The value of I is 4

The value of I is 5

The value of I is 6

The value of I is 7

The value of I is 8

The value of I is 9

The value of I is 10

Posted 8th November 2014 by Unknown

0 Add a comment

OCT
21

Bulk Collect

This is used for array fetches

With this you can retrieve multiple rows of data with a single round trip.

This reduces the number of context switches between the pl/sql and sql engines.

You can use bulk collect in both dynamic and static sql.

You can use bulk collect in select, fetch into and returning into clauses.

SQL engine automatically initializes and extends the collections you reference in the bulk
collect clause.

You can fetch into multiple collections with one column each.

You can use the limit clause of bulk collect to restrict the no of rows retrieved.

SELECT * FROM product_details;

-->-- Bulk collect in FETCH INTO --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN
OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Bulk collect in SELECT clause --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

BEGIN

SELECT * BULK COLLECT INTO dta FROM product_details;

FOR i IN dta.FIRST .. dta.LAST LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;
-->-- LIMIT in Bulk collect --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta LIMIT 30;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Multiple fetches in INTO clause --<--

SELECT * FROM product_details;


DECLARE

TYPE alldata_typ1 IS TABLE OF product_details.p_id%TYPE;

TYPE alldata_typ2 IS TABLE OF product_details.p_name%TYPE;

dta1 alldata_typ1;

dta2 alldata_typ2;

CURSOR proddt_cur IS

SELECT p_id, p_name FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta1, dta2;

CLOSE proddt_cur;

FOR i IN dta1.FIRST .. dta1.COUNT LOOP

dbms_output.put_line('Department Id : ' || dta1(i));

END LOOP;

FOR i IN dta2.FIRST .. dta2.COUNT LOOP

dbms_output.put_line('Department Name : ' || dta2(i));

END LOOP;

END;

/
DROP TABLE dep_details;

DROP TABLE product_details;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Ref Cursor

This is unconstrained cursor which will return different types depends upon the user input.

Ref cursors cannot be closed implicitly.

Ref cursor with return type is called strong cursor.

Ref cursor without return type is called weak cursor.

You can declare ref cursor type in package spec as well as body.

You can declare ref cursor types in local subprograms or anonymous blocks.

CREATE OR REPLACE PROCEDURE ref_c_sp(dep_det_c IN OUT SYS_REFCURSOR)

AS

BEGIN

OPEN dep_det_c

FOR
SELECT * FROM dep_details d;

END;

DECLARE

dep_det_c SYS_REFCURSOR;

tab_data dep_details%ROWTYPE;

BEGIN

ref_c_sp(dep_det_c);

LOOP

FETCH dep_det_c INTO tab_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department Name : '|| tab_data.d_name);

END LOOP;

CLOSE dep_det_c;

END;

/*sample output*/

Department Name : Admin

Department Name : HR

Department Name : Sales


Department Name : Marketing

DROP PROCEDURE ref_c_sp;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Cursor

SQL Private work Area where the query get passed and executed.

Types

******

Implicit(SQL)

Explicit

-->-- advanced cursor types --<--

Parametrized Cursor

Ref Cursor

Implicit
********

ORACLE implicitly opens a cursor to process each SQL statement not associated with an
explicitly declared cursor.

PL/SQL lets you refer to the most recent implicit cursor as the SQL” cursor. So, although you
cannot use the OPEN,

FETCH, and CLOSE statements to control an implicit cursor, you can still use cursor attributes to
access information

about the most recently executed SQL statement.

Cursor Stages

**************

OPEN cursor_name

FETCH (with in loop)

CLOSE cursor_name

Explicit

The set of rows returned by a query can consist of zero, one, or multiple rows,

depending on how many rows meet your search criteria. When a query returns multiple rows,

you can explicitly define a cursor to process the rows. You use three commands to control the
cursor

Cursor Attributes

*****************
%FOUND

%NOTFOUND

%ISOPEN

%ROWCOUNT

%BULK_ROWCOUNT --<-- used to handle error while using bulk collection.

%BULK_EXCEPTIONS --<-- used to handle error while using bulk collection.

Cursor Declaration

DECLARE

CURSOR <cursor_name>

IS

<SELECT statement>

BEGIN

--> some stmt

END;

Cursor Loop

Loop

While Loop

For Loop

Cursor Clauses

Return
For update

Where current of

Bulk collect

-->-- creating table

create table product_details

p_id NUMBER,

p_name VARCHAR2(30),

p_order_dt DATE

);

-->-- Inserting data

BEGIN

FOR i IN 1 .. 75 LOOP

INSERT INTO product_details VALUES (i, 'prod_name_' || i, SYSDATE + i);

END LOOP;

commit;

END;
-->-- selecting data

SELECT * FROM product_details;

---------------------------------------------

p_id p_name p_order_dt

---------------------------------------------

1 prod_name_1 10/11/2014 3:48:32 PM

2 prod_name_2 10/12/2014 3:48:32 PM

3 prod_name_3 10/13/2014 3:48:32 PM

4 prod_name_4 10/14/2014 3:48:32 PM

5 prod_name_5 10/15/2014 3:48:32 PM

6 prod_name_6 10/16/2014 3:48:32 PM

7 prod_name_7 10/17/2014 3:48:32 PM

8 prod_name_8 10/18/2014 3:48:32 PM

9 prod_name_9 10/19/2014 3:48:32 PM

10 prod_name_10 10/20/2014 3:48:32 PM

11 prod_name_11 10/21/2014 3:48:32 PM

12 prod_name_12 10/22/2014 3:48:32 PM

13 prod_name_13 10/23/2014 3:48:32 PM

14 prod_name_14 10/24/2014 3:48:32 PM

15 prod_name_15 10/25/2014 3:48:32 PM

16 prod_name_16 10/26/2014 3:48:32 PM

17 prod_name_17 10/27/2014 3:48:32 PM

18 prod_name_18 10/28/2014 3:48:32 PM


19 prod_name_19 10/29/2014 3:48:32 PM

20 prod_name_20 10/30/2014 3:48:32 PM

---------------------------------------------

----------------------------------------------

Implicit Cursor

----------------------------------------------

--will update soon

----------------------------------------------

Explicit Cursor

----------------------------------------------

**********************************************

Processing cursor data by using LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;


BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND; --<-- if next record not found means control will
come out from the loop

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

DECLARE

all_data product_details%ROWTYPE;
--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

EXIT WHEN prod_detail_cur%FOUND; --<-- if next record found means control will come
out from the loop

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

DECLARE
all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;
/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor Already closed

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;
EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

-->-- CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor closed


**********************************************

Processing cursor data by using WHILE LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

OPEN prod_detail_cur;

FETCH prod_detail_cur

INTO all_data;

WHILE prod_detail_cur%FOUND LOOP

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

FETCH prod_detail_cur

INTO all_data;
END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

************************************************************

Processing cursor data by using FOR LOOP - CURSOR FOR LOOP

************************************************************

DECLARE

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

FOR i IN prod_detail_cur

LOOP

dbms_output.put_line('Product id : ' || i.p_id ||


' Product Name : ' || i.p_name ||

' ( Orderd on : ' || TRIM(i.p_order_dt) || ' )');

END LOOP;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

Parameterized Cursor

*********************

This was used when you are going to use the cursor in more than one place with different
values for the same where clause.

Cursor parameters must be in mode.

Cursor parameters may have default values.

The scope of cursor parameter is within the select statement.


CREATE TABLE dep_details(d_id NUMBER,d_name VARCHAR2(30), location_id NUMBER);

BEGIN

INSRT INTO dep_details VALUES(001,'Admin',1010);

INSRT INTO dep_details VALUES(002,'HR',1010);

INSRT INTO dep_details VALUES(003,'Sales',1020);

INSRT INTO dep_details VALUES(004,'Marketing',1020);

commit;

END;

SELECT * FROM dep_details;

----------------------------

d_id d_name location_id

----------------------------

1 Admin 1010

2 HR 1010

3 Sales 1020

4 Marketing 1020

----------------------------

DECLARE

-->--Declaring parameterized cursor


CURSOR dep_det_c(p_location_id NUMBER) IS

SELECT * FROM dep_details d WHERE d.location_id = p_location_id;

all_data dep_details%ROWTYPE;

BEGIN

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

OPEN dep_det_c(1010);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

-->-- opening same cursor with different input value

OPEN dep_det_c(1020);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||


' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

END;

/*sample output*/

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 1 Department Name : Admin

Department id : 2 Department Name : HR

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 3 Department Name : Sales

Department id : 4 Department Name : Marketing

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Handling Exception
Error Handling in oracle

ERROR

Any departure from the expected behavior of the system or program,

which stops the working of the system is an error.

Types : compile time error

Run time error

EXCEPTION

Any error or problem which one can handle and continue to work normally.

Handling Exception

When exception is raised, control passes to the exception section of the block.

i.e. EXCEPTION

WHEN name_of_exception THEN

Types : Pre Defined Exceptions

User Defined Exceptions

Predefined Exception

*********************
Oracle has predefined several exceptions that correspond to the most common oracle errors.

------------------------------------------------------------------------

Exception Oracle Error SQL Code Value

------------------------------------------------------------------------

ZERO_DIVIDE ORA-01476 -1476

NO_DATA_FOUND ORA-01403 +100

DUP_VAL_ON_INDEX ORA-00001 -1

TOO_MANY_ROWS ORA-01422 -1422

VALUE_ERROR ORA-06502 -6502

CURSOR_ALREADY_OPEN ORA-06511 -6511

OTHERS

------------------------------------------------------------------------

-->-- ZERO_DIVIDE --<--

Your program attempts to divide a number by zero.

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION
WHEN ZERO_DIVIDE THEN

dbms_output.put_line('Divisor is equal to zero');

END;

-->-- NO_DATA_FOUND --<--

Single row SELECT returned no rows or your program referenced a deleted element in a nested
table

or an uninitialized element in an associative array (index-by table).

CREATE TABLE test_tb(id NUMBER PRIMARY KEY);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN NO_DATA_FOUND THEN

dbms_output.put_line('There is no data inside the table');

END;

-->-- DUP_VAL_ON_INDEX --<--


A program attempted to insert duplicate values in a column that is constrained by a unique
index.

INSERT INTO test_tb VALUES (1);

INSERT INTO test_tb VALUES (2);

commit;

BEGIN

INSERT INTO test_tb VALUES (2);

EXCEPTION

WHEN DUP_VAL_ON_INDEX THEN

dbms_output.put_line('Duplicate values are not allowed');

END;

-->-- TOO_MANY_ROWS --<--

Single row SELECT returned multiple rows.

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION
WHEN TOO_MANY_ROWS THEN

dbms_output.put_line('Query returning more than one row');

END;

DROP TABLE test_tb;

-->-- VALUE_ERROR --<--

An arithmetic, conversion, truncation, or size constraint error occurred.

DECLARE

num1 NUMBER(2);

BEGIN

num1 := 345;

EXCEPTION

WHEN VALUE_ERROR THEN

dbms_output.put_line('check the size of the variable');

END;

-->-- CURSOR_ALREADY_OPEN --<--

A program attempted to open an already opened cursor.


CREATE TABLE emp(id NUMBER, name VARCHAR2(30));

BEGIN

INSERT INTO emp VALUES(1,'Name1');

INSERT INTO emp VALUES(2,'Name2');

INSERT INTO emp VALUES(3,'Name3');

INSERT INTO emp VALUES(4,'Name4');

COMMIT;

END;

SELECT * FROM emp;

DECLARE

cursor emp_c IS

SELECT * FROM emp;

all_data emp%ROWTYPE;

BEGIN

OPEN emp_c;

OPEN emp_c;

NULL;

CLOSE emp_c;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN


dbms_output.put_line('Cursor already opened');

END;

DROP TABLE emp;

-->-- OTHERS --<--

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

WHEN OTHERS THEN

dbms_output.put_line('Some other error ' || SQLERRM);

END;

User Defined Exception

**********************

A user-defined exception is an error that is defined by the programmer.


User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,

exceptions have a type EXCEPTION and scope.

DECLARE

v_gender CHAR := '&gender';

gender_ex EXCEPTION;

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE gender_ex;

END IF;

dbms_output.put_line('Gender : '||v_gender);

EXCEPTION

WHEN gender_ex THEN

dbms_output.put_line('Please Enter valid gender');

END;

create table test_insert (id NUMBER, Name VARCHAR2(30));

DECLARE

abort_ex EXCEPTION;

BEGIN

FOR i IN 1..100

LOOP
BEGIN

IF mod(i,10)=0 THEN

RAISE abort_ex;

END IF;

INSERT INTO test_insert VALUES(i, 'Name'||i);

EXCEPTION

WHEN abort_ex THEN

NULL;

END;

END LOOP;

COMMIT;

END;

SELECT * FROM test_insert;

DROP TABLE test_insert;

SQLERRM and SQLCODE

********************

SQLCODE returns the current error code, and SQLERRM returns the current error message
text;

For user-defined exception SQLCODE returns 1 and SQLERRM returns “user-defined


exception”.

SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.
CREATE TABLE test_tb (id NUMBER);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

dbms_output.put_line(v_id);

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('SQLERRM : ' || SQLERRM);

dbms_output.put_line('SQLCODE : ' || SQLCODE);

END;

/*sample output*/

SQLERRM : ORA-01403: no data found

SQLCODE : 100

DROP TABLE test_tb;

PRAGMA EXCEPTION_INIT

*********************
Using this you can associate a named exception with a particular oracle error.

This gives you the ability to trap this error specifically, rather than via an OTHERS handler.

Syntax:

PRAGMA EXCEPTION_INIT(exception_name, oracle_error_number);

DECLARE

v_result NUMBER;

PRAGMA EXCEPTION_INIT(Invalid, -1476);

BEGIN

SELECT 453 / 0 INTO v_result FROM dual;

dbms_output.put_line('Result : ' || v_result);

EXCEPTION

WHEN INVALID THEN

dbms_output.put_line('Invalid Exception');

END;

RAISE_APPLICATION_ERROR

************************
You can use this built-in function to create your own error messages, which can be more
descriptive than named exceptions.

Error Number :

Oracle Error Range : From -00000 to -19999

User Error Range : From -20000 to -20999

DECLARE

v_gender CHAR := '&gender';

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE_APPLICATION_ERROR(-20003, 'Enter valid gender');

END IF;

dbms_output.put_line('Gender : ' || v_gender);

END;

Posted 21st October 2014 by Unknown

1 View comments

Loading
Dynamic Views theme. Powered by Blogger.

Oracle sql & Pl/sql

search

Home Sql and pl/sql Sql Interview Questions

JUL

20

INLINE view in Oracle with 12c New Features

Named sub Query in FROM clause is call it as INLINE VIEW.

Oracle process a inline view faster than sub query

Inline View in Oracle

--Query to display all the employees who are all getting salary more than their department
average salary

SELECT First_name

, last_name

, salary

, department_id

FROM employees a , ( SELECT b.department_id

, AVG(b.salary) avg_sal

FROM employees b

GROUP BY b.department_id
)b

WHERE a.department_id = b.department_id

AND a.salary > b.avg_salary;

Display all the customer who have placed more number of orders by using INLINE view

CREATE TABLE customer_order_det_tb

( custm_id NUMBER ,

custm_nm VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

ttl_amt NUMBER(7,2)

);

BEGIN

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '11-Jul-15' , 45000.00);

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '14-Jul-15' , 27000.00);

INSERT INTO customer_order_det_tb VALUES(101, 'Raja' , '13-Jul-15' , 17000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 34000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 38000.00);

COMMIT;

END;

SELECT c.*
FROM customer_order_det_tb c;

--------------------------------------------

custm_id custm_nm order_dt ttl_amt

--------------------------------------------

100 Murugappan 7/11/2015 45000.00

100 Murugappan 7/14/2015 27000.00

101 Raja 7/13/2015 17000.00

102 Ramesh 7/15/2015 34000.00

102 Ramesh 7/15/2015 38000.00

--------------------------------------------

--Writing a Quer to display all the customer who have placed maximum number of order

--Query #1 for inline view

SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC;

--------------------------------

custm_id custm_nm total_odr

--------------------------------

100 Murugappan 2
102 Ramesh 2

101 Raja 1

--------------------------------

--Query #2 for inline view

SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm;

----------

total_odr

----------

----------

Inline view to find all the customers who have placed maximum number of orders

/****************************************

Syntax

SELECT * FROM <query1> x, <query2> y

WHERE contition;

****************************************/
SELECT query1.* FROM

( SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC

) query1,

( SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm

) query2

WHERE query1.total_odr = query2.total_odr;

-------------------------------

custm_id custm_nm total_odr

-------------------------------

100 Murugappan 2

102 Ramesh 2

-------------------------------

DROP TABLE customer_order_det_tb;

--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT

SELECT first_name, salary


FROM ( SELECT first_name, salary

FROM employees e

WHERE job_id NOT IN ('SALESMAN','PRESIDENT')

ORDER BY salary DESC

WHERE ROWNUM < 4;

New Oracle 12c Inline view Syntax

LATERAL clause for In-line views

Allows for columns in the inline view to be accessed!!

Example :

--in 11g

SELECT * FROM employees e, (

SELECT *

FROM departments d

WHERE e.department_id = d.department_id);

ORA-0090: "E"."DEPARTMENT_ID": Invalid Identifier


--in 12c

SELECT * FROM employees e, LATERAL(

SELECT *

FROM departments d

WHERE e.department_id = d.department_id

);

--in 11g

WITH t

AS

( SELECT LEVEL a

FROM dual

CONNECT BY LEVEL <= 30)

SELECT *

FROM t, (SELECT *

FROM employees

WHERE department_id = t.a

);

ORA-00904: "T"."A": invalid Identifier

--in 12c

WITH t

AS
(SELECT LEVEL a FROM dual CONNECT BY LEVEL <= 30)

SELECT * FROM t,

LATERAL(SELECT *

FROM employees

WHERE department_id = t.a);

Hope you have enjoyed this little article

Feed backs are always Welcome :) (:

Posted 20th July 2015 by Unknown

0 Add a comment

JAN

23

Salary Related Questions in Oracle

--creating table

CREATE TABLE employee_data

eid NUMBER(4),
ename VARCHAR2(30),

depno NUMBER(3),

salary NUMBER(8)

);

BEGIN

--Inserting records

INSERT INTO employee_data VALUES(1000,'Name01',90,30000);

INSERT INTO employee_data VALUES(1001,'Name02',90,6000);

INSERT INTO employee_data VALUES(1002,'Name03',90,23000);

INSERT INTO employee_data VALUES(1003,'Name04',60,35000);

INSERT INTO employee_data VALUES(1004,'Name05',60,60000);

INSERT INTO employee_data VALUES(1005,'Name06',60,30000);

INSERT INTO employee_data VALUES(1006,'Name07',80,36000);

INSERT INTO employee_data VALUES(1007,'Name08',80,29000);

INSERT INTO employee_data VALUES(1008,'Name09',80,37000);

INSERT INTO employee_data VALUES(1009,'Name10',80,41000);

COMMIT;

END;

SELECT * FROM employee_data


ORDER BY salary DESC;

--query to find maximum salary from employee_data table

SELECT MAX(salary) FROM employee_data;

--query to find minimum salary from employee_data table

SELECT MIN(salary) FROM employee_data;

--query to find second maximum salary from employee_data table

SELECT MAX(salary)

FROM employee_data

WHERE salary NOT IN (SELECT MAX(salary)

FROM employee_data);

--query to select 5th maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= 5);


--query to select nth maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= &n);

--query to select all the details of the employee whose getting nth maximum salary

SELECT *

FROM (SELECT emp.*,

rownum rn

FROM (SELECT *

FROM employee_data

ORDER BY salary DESC) emp)

WHERE rn = 9;

--same query using row_numbr( ) function

SELECT *
FROM (SELECT emp.*,

row_number() over(ORDER BY salary) rank

FROM employee_data emp)

WHERE rank = 9;

--same query using rank( ) function

SELECT *

FROM (SELECT emp.*,

rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--same query using dense_rank( ) function

SELECT *

FROM (SELECT emp.*,

dense_rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--query to display display maximum salary in all the department

SELECT e.depno "Department id",


MAX(salary) "Maximum Salary"

FROM employee_data e

GROUP BY e.depno;

--query to display all the employees who are all getting salary more than average salary of the
company

SELECT e.* FROM employee_data e

WHERE salary > (SELECT AVG(salary) FROM employee_data);

--query to display all the employees who are all getting salary more than their department
average salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE department_id = OUT.department_id);

--query to display all the employees who are all getting salary more than their manager salary

SELECT employee_id,
first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE employee_id = OUT.manager_id);

Documented By : Murugappan Annamalai

Posted on : 23-Jan-15 16:34:00 IST.

Hope you have enjoyed this little article

Feed backs are always welcome :)

Posted 23rd January 2015 by Unknown

7 View comments

JAN

22

Why prefer COALESCE over NVL

Documented By : Nimish Garg


I prefer using "COALESCE" over "NVL" is some of the scenarios. Last week One of my friend
asked me what is the advantage of using "COALESCE" where we can simply use "NVL". I simply
gave him the reply from Oracle Docs i.e. NVL lets you replace null (returned as a blank) with a
string in the results of a query and COALESCE returns the first non-null expr in the expression list.
Oracle Database uses short-circuit evaluation with "COALESCE".

He replied that he knows the difference, he knows that "COALESCE" can take multiple arguments
and so on. He was more interested in understanding "short-circuit evaluation" of "COALESCE"
and the scenarios where I prefer using "COALESCE" over "NVL".

To make him understand I created following function which takes One second in every execution
and simply returns '--null--' and executed 2 very similar queries one with NVL and other with
COALESCE.

SQL> create or replace function f_null return varchar2

2 is

3 begin

4 dbms_lock.sleep(1);

5 return '--null--';

6 end;

7 /

Function created.

Following are the queries which I used to demonstrate that NVL evaluates both arguments even
if the second argument is not used and COALESCE uses short-circuit evaluation i.e. it only
evaluates the arguments only if they are needed.
SQL> select e.empno, e.ename ename, nvl(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.
Elapsed: 00:00:14.01

SQL> select e.empno, e.ename ename, coalesce(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.
Elapsed: 00:00:01.01

Here we can see easily that the first query with NVL took 14+ seconds, one second for each
record even if the "f_null" value was used only in one record. On the contrary as mentioned in
Oracle Documentation "COALESCE" uses its "short-circuit evaluation" and "f_null" was called
only once and so second query took only One Second. "COALESCE" is certainly use less resources
than NVL.

Posted 22nd January 2015 by Unknown

0 Add a comment

DEC

21

Constraints

It Enforce Rule On Table

We can create constraint at the time of Creating Table

1. Column Level Declaration

2. Table Level Declaration


1. We can provide own name.

Format : [part_of_project_name-table_name-column_name-constraint_type]

Example : gmind_emp_id_pk _uk _ck _f

2. system name name

Format : sys_cn

Example : SYS_C405323

We can create constraint after the table has been created

Types

Primary Key

Not allowed Null value

Not allowed you to enter duplicate value

Ex : Employee_id, Student_id

Unique Key
allowed Null value

Not allowed you to enter duplicate value

Ex : Contact_no, email

Foreign Key

It will allowed you to enter NULL and Duplicate value.

c1(pk) : 1 2 3

c2(f) : 1 1 2 3 4 Not allowed

Allowed you to enter duplicate value and null value

Not Null

It will not allowed you to enter null value

Check

You can check your own condition

Simple Table for understanding


------------------------------------

Duplicate NULL

------------------------------------

Primary Key X X

Unique Key X Allowed

Foreign Key Allowed Allowed

------------------------------------

creating table with all constraint type

Create table my_stu_details

S_id Number(2),

S_name Varchar2(30) Not Null, --SYS_Cn

s_mail Varchar2(30),

s_gender char(1),

s_did Number(3),

Constraint my_stu_sid_pk PRIMARY KEY (s_id),

constraint my_stu_mail_uk UNIQUE (s_mail) ,

Constraint my_stu_gen_ck CHECK (s_gender IN ('M', 'F', 'm', 'f')),

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

);
DESC my_stu_details;

------------------------------------

Name Type Nullable

------------------------------------

S_ID NUMBER(2)

S_NAME VARCHAR2(30)

S_MAIL VARCHAR2(30) Y

S_GENDER CHAR(1) Y

S_DID NUMBER(3) Y

------------------------------------

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name1' , 'name1@gmail.com' , 'm' , 60 );

Select * from my_stu_details;

Validating Primary Key


Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-00001: unique constraint (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (NULL, 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-01400: cannot insert NULL into (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (2 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

Validating NOT NULL Constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , NULL , 'name3@gmail.com' , 'F' , 80 );

ORA-01400: cannot insert NULL into ("HR"."MY_STU_DETAILS"."S_NAME")


Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , 'Name3' , 'name3@gmail.com' , 'F' , 80 );

Select * from my_stu_details;

Validating Unique Key Constraint

--Duplicate Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , 'name3@gmail.com' , 'F' , 80 );

ORA-00001: unique constraint (HR.MY_STU_MAIL_UK) violated

--Null Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , null , 'M' , 70 );


Select * from my_stu_details;

Validating Check constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'j' , 70 );

ORA-02290: check constraint (HR.MY_STU_GEN_CK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'M' , 70 );

Select * from my_stu_details;

Validating Foreign Key

Select * from Departments;


Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 3 );

ORA-02291: integrity constraint (HR.MY_STU_DID_FK) violated - parent key not found

Departments table : parent table

my_stu_details : Child table

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

--------------------------------------------------------

s_id s_name s_mail s_gender s_did

--------------------------------------------------------

1 name1 name1@gmail.com m 60

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 M 70

5 Name5 name5@gmail.com M 70
6 Name6 name6@gmail.com F 90

--------------------------------------------------------

Deleting the Primary key value which is referred by Foreign Key

Select * from Departments;

DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID

------------------------------------------------------------

60 IT 103 1400 <---- Delete

-- don't execute this query

--Delete From Departments

--Where Department_id = 60;

1) ON DELETE SET NULL

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------
6 Name6 name6@gmail.com F 90

1 name1 name1@gmail.com m -

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

2) ON DELETE SET CASCADE

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

Syntax

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE CASCADE
Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE SET NULL

Constraint Related Data Dictionary Table information.

To view constraint Information

SELECT c.owner,

c.constraint_name,

c.constraint_type,

c.table_name,

c.r_constraint_name,

c.status

FROM user_constraints c

WHERE c.table_name = 'MY_STU_DETAILS';

------------------------------------------------------------------------------------

owner constraint_name constraint_type table_name r_constraint_name status

------------------------------------------------------------------------------------

HR SYS_C004023 C MY_STU_DETAILS ENABLED

HR MY_STU_GEN_CK C MY_STU_DETAILS ENABLED

HR MY_STU_SID_PK P MY_STU_DETAILS ENABLED


HR MY_STU_MAIL_UK U MY_STU_DETAILS ENABLED

HR MY_STU_DID_FK R MY_STU_DETAILS DEPT_ID_PK ENABLED

------------------------------------------------------------------------------------

To view constraint name with corresponding column name

SELECT * FROM user_cons_columns c

WHERE c.table_name = 'MY_STU_DETAILS';

-------------------------------------------------------------

owner constraint_name table_name column_name position

-------------------------------------------------------------

HR MY_STU_MAIL_UK MY_STU_DETAILS S_MAIL 1

HR MY_STU_SID_PK MY_STU_DETAILS S_ID 1

HR MY_STU_GEN_CK MY_STU_DETAILS S_GENDER

HR SYS_C004023 MY_STU_DETAILS S_NAME

HR MY_STU_DID_FK MY_STU_DETAILS S_DID 1

-------------------------------------------------------------

Creating Composite Primary Key


Creating Primary Key with more than one number of column

ALTER TABLE table_name

ADD CONSTRAINT constraint_name PRIMARY KEY(column1, column_2 , column3);

In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.

creating constraint after the table creation

ALTER TABLE table_name

ADD CONSTRAINT constraint_name CONSTRAINT_TYPE(column_name);

ALTER TABLE table_name

DROP CONSTRAINT constraint_name;

ALTER TABLE table_name

DROP PRIMARY KEY;

To drop related foreign key

ALTER TABLE table_name


DROP PRIMARY KEY CASCADE;

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name;

Disable constraint with related foreign key constraint

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name CASCADE;

ALTER TABLE table_name

ENABLE CONSTRAINT constraint_name;

Interview Questions

What are all the type of constraint available in oracle?

Difference between PRIMARY KEY and UNIQUE key.

Difference between PRIMARY KEY ans FOREIGN KEY.

Difference between UNIQUE key and FOREIGN KEY.

Is it possible to create tow primary key in single table.


Write a syntax to create FOREIGN constraint.

How to create constraint after the table has been created?

How to enable and disable a constraint.

Which data dictionary table contains information about constraints?

Which Data Dictionary table contains information about constraint with corresponding column
name?

What is composite primary key?

Explain ON DELETE CASCADE and ON DELETE SET NULL option.

~Thanks For Reading~

Post your valuable feedback below

Posted 21st December 2014 by Unknown

1 View comments

UnknownMay 22, 2017 at 12:39 AM

good

Reply

DEC
4

listagg in Oracle 11g

Oracle 11gR2 listagg built-in function allows for many table columns to be displayed within a
single row, a non-first-normal form display

Syntax :

listagg(column_value,'delimiter') WITHIN GROUP(ORDER BY column_name)

--Example 1:

CREATE TABLE test_ins(empid NUMBER,product VARCHAR2(30));

BEGIN

INSERT INTO test_ins VALUES( 101,'pendrive');

INSERT INTO test_ins VALUES( 102,'toy');

INSERT INTO test_ins VALUES( 101,'ipod');

INSERT INTO test_ins VALUES( 102,'hat');

INSERT INTO test_ins VALUES( 103,'cpu');

INSERT INTO test_ins VALUES( 104,'pen');

INSERT INTO test_ins VALUES( 104,'car');

INSERT INTO test_ins VALUES( 104,'mat');

INSERT INTO test_ins VALUES( 105,'tv');

INSERT INTO test_ins VALUES( 106,'laptop');


commit;

END;

SELECT * FROM test_ins;

SELECT empid "Employee",

listagg(product,

',') within

GROUP (ORDER BY empid) "Products"

FROM test_ins

GROUP BY empid;

-->-- Result set --<--


DROP TABLE test_ins;

-->-- Example 2

select department_id "Department id", listagg(first_name,', ') WITHIN GROUP(ORDER BY


employee_id) "Employees"

FROM employees

WHERE department_id IN (10,20,30,60)

GROUP BY department_id;

-->-- Result set --<--

Posted 4th December 2014 by Unknown

0 Add a comment

NOV

Condition and Looping Statement


IF

IF ELSE

Multiple IF ELSE

LOOP

FOR LOOP

WHILE LOOP

create table test_udt(id NUMBER, salary NUMBER);

BEGIN

INSERT INTO test_udt VALUES(001,23000);

INSERT INTO test_udt VALUES(002,43000);

INSERT INTO test_udt VALUES(003,78000);

INSERT INTO test_udt VALUES(004,25000);

INSERT INTO test_udt VALUES(005,26000);

INSERT INTO test_udt VALUES(006,90000);

Commit;

END;

select * from test_udt;


IF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 1;

IF v_salary > 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

END IF;

commit;

END;

IF ELSE

DECLARE
v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

ELSE

UPDATE test_udt t

SET t.salary = v_salary+20007

WHERE t.id = v_id ;

END IF;

commit;

END;

--same example with less number of lines

DECLARE
v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

v_salary := v_salary+10005;

ELSE

v_salary := v_salary+20007;

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

Multiple IF ELSIF
DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 3;

IF v_id = 1 THEN

v_salary := 1000;

dbms_output.put_line('1 inside');

ELSIF v_id = 2 THEN

v_salary := 2000;

dbms_output.put_line('2 inside');

ELSIF v_id = 3 THEN

v_salary := 3000;

dbms_output.put_line('3 inside');

ELSIF v_id = 4 THEN

v_salary := 4000;

dbms_output.put_line('4 inside');

END IF;

UPDATE test_udt t
SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

LOOP

--syntax

LOOP

--statements

--increment

--exit statement

END LOOP;

CREATE TABLE prod_details (pid VARCHAR2(3), pname VARCHAR2(30));

DECLARE

i NUMBER := 1;

x VARCHAR2(3);
BEGIN

LOOP

x := lpad(i,3,'0');

dbms_output.put_line('x value : '|| x);

INSERT INTO prod_details VALUES(i, 'Product '||i);

EXIT WHEN i >900;

i := i+1;

IF MOD(i,100) = 0 THEN

commit;

dbms_output.put_line('commit executed');

END IF;

END LOOP;

END;

SELECT * FROM prod_details ORDER BY 1;

DROP TABLE prod_details;

FOR LOOP

BEGIN

FOR I in 1..5

LOOP
Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

FOR LOOP - Reverse

BEGIN

FOR I in REVERSE 14..50

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

WHILE LOOP

DECLARE

i_val NUMBER:=0;

BEGIN

WHILE (i_val < 11)

LOOP

dbms_output.put_line('The value of I is '||i_val);

i_val := i_val + 1;

END LOOP;
END;

sample output:

The value of I is 0

The value of I is 1

The value of I is 2

The value of I is 3

The value of I is 4

The value of I is 5

The value of I is 6

The value of I is 7

The value of I is 8

The value of I is 9

The value of I is 10

Posted 8th November 2014 by Unknown

0 Add a comment

OCT

21
Bulk Collect

This is used for array fetches

With this you can retrieve multiple rows of data with a single round trip.

This reduces the number of context switches between the pl/sql and sql engines.

You can use bulk collect in both dynamic and static sql.

You can use bulk collect in select, fetch into and returning into clauses.

SQL engine automatically initializes and extends the collections you reference in the bulk
collect clause.

You can fetch into multiple collections with one column each.

You can use the limit clause of bulk collect to restrict the no of rows retrieved.

SELECT * FROM product_details;

-->-- Bulk collect in FETCH INTO --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;
FETCH proddt_cur BULK COLLECT

INTO dta;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Bulk collect in SELECT clause --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

BEGIN

SELECT * BULK COLLECT INTO dta FROM product_details;

FOR i IN dta.FIRST .. dta.LAST LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;
-->-- LIMIT in Bulk collect --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta LIMIT 30;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Multiple fetches in INTO clause --<--

SELECT * FROM product_details;


DECLARE

TYPE alldata_typ1 IS TABLE OF product_details.p_id%TYPE;

TYPE alldata_typ2 IS TABLE OF product_details.p_name%TYPE;

dta1 alldata_typ1;

dta2 alldata_typ2;

CURSOR proddt_cur IS

SELECT p_id, p_name FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta1, dta2;

CLOSE proddt_cur;

FOR i IN dta1.FIRST .. dta1.COUNT LOOP

dbms_output.put_line('Department Id : ' || dta1(i));

END LOOP;

FOR i IN dta2.FIRST .. dta2.COUNT LOOP

dbms_output.put_line('Department Name : ' || dta2(i));

END LOOP;

END;

/
DROP TABLE dep_details;

DROP TABLE product_details;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Ref Cursor

This is unconstrained cursor which will return different types depends upon the user input.

Ref cursors cannot be closed implicitly.

Ref cursor with return type is called strong cursor.

Ref cursor without return type is called weak cursor.

You can declare ref cursor type in package spec as well as body.

You can declare ref cursor types in local subprograms or anonymous blocks.

CREATE OR REPLACE PROCEDURE ref_c_sp(dep_det_c IN OUT SYS_REFCURSOR)

AS

BEGIN

OPEN dep_det_c

FOR
SELECT * FROM dep_details d;

END;

DECLARE

dep_det_c SYS_REFCURSOR;

tab_data dep_details%ROWTYPE;

BEGIN

ref_c_sp(dep_det_c);

LOOP

FETCH dep_det_c INTO tab_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department Name : '|| tab_data.d_name);

END LOOP;

CLOSE dep_det_c;

END;

/*sample output*/

Department Name : Admin

Department Name : HR

Department Name : Sales


Department Name : Marketing

DROP PROCEDURE ref_c_sp;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Cursor

SQL Private work Area where the query get passed and executed.

Types

******

Implicit(SQL)

Explicit

-->-- advanced cursor types --<--

Parametrized Cursor

Ref Cursor

Implicit
********

ORACLE implicitly opens a cursor to process each SQL statement not associated with an
explicitly declared cursor.

PL/SQL lets you refer to the most recent implicit cursor as the SQL” cursor. So, although you
cannot use the OPEN,

FETCH, and CLOSE statements to control an implicit cursor, you can still use cursor attributes to
access information

about the most recently executed SQL statement.

Cursor Stages

**************

OPEN cursor_name

FETCH (with in loop)

CLOSE cursor_name

Explicit

The set of rows returned by a query can consist of zero, one, or multiple rows,

depending on how many rows meet your search criteria. When a query returns multiple rows,

you can explicitly define a cursor to process the rows. You use three commands to control the
cursor

Cursor Attributes

*****************
%FOUND

%NOTFOUND

%ISOPEN

%ROWCOUNT

%BULK_ROWCOUNT --<-- used to handle error while using bulk collection.

%BULK_EXCEPTIONS --<-- used to handle error while using bulk collection.

Cursor Declaration

DECLARE

CURSOR <cursor_name>

IS

<SELECT statement>

BEGIN

--> some stmt

END;

Cursor Loop

Loop

While Loop

For Loop

Cursor Clauses

Return
For update

Where current of

Bulk collect

-->-- creating table

create table product_details

p_id NUMBER,

p_name VARCHAR2(30),

p_order_dt DATE

);

-->-- Inserting data

BEGIN

FOR i IN 1 .. 75 LOOP

INSERT INTO product_details VALUES (i, 'prod_name_' || i, SYSDATE + i);

END LOOP;

commit;

END;
-->-- selecting data

SELECT * FROM product_details;

---------------------------------------------

p_id p_name p_order_dt

---------------------------------------------

1 prod_name_1 10/11/2014 3:48:32 PM

2 prod_name_2 10/12/2014 3:48:32 PM

3 prod_name_3 10/13/2014 3:48:32 PM

4 prod_name_4 10/14/2014 3:48:32 PM

5 prod_name_5 10/15/2014 3:48:32 PM

6 prod_name_6 10/16/2014 3:48:32 PM

7 prod_name_7 10/17/2014 3:48:32 PM

8 prod_name_8 10/18/2014 3:48:32 PM

9 prod_name_9 10/19/2014 3:48:32 PM

10 prod_name_10 10/20/2014 3:48:32 PM

11 prod_name_11 10/21/2014 3:48:32 PM

12 prod_name_12 10/22/2014 3:48:32 PM

13 prod_name_13 10/23/2014 3:48:32 PM

14 prod_name_14 10/24/2014 3:48:32 PM

15 prod_name_15 10/25/2014 3:48:32 PM

16 prod_name_16 10/26/2014 3:48:32 PM

17 prod_name_17 10/27/2014 3:48:32 PM

18 prod_name_18 10/28/2014 3:48:32 PM


19 prod_name_19 10/29/2014 3:48:32 PM

20 prod_name_20 10/30/2014 3:48:32 PM

---------------------------------------------

----------------------------------------------

Implicit Cursor

----------------------------------------------

--will update soon

----------------------------------------------

Explicit Cursor

----------------------------------------------

**********************************************

Processing cursor data by using LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;


BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND; --<-- if next record not found means control will
come out from the loop

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

DECLARE

all_data product_details%ROWTYPE;
--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

EXIT WHEN prod_detail_cur%FOUND; --<-- if next record found means control will come
out from the loop

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

DECLARE
all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;
/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor Already closed

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;
EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

-->-- CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor closed


**********************************************

Processing cursor data by using WHILE LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

OPEN prod_detail_cur;

FETCH prod_detail_cur

INTO all_data;

WHILE prod_detail_cur%FOUND LOOP

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

FETCH prod_detail_cur

INTO all_data;
END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

************************************************************

Processing cursor data by using FOR LOOP - CURSOR FOR LOOP

************************************************************

DECLARE

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

FOR i IN prod_detail_cur

LOOP

dbms_output.put_line('Product id : ' || i.p_id ||


' Product Name : ' || i.p_name ||

' ( Orderd on : ' || TRIM(i.p_order_dt) || ' )');

END LOOP;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

Parameterized Cursor

*********************

This was used when you are going to use the cursor in more than one place with different
values for the same where clause.

Cursor parameters must be in mode.

Cursor parameters may have default values.

The scope of cursor parameter is within the select statement.


CREATE TABLE dep_details(d_id NUMBER,d_name VARCHAR2(30), location_id NUMBER);

BEGIN

INSRT INTO dep_details VALUES(001,'Admin',1010);

INSRT INTO dep_details VALUES(002,'HR',1010);

INSRT INTO dep_details VALUES(003,'Sales',1020);

INSRT INTO dep_details VALUES(004,'Marketing',1020);

commit;

END;

SELECT * FROM dep_details;

----------------------------

d_id d_name location_id

----------------------------

1 Admin 1010

2 HR 1010

3 Sales 1020

4 Marketing 1020

----------------------------

DECLARE

-->--Declaring parameterized cursor


CURSOR dep_det_c(p_location_id NUMBER) IS

SELECT * FROM dep_details d WHERE d.location_id = p_location_id;

all_data dep_details%ROWTYPE;

BEGIN

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

OPEN dep_det_c(1010);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

-->-- opening same cursor with different input value

OPEN dep_det_c(1020);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||


' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

END;

/*sample output*/

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 1 Department Name : Admin

Department id : 2 Department Name : HR

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 3 Department Name : Sales

Department id : 4 Department Name : Marketing

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Handling Exception
Error Handling in oracle

ERROR

Any departure from the expected behavior of the system or program,

which stops the working of the system is an error.

Types : compile time error

Run time error

EXCEPTION

Any error or problem which one can handle and continue to work normally.

Handling Exception

When exception is raised, control passes to the exception section of the block.

i.e. EXCEPTION

WHEN name_of_exception THEN

Types : Pre Defined Exceptions

User Defined Exceptions

Predefined Exception

*********************
Oracle has predefined several exceptions that correspond to the most common oracle errors.

------------------------------------------------------------------------

Exception Oracle Error SQL Code Value

------------------------------------------------------------------------

ZERO_DIVIDE ORA-01476 -1476

NO_DATA_FOUND ORA-01403 +100

DUP_VAL_ON_INDEX ORA-00001 -1

TOO_MANY_ROWS ORA-01422 -1422

VALUE_ERROR ORA-06502 -6502

CURSOR_ALREADY_OPEN ORA-06511 -6511

OTHERS

------------------------------------------------------------------------

-->-- ZERO_DIVIDE --<--

Your program attempts to divide a number by zero.

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION
WHEN ZERO_DIVIDE THEN

dbms_output.put_line('Divisor is equal to zero');

END;

-->-- NO_DATA_FOUND --<--

Single row SELECT returned no rows or your program referenced a deleted element in a nested
table

or an uninitialized element in an associative array (index-by table).

CREATE TABLE test_tb(id NUMBER PRIMARY KEY);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN NO_DATA_FOUND THEN

dbms_output.put_line('There is no data inside the table');

END;

-->-- DUP_VAL_ON_INDEX --<--


A program attempted to insert duplicate values in a column that is constrained by a unique
index.

INSERT INTO test_tb VALUES (1);

INSERT INTO test_tb VALUES (2);

commit;

BEGIN

INSERT INTO test_tb VALUES (2);

EXCEPTION

WHEN DUP_VAL_ON_INDEX THEN

dbms_output.put_line('Duplicate values are not allowed');

END;

-->-- TOO_MANY_ROWS --<--

Single row SELECT returned multiple rows.

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION
WHEN TOO_MANY_ROWS THEN

dbms_output.put_line('Query returning more than one row');

END;

DROP TABLE test_tb;

-->-- VALUE_ERROR --<--

An arithmetic, conversion, truncation, or size constraint error occurred.

DECLARE

num1 NUMBER(2);

BEGIN

num1 := 345;

EXCEPTION

WHEN VALUE_ERROR THEN

dbms_output.put_line('check the size of the variable');

END;

-->-- CURSOR_ALREADY_OPEN --<--

A program attempted to open an already opened cursor.


CREATE TABLE emp(id NUMBER, name VARCHAR2(30));

BEGIN

INSERT INTO emp VALUES(1,'Name1');

INSERT INTO emp VALUES(2,'Name2');

INSERT INTO emp VALUES(3,'Name3');

INSERT INTO emp VALUES(4,'Name4');

COMMIT;

END;

SELECT * FROM emp;

DECLARE

cursor emp_c IS

SELECT * FROM emp;

all_data emp%ROWTYPE;

BEGIN

OPEN emp_c;

OPEN emp_c;

NULL;

CLOSE emp_c;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN


dbms_output.put_line('Cursor already opened');

END;

DROP TABLE emp;

-->-- OTHERS --<--

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

WHEN OTHERS THEN

dbms_output.put_line('Some other error ' || SQLERRM);

END;

User Defined Exception

**********************

A user-defined exception is an error that is defined by the programmer.


User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,

exceptions have a type EXCEPTION and scope.

DECLARE

v_gender CHAR := '&gender';

gender_ex EXCEPTION;

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE gender_ex;

END IF;

dbms_output.put_line('Gender : '||v_gender);

EXCEPTION

WHEN gender_ex THEN

dbms_output.put_line('Please Enter valid gender');

END;

create table test_insert (id NUMBER, Name VARCHAR2(30));

DECLARE

abort_ex EXCEPTION;

BEGIN

FOR i IN 1..100

LOOP
BEGIN

IF mod(i,10)=0 THEN

RAISE abort_ex;

END IF;

INSERT INTO test_insert VALUES(i, 'Name'||i);

EXCEPTION

WHEN abort_ex THEN

NULL;

END;

END LOOP;

COMMIT;

END;

SELECT * FROM test_insert;

DROP TABLE test_insert;

SQLERRM and SQLCODE

********************

SQLCODE returns the current error code, and SQLERRM returns the current error message
text;

For user-defined exception SQLCODE returns 1 and SQLERRM returns “user-defined


exception”.

SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.
CREATE TABLE test_tb (id NUMBER);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

dbms_output.put_line(v_id);

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('SQLERRM : ' || SQLERRM);

dbms_output.put_line('SQLCODE : ' || SQLCODE);

END;

/*sample output*/

SQLERRM : ORA-01403: no data found

SQLCODE : 100

DROP TABLE test_tb;

PRAGMA EXCEPTION_INIT

*********************
Using this you can associate a named exception with a particular oracle error.

This gives you the ability to trap this error specifically, rather than via an OTHERS handler.

Syntax:

PRAGMA EXCEPTION_INIT(exception_name, oracle_error_number);

DECLARE

v_result NUMBER;

PRAGMA EXCEPTION_INIT(Invalid, -1476);

BEGIN

SELECT 453 / 0 INTO v_result FROM dual;

dbms_output.put_line('Result : ' || v_result);

EXCEPTION

WHEN INVALID THEN

dbms_output.put_line('Invalid Exception');

END;

RAISE_APPLICATION_ERROR

************************
You can use this built-in function to create your own error messages, which can be more
descriptive than named exceptions.

Error Number :

Oracle Error Range : From -00000 to -19999

User Error Range : From -20000 to -20999

DECLARE

v_gender CHAR := '&gender';

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE_APPLICATION_ERROR(-20003, 'Enter valid gender');

END IF;

dbms_output.put_line('Gender : ' || v_gender);

END;

Posted 21st October 2014 by Unknown

1 View comments

Loading
Dynamic Views theme. Powered by Blogger.

Oracle sql & Pl/sql

search

Home Sql and pl/sql Sql Interview Questions

JUL

20

INLINE view in Oracle with 12c New Features

Named sub Query in FROM clause is call it as INLINE VIEW.

Oracle process a inline view faster than sub query

Inline View in Oracle

--Query to display all the employees who are all getting salary more than their department
average salary

SELECT First_name

, last_name

, salary

, department_id

FROM employees a , ( SELECT b.department_id

, AVG(b.salary) avg_sal

FROM employees b

GROUP BY b.department_id
)b

WHERE a.department_id = b.department_id

AND a.salary > b.avg_salary;

Display all the customer who have placed more number of orders by using INLINE view

CREATE TABLE customer_order_det_tb

( custm_id NUMBER ,

custm_nm VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

ttl_amt NUMBER(7,2)

);

BEGIN

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '11-Jul-15' , 45000.00);

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '14-Jul-15' , 27000.00);

INSERT INTO customer_order_det_tb VALUES(101, 'Raja' , '13-Jul-15' , 17000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 34000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 38000.00);

COMMIT;

END;

SELECT c.*
FROM customer_order_det_tb c;

--------------------------------------------

custm_id custm_nm order_dt ttl_amt

--------------------------------------------

100 Murugappan 7/11/2015 45000.00

100 Murugappan 7/14/2015 27000.00

101 Raja 7/13/2015 17000.00

102 Ramesh 7/15/2015 34000.00

102 Ramesh 7/15/2015 38000.00

--------------------------------------------

--Writing a Quer to display all the customer who have placed maximum number of order

--Query #1 for inline view

SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC;

--------------------------------

custm_id custm_nm total_odr

--------------------------------

100 Murugappan 2
102 Ramesh 2

101 Raja 1

--------------------------------

--Query #2 for inline view

SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm;

----------

total_odr

----------

----------

Inline view to find all the customers who have placed maximum number of orders

/****************************************

Syntax

SELECT * FROM <query1> x, <query2> y

WHERE contition;

****************************************/
SELECT query1.* FROM

( SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC

) query1,

( SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm

) query2

WHERE query1.total_odr = query2.total_odr;

-------------------------------

custm_id custm_nm total_odr

-------------------------------

100 Murugappan 2

102 Ramesh 2

-------------------------------

DROP TABLE customer_order_det_tb;

--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT

SELECT first_name, salary


FROM ( SELECT first_name, salary

FROM employees e

WHERE job_id NOT IN ('SALESMAN','PRESIDENT')

ORDER BY salary DESC

WHERE ROWNUM < 4;

New Oracle 12c Inline view Syntax

LATERAL clause for In-line views

Allows for columns in the inline view to be accessed!!

Example :

--in 11g

SELECT * FROM employees e, (

SELECT *

FROM departments d

WHERE e.department_id = d.department_id);

ORA-0090: "E"."DEPARTMENT_ID": Invalid Identifier


--in 12c

SELECT * FROM employees e, LATERAL(

SELECT *

FROM departments d

WHERE e.department_id = d.department_id

);

--in 11g

WITH t

AS

( SELECT LEVEL a

FROM dual

CONNECT BY LEVEL <= 30)

SELECT *

FROM t, (SELECT *

FROM employees

WHERE department_id = t.a

);

ORA-00904: "T"."A": invalid Identifier

--in 12c

WITH t

AS
(SELECT LEVEL a FROM dual CONNECT BY LEVEL <= 30)

SELECT * FROM t,

LATERAL(SELECT *

FROM employees

WHERE department_id = t.a);

Hope you have enjoyed this little article

Feed backs are always Welcome :) (:

Posted 20th July 2015 by Unknown

0 Add a comment

JAN

23

Salary Related Questions in Oracle

--creating table

CREATE TABLE employee_data

eid NUMBER(4),
ename VARCHAR2(30),

depno NUMBER(3),

salary NUMBER(8)

);

BEGIN

--Inserting records

INSERT INTO employee_data VALUES(1000,'Name01',90,30000);

INSERT INTO employee_data VALUES(1001,'Name02',90,6000);

INSERT INTO employee_data VALUES(1002,'Name03',90,23000);

INSERT INTO employee_data VALUES(1003,'Name04',60,35000);

INSERT INTO employee_data VALUES(1004,'Name05',60,60000);

INSERT INTO employee_data VALUES(1005,'Name06',60,30000);

INSERT INTO employee_data VALUES(1006,'Name07',80,36000);

INSERT INTO employee_data VALUES(1007,'Name08',80,29000);

INSERT INTO employee_data VALUES(1008,'Name09',80,37000);

INSERT INTO employee_data VALUES(1009,'Name10',80,41000);

COMMIT;

END;

SELECT * FROM employee_data


ORDER BY salary DESC;

--query to find maximum salary from employee_data table

SELECT MAX(salary) FROM employee_data;

--query to find minimum salary from employee_data table

SELECT MIN(salary) FROM employee_data;

--query to find second maximum salary from employee_data table

SELECT MAX(salary)

FROM employee_data

WHERE salary NOT IN (SELECT MAX(salary)

FROM employee_data);

--query to select 5th maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= 5);


--query to select nth maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= &n);

--query to select all the details of the employee whose getting nth maximum salary

SELECT *

FROM (SELECT emp.*,

rownum rn

FROM (SELECT *

FROM employee_data

ORDER BY salary DESC) emp)

WHERE rn = 9;

--same query using row_numbr( ) function

SELECT *
FROM (SELECT emp.*,

row_number() over(ORDER BY salary) rank

FROM employee_data emp)

WHERE rank = 9;

--same query using rank( ) function

SELECT *

FROM (SELECT emp.*,

rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--same query using dense_rank( ) function

SELECT *

FROM (SELECT emp.*,

dense_rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--query to display display maximum salary in all the department

SELECT e.depno "Department id",


MAX(salary) "Maximum Salary"

FROM employee_data e

GROUP BY e.depno;

--query to display all the employees who are all getting salary more than average salary of the
company

SELECT e.* FROM employee_data e

WHERE salary > (SELECT AVG(salary) FROM employee_data);

--query to display all the employees who are all getting salary more than their department
average salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE department_id = OUT.department_id);

--query to display all the employees who are all getting salary more than their manager salary

SELECT employee_id,
first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE employee_id = OUT.manager_id);

Documented By : Murugappan Annamalai

Posted on : 23-Jan-15 16:34:00 IST.

Hope you have enjoyed this little article

Feed backs are always welcome :)

Posted 23rd January 2015 by Unknown

7 View comments

JAN

22

Why prefer COALESCE over NVL

Documented By : Nimish Garg


I prefer using "COALESCE" over "NVL" is some of the scenarios. Last week One of my friend
asked me what is the advantage of using "COALESCE" where we can simply use "NVL". I simply
gave him the reply from Oracle Docs i.e. NVL lets you replace null (returned as a blank) with a
string in the results of a query and COALESCE returns the first non-null expr in the expression list.
Oracle Database uses short-circuit evaluation with "COALESCE".

He replied that he knows the difference, he knows that "COALESCE" can take multiple arguments
and so on. He was more interested in understanding "short-circuit evaluation" of "COALESCE"
and the scenarios where I prefer using "COALESCE" over "NVL".

To make him understand I created following function which takes One second in every execution
and simply returns '--null--' and executed 2 very similar queries one with NVL and other with
COALESCE.

SQL> create or replace function f_null return varchar2

2 is

3 begin

4 dbms_lock.sleep(1);

5 return '--null--';

6 end;

7 /

Function created.

Following are the queries which I used to demonstrate that NVL evaluates both arguments even
if the second argument is not used and COALESCE uses short-circuit evaluation i.e. it only
evaluates the arguments only if they are needed.
SQL> select e.empno, e.ename ename, nvl(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.
Elapsed: 00:00:14.01

SQL> select e.empno, e.ename ename, coalesce(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.
Elapsed: 00:00:01.01

Here we can see easily that the first query with NVL took 14+ seconds, one second for each
record even if the "f_null" value was used only in one record. On the contrary as mentioned in
Oracle Documentation "COALESCE" uses its "short-circuit evaluation" and "f_null" was called
only once and so second query took only One Second. "COALESCE" is certainly use less resources
than NVL.

Posted 22nd January 2015 by Unknown

0 Add a comment

DEC

21

Constraints

It Enforce Rule On Table

We can create constraint at the time of Creating Table

1. Column Level Declaration

2. Table Level Declaration


1. We can provide own name.

Format : [part_of_project_name-table_name-column_name-constraint_type]

Example : gmind_emp_id_pk _uk _ck _f

2. system name name

Format : sys_cn

Example : SYS_C405323

We can create constraint after the table has been created

Types

Primary Key

Not allowed Null value

Not allowed you to enter duplicate value

Ex : Employee_id, Student_id

Unique Key
allowed Null value

Not allowed you to enter duplicate value

Ex : Contact_no, email

Foreign Key

It will allowed you to enter NULL and Duplicate value.

c1(pk) : 1 2 3

c2(f) : 1 1 2 3 4 Not allowed

Allowed you to enter duplicate value and null value

Not Null

It will not allowed you to enter null value

Check

You can check your own condition

Simple Table for understanding


------------------------------------

Duplicate NULL

------------------------------------

Primary Key X X

Unique Key X Allowed

Foreign Key Allowed Allowed

------------------------------------

creating table with all constraint type

Create table my_stu_details

S_id Number(2),

S_name Varchar2(30) Not Null, --SYS_Cn

s_mail Varchar2(30),

s_gender char(1),

s_did Number(3),

Constraint my_stu_sid_pk PRIMARY KEY (s_id),

constraint my_stu_mail_uk UNIQUE (s_mail) ,

Constraint my_stu_gen_ck CHECK (s_gender IN ('M', 'F', 'm', 'f')),

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

);
DESC my_stu_details;

------------------------------------

Name Type Nullable

------------------------------------

S_ID NUMBER(2)

S_NAME VARCHAR2(30)

S_MAIL VARCHAR2(30) Y

S_GENDER CHAR(1) Y

S_DID NUMBER(3) Y

------------------------------------

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name1' , 'name1@gmail.com' , 'm' , 60 );

Select * from my_stu_details;

Validating Primary Key


Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-00001: unique constraint (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (NULL, 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-01400: cannot insert NULL into (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (2 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

Validating NOT NULL Constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , NULL , 'name3@gmail.com' , 'F' , 80 );

ORA-01400: cannot insert NULL into ("HR"."MY_STU_DETAILS"."S_NAME")


Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , 'Name3' , 'name3@gmail.com' , 'F' , 80 );

Select * from my_stu_details;

Validating Unique Key Constraint

--Duplicate Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , 'name3@gmail.com' , 'F' , 80 );

ORA-00001: unique constraint (HR.MY_STU_MAIL_UK) violated

--Null Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , null , 'M' , 70 );


Select * from my_stu_details;

Validating Check constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'j' , 70 );

ORA-02290: check constraint (HR.MY_STU_GEN_CK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'M' , 70 );

Select * from my_stu_details;

Validating Foreign Key

Select * from Departments;


Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 3 );

ORA-02291: integrity constraint (HR.MY_STU_DID_FK) violated - parent key not found

Departments table : parent table

my_stu_details : Child table

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

--------------------------------------------------------

s_id s_name s_mail s_gender s_did

--------------------------------------------------------

1 name1 name1@gmail.com m 60

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 M 70

5 Name5 name5@gmail.com M 70
6 Name6 name6@gmail.com F 90

--------------------------------------------------------

Deleting the Primary key value which is referred by Foreign Key

Select * from Departments;

DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID

------------------------------------------------------------

60 IT 103 1400 <---- Delete

-- don't execute this query

--Delete From Departments

--Where Department_id = 60;

1) ON DELETE SET NULL

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------
6 Name6 name6@gmail.com F 90

1 name1 name1@gmail.com m -

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

2) ON DELETE SET CASCADE

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

Syntax

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE CASCADE
Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE SET NULL

Constraint Related Data Dictionary Table information.

To view constraint Information

SELECT c.owner,

c.constraint_name,

c.constraint_type,

c.table_name,

c.r_constraint_name,

c.status

FROM user_constraints c

WHERE c.table_name = 'MY_STU_DETAILS';

------------------------------------------------------------------------------------

owner constraint_name constraint_type table_name r_constraint_name status

------------------------------------------------------------------------------------

HR SYS_C004023 C MY_STU_DETAILS ENABLED

HR MY_STU_GEN_CK C MY_STU_DETAILS ENABLED

HR MY_STU_SID_PK P MY_STU_DETAILS ENABLED


HR MY_STU_MAIL_UK U MY_STU_DETAILS ENABLED

HR MY_STU_DID_FK R MY_STU_DETAILS DEPT_ID_PK ENABLED

------------------------------------------------------------------------------------

To view constraint name with corresponding column name

SELECT * FROM user_cons_columns c

WHERE c.table_name = 'MY_STU_DETAILS';

-------------------------------------------------------------

owner constraint_name table_name column_name position

-------------------------------------------------------------

HR MY_STU_MAIL_UK MY_STU_DETAILS S_MAIL 1

HR MY_STU_SID_PK MY_STU_DETAILS S_ID 1

HR MY_STU_GEN_CK MY_STU_DETAILS S_GENDER

HR SYS_C004023 MY_STU_DETAILS S_NAME

HR MY_STU_DID_FK MY_STU_DETAILS S_DID 1

-------------------------------------------------------------

Creating Composite Primary Key


Creating Primary Key with more than one number of column

ALTER TABLE table_name

ADD CONSTRAINT constraint_name PRIMARY KEY(column1, column_2 , column3);

In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.

creating constraint after the table creation

ALTER TABLE table_name

ADD CONSTRAINT constraint_name CONSTRAINT_TYPE(column_name);

ALTER TABLE table_name

DROP CONSTRAINT constraint_name;

ALTER TABLE table_name

DROP PRIMARY KEY;

To drop related foreign key

ALTER TABLE table_name


DROP PRIMARY KEY CASCADE;

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name;

Disable constraint with related foreign key constraint

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name CASCADE;

ALTER TABLE table_name

ENABLE CONSTRAINT constraint_name;

Interview Questions

What are all the type of constraint available in oracle?

Difference between PRIMARY KEY and UNIQUE key.

Difference between PRIMARY KEY ans FOREIGN KEY.

Difference between UNIQUE key and FOREIGN KEY.

Is it possible to create tow primary key in single table.


Write a syntax to create FOREIGN constraint.

How to create constraint after the table has been created?

How to enable and disable a constraint.

Which data dictionary table contains information about constraints?

Which Data Dictionary table contains information about constraint with corresponding column
name?

What is composite primary key?

Explain ON DELETE CASCADE and ON DELETE SET NULL option.

~Thanks For Reading~

Post your valuable feedback below

Posted 21st December 2014 by Unknown

1 View comments

UnknownMay 22, 2017 at 12:39 AM

good

Reply

DEC
4

listagg in Oracle 11g

Oracle 11gR2 listagg built-in function allows for many table columns to be displayed within a
single row, a non-first-normal form display

Syntax :

listagg(column_value,'delimiter') WITHIN GROUP(ORDER BY column_name)

--Example 1:

CREATE TABLE test_ins(empid NUMBER,product VARCHAR2(30));

BEGIN

INSERT INTO test_ins VALUES( 101,'pendrive');

INSERT INTO test_ins VALUES( 102,'toy');

INSERT INTO test_ins VALUES( 101,'ipod');

INSERT INTO test_ins VALUES( 102,'hat');

INSERT INTO test_ins VALUES( 103,'cpu');

INSERT INTO test_ins VALUES( 104,'pen');

INSERT INTO test_ins VALUES( 104,'car');

INSERT INTO test_ins VALUES( 104,'mat');

INSERT INTO test_ins VALUES( 105,'tv');

INSERT INTO test_ins VALUES( 106,'laptop');


commit;

END;

SELECT * FROM test_ins;

SELECT empid "Employee",

listagg(product,

',') within

GROUP (ORDER BY empid) "Products"

FROM test_ins

GROUP BY empid;

-->-- Result set --<--


DROP TABLE test_ins;

-->-- Example 2

select department_id "Department id", listagg(first_name,', ') WITHIN GROUP(ORDER BY


employee_id) "Employees"

FROM employees

WHERE department_id IN (10,20,30,60)

GROUP BY department_id;

-->-- Result set --<--

Posted 4th December 2014 by Unknown

0 Add a comment

NOV

Condition and Looping Statement


IF

IF ELSE

Multiple IF ELSE

LOOP

FOR LOOP

WHILE LOOP

create table test_udt(id NUMBER, salary NUMBER);

BEGIN

INSERT INTO test_udt VALUES(001,23000);

INSERT INTO test_udt VALUES(002,43000);

INSERT INTO test_udt VALUES(003,78000);

INSERT INTO test_udt VALUES(004,25000);

INSERT INTO test_udt VALUES(005,26000);

INSERT INTO test_udt VALUES(006,90000);

Commit;

END;

select * from test_udt;


IF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 1;

IF v_salary > 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

END IF;

commit;

END;

IF ELSE

DECLARE
v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

ELSE

UPDATE test_udt t

SET t.salary = v_salary+20007

WHERE t.id = v_id ;

END IF;

commit;

END;

--same example with less number of lines

DECLARE
v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

v_salary := v_salary+10005;

ELSE

v_salary := v_salary+20007;

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

Multiple IF ELSIF
DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 3;

IF v_id = 1 THEN

v_salary := 1000;

dbms_output.put_line('1 inside');

ELSIF v_id = 2 THEN

v_salary := 2000;

dbms_output.put_line('2 inside');

ELSIF v_id = 3 THEN

v_salary := 3000;

dbms_output.put_line('3 inside');

ELSIF v_id = 4 THEN

v_salary := 4000;

dbms_output.put_line('4 inside');

END IF;

UPDATE test_udt t
SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

LOOP

--syntax

LOOP

--statements

--increment

--exit statement

END LOOP;

CREATE TABLE prod_details (pid VARCHAR2(3), pname VARCHAR2(30));

DECLARE

i NUMBER := 1;

x VARCHAR2(3);
BEGIN

LOOP

x := lpad(i,3,'0');

dbms_output.put_line('x value : '|| x);

INSERT INTO prod_details VALUES(i, 'Product '||i);

EXIT WHEN i >900;

i := i+1;

IF MOD(i,100) = 0 THEN

commit;

dbms_output.put_line('commit executed');

END IF;

END LOOP;

END;

SELECT * FROM prod_details ORDER BY 1;

DROP TABLE prod_details;

FOR LOOP

BEGIN

FOR I in 1..5

LOOP
Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

FOR LOOP - Reverse

BEGIN

FOR I in REVERSE 14..50

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

WHILE LOOP

DECLARE

i_val NUMBER:=0;

BEGIN

WHILE (i_val < 11)

LOOP

dbms_output.put_line('The value of I is '||i_val);

i_val := i_val + 1;

END LOOP;
END;

sample output:

The value of I is 0

The value of I is 1

The value of I is 2

The value of I is 3

The value of I is 4

The value of I is 5

The value of I is 6

The value of I is 7

The value of I is 8

The value of I is 9

The value of I is 10

Posted 8th November 2014 by Unknown

0 Add a comment

OCT

21
Bulk Collect

This is used for array fetches

With this you can retrieve multiple rows of data with a single round trip.

This reduces the number of context switches between the pl/sql and sql engines.

You can use bulk collect in both dynamic and static sql.

You can use bulk collect in select, fetch into and returning into clauses.

SQL engine automatically initializes and extends the collections you reference in the bulk
collect clause.

You can fetch into multiple collections with one column each.

You can use the limit clause of bulk collect to restrict the no of rows retrieved.

SELECT * FROM product_details;

-->-- Bulk collect in FETCH INTO --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;
FETCH proddt_cur BULK COLLECT

INTO dta;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Bulk collect in SELECT clause --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

BEGIN

SELECT * BULK COLLECT INTO dta FROM product_details;

FOR i IN dta.FIRST .. dta.LAST LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;
-->-- LIMIT in Bulk collect --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta LIMIT 30;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Multiple fetches in INTO clause --<--

SELECT * FROM product_details;


DECLARE

TYPE alldata_typ1 IS TABLE OF product_details.p_id%TYPE;

TYPE alldata_typ2 IS TABLE OF product_details.p_name%TYPE;

dta1 alldata_typ1;

dta2 alldata_typ2;

CURSOR proddt_cur IS

SELECT p_id, p_name FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta1, dta2;

CLOSE proddt_cur;

FOR i IN dta1.FIRST .. dta1.COUNT LOOP

dbms_output.put_line('Department Id : ' || dta1(i));

END LOOP;

FOR i IN dta2.FIRST .. dta2.COUNT LOOP

dbms_output.put_line('Department Name : ' || dta2(i));

END LOOP;

END;

/
DROP TABLE dep_details;

DROP TABLE product_details;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Ref Cursor

This is unconstrained cursor which will return different types depends upon the user input.

Ref cursors cannot be closed implicitly.

Ref cursor with return type is called strong cursor.

Ref cursor without return type is called weak cursor.

You can declare ref cursor type in package spec as well as body.

You can declare ref cursor types in local subprograms or anonymous blocks.

CREATE OR REPLACE PROCEDURE ref_c_sp(dep_det_c IN OUT SYS_REFCURSOR)

AS

BEGIN

OPEN dep_det_c

FOR
SELECT * FROM dep_details d;

END;

DECLARE

dep_det_c SYS_REFCURSOR;

tab_data dep_details%ROWTYPE;

BEGIN

ref_c_sp(dep_det_c);

LOOP

FETCH dep_det_c INTO tab_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department Name : '|| tab_data.d_name);

END LOOP;

CLOSE dep_det_c;

END;

/*sample output*/

Department Name : Admin

Department Name : HR

Department Name : Sales


Department Name : Marketing

DROP PROCEDURE ref_c_sp;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Cursor

SQL Private work Area where the query get passed and executed.

Types

******

Implicit(SQL)

Explicit

-->-- advanced cursor types --<--

Parametrized Cursor

Ref Cursor
Implicit

********

ORACLE implicitly opens a cursor to process each SQL statement not associated with an
explicitly declared cursor.

PL/SQL lets you refer to the most recent implicit cursor as the SQL” cursor. So, although you
cannot use the OPEN,

FETCH, and CLOSE statements to control an implicit cursor, you can still use cursor attributes to
access information

about the most recently executed SQL statement.

Cursor Stages

**************

OPEN cursor_name

FETCH (with in loop)

CLOSE cursor_name

Explicit

The set of rows returned by a query can consist of zero, one, or multiple rows,

depending on how many rows meet your search criteria. When a query returns multiple rows,

you can explicitly define a cursor to process the rows. You use three commands to control the
cursor

Cursor Attributes
*****************

%FOUND

%NOTFOUND

%ISOPEN

%ROWCOUNT

%BULK_ROWCOUNT --<-- used to handle error while using bulk collection.

%BULK_EXCEPTIONS --<-- used to handle error while using bulk collection.

Cursor Declaration

DECLARE

CURSOR <cursor_name>

IS

<SELECT statement>

BEGIN

--> some stmt

END;

Cursor Loop

Loop

While Loop

For Loop

Cursor Clauses
Return

For update

Where current of

Bulk collect

-->-- creating table

create table product_details

p_id NUMBER,

p_name VARCHAR2(30),

p_order_dt DATE

);

-->-- Inserting data

BEGIN

FOR i IN 1 .. 75 LOOP

INSERT INTO product_details VALUES (i, 'prod_name_' || i, SYSDATE + i);

END LOOP;

commit;

END;
-->-- selecting data

SELECT * FROM product_details;

---------------------------------------------

p_id p_name p_order_dt

---------------------------------------------

1 prod_name_1 10/11/2014 3:48:32 PM

2 prod_name_2 10/12/2014 3:48:32 PM

3 prod_name_3 10/13/2014 3:48:32 PM

4 prod_name_4 10/14/2014 3:48:32 PM

5 prod_name_5 10/15/2014 3:48:32 PM

6 prod_name_6 10/16/2014 3:48:32 PM

7 prod_name_7 10/17/2014 3:48:32 PM

8 prod_name_8 10/18/2014 3:48:32 PM

9 prod_name_9 10/19/2014 3:48:32 PM

10 prod_name_10 10/20/2014 3:48:32 PM

11 prod_name_11 10/21/2014 3:48:32 PM

12 prod_name_12 10/22/2014 3:48:32 PM

13 prod_name_13 10/23/2014 3:48:32 PM

14 prod_name_14 10/24/2014 3:48:32 PM

15 prod_name_15 10/25/2014 3:48:32 PM

16 prod_name_16 10/26/2014 3:48:32 PM

17 prod_name_17 10/27/2014 3:48:32 PM


18 prod_name_18 10/28/2014 3:48:32 PM

19 prod_name_19 10/29/2014 3:48:32 PM

20 prod_name_20 10/30/2014 3:48:32 PM

---------------------------------------------

----------------------------------------------

Implicit Cursor

----------------------------------------------

--will update soon

----------------------------------------------

Explicit Cursor

----------------------------------------------

**********************************************

Processing cursor data by using LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details


WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND; --<-- if next record not found means control will
come out from the loop

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

DECLARE
all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

EXIT WHEN prod_detail_cur%FOUND; --<-- if next record found means control will come
out from the loop

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )


DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;
END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor Already closed

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur
INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

-->-- CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )


prod_detail_cur cursor closed

**********************************************

Processing cursor data by using WHILE LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

OPEN prod_detail_cur;

FETCH prod_detail_cur

INTO all_data;

WHILE prod_detail_cur%FOUND LOOP

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

FETCH prod_detail_cur
INTO all_data;

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

************************************************************

Processing cursor data by using FOR LOOP - CURSOR FOR LOOP

************************************************************

DECLARE

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

FOR i IN prod_detail_cur

LOOP
dbms_output.put_line('Product id : ' || i.p_id ||

' Product Name : ' || i.p_name ||

' ( Orderd on : ' || TRIM(i.p_order_dt) || ' )');

END LOOP;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

Parameterized Cursor

*********************

This was used when you are going to use the cursor in more than one place with different
values for the same where clause.

Cursor parameters must be in mode.

Cursor parameters may have default values.

The scope of cursor parameter is within the select statement.


CREATE TABLE dep_details(d_id NUMBER,d_name VARCHAR2(30), location_id NUMBER);

BEGIN

INSRT INTO dep_details VALUES(001,'Admin',1010);

INSRT INTO dep_details VALUES(002,'HR',1010);

INSRT INTO dep_details VALUES(003,'Sales',1020);

INSRT INTO dep_details VALUES(004,'Marketing',1020);

commit;

END;

SELECT * FROM dep_details;

----------------------------

d_id d_name location_id

----------------------------

1 Admin 1010

2 HR 1010

3 Sales 1020

4 Marketing 1020

----------------------------

DECLARE
-->--Declaring parameterized cursor

CURSOR dep_det_c(p_location_id NUMBER) IS

SELECT * FROM dep_details d WHERE d.location_id = p_location_id;

all_data dep_details%ROWTYPE;

BEGIN

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

OPEN dep_det_c(1010);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

-->-- opening same cursor with different input value

OPEN dep_det_c(1020);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;


dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

END;

/*sample output*/

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 1 Department Name : Admin

Department id : 2 Department Name : HR

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 3 Department Name : Sales

Department id : 4 Department Name : Marketing

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21
Handling Exception

Error Handling in oracle

ERROR

Any departure from the expected behavior of the system or program,

which stops the working of the system is an error.

Types : compile time error

Run time error

EXCEPTION

Any error or problem which one can handle and continue to work normally.

Handling Exception

When exception is raised, control passes to the exception section of the block.

i.e. EXCEPTION

WHEN name_of_exception THEN

Types : Pre Defined Exceptions

User Defined Exceptions

Predefined Exception
*********************

Oracle has predefined several exceptions that correspond to the most common oracle errors.

------------------------------------------------------------------------

Exception Oracle Error SQL Code Value

------------------------------------------------------------------------

ZERO_DIVIDE ORA-01476 -1476

NO_DATA_FOUND ORA-01403 +100

DUP_VAL_ON_INDEX ORA-00001 -1

TOO_MANY_ROWS ORA-01422 -1422

VALUE_ERROR ORA-06502 -6502

CURSOR_ALREADY_OPEN ORA-06511 -6511

OTHERS

------------------------------------------------------------------------

-->-- ZERO_DIVIDE --<--

Your program attempts to divide a number by zero.

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;


EXCEPTION

WHEN ZERO_DIVIDE THEN

dbms_output.put_line('Divisor is equal to zero');

END;

-->-- NO_DATA_FOUND --<--

Single row SELECT returned no rows or your program referenced a deleted element in a nested
table

or an uninitialized element in an associative array (index-by table).

CREATE TABLE test_tb(id NUMBER PRIMARY KEY);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN NO_DATA_FOUND THEN

dbms_output.put_line('There is no data inside the table');

END;

-->-- DUP_VAL_ON_INDEX --<--


A program attempted to insert duplicate values in a column that is constrained by a unique
index.

INSERT INTO test_tb VALUES (1);

INSERT INTO test_tb VALUES (2);

commit;

BEGIN

INSERT INTO test_tb VALUES (2);

EXCEPTION

WHEN DUP_VAL_ON_INDEX THEN

dbms_output.put_line('Duplicate values are not allowed');

END;

-->-- TOO_MANY_ROWS --<--

Single row SELECT returned multiple rows.

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;


EXCEPTION

WHEN TOO_MANY_ROWS THEN

dbms_output.put_line('Query returning more than one row');

END;

DROP TABLE test_tb;

-->-- VALUE_ERROR --<--

An arithmetic, conversion, truncation, or size constraint error occurred.

DECLARE

num1 NUMBER(2);

BEGIN

num1 := 345;

EXCEPTION

WHEN VALUE_ERROR THEN

dbms_output.put_line('check the size of the variable');

END;

-->-- CURSOR_ALREADY_OPEN --<--

A program attempted to open an already opened cursor.


CREATE TABLE emp(id NUMBER, name VARCHAR2(30));

BEGIN

INSERT INTO emp VALUES(1,'Name1');

INSERT INTO emp VALUES(2,'Name2');

INSERT INTO emp VALUES(3,'Name3');

INSERT INTO emp VALUES(4,'Name4');

COMMIT;

END;

SELECT * FROM emp;

DECLARE

cursor emp_c IS

SELECT * FROM emp;

all_data emp%ROWTYPE;

BEGIN

OPEN emp_c;

OPEN emp_c;

NULL;

CLOSE emp_c;

EXCEPTION
WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

END;

DROP TABLE emp;

-->-- OTHERS --<--

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

WHEN OTHERS THEN

dbms_output.put_line('Some other error ' || SQLERRM);

END;

User Defined Exception

**********************
A user-defined exception is an error that is defined by the programmer.

User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,

exceptions have a type EXCEPTION and scope.

DECLARE

v_gender CHAR := '&gender';

gender_ex EXCEPTION;

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE gender_ex;

END IF;

dbms_output.put_line('Gender : '||v_gender);

EXCEPTION

WHEN gender_ex THEN

dbms_output.put_line('Please Enter valid gender');

END;

create table test_insert (id NUMBER, Name VARCHAR2(30));

DECLARE

abort_ex EXCEPTION;

BEGIN

FOR i IN 1..100
LOOP

BEGIN

IF mod(i,10)=0 THEN

RAISE abort_ex;

END IF;

INSERT INTO test_insert VALUES(i, 'Name'||i);

EXCEPTION

WHEN abort_ex THEN

NULL;

END;

END LOOP;

COMMIT;

END;

SELECT * FROM test_insert;

DROP TABLE test_insert;

SQLERRM and SQLCODE

********************

SQLCODE returns the current error code, and SQLERRM returns the current error message
text;

For user-defined exception SQLCODE returns 1 and SQLERRM returns “user-defined


exception”.
SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.

CREATE TABLE test_tb (id NUMBER);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

dbms_output.put_line(v_id);

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('SQLERRM : ' || SQLERRM);

dbms_output.put_line('SQLCODE : ' || SQLCODE);

END;

/*sample output*/

SQLERRM : ORA-01403: no data found

SQLCODE : 100

DROP TABLE test_tb;

PRAGMA EXCEPTION_INIT
*********************

Using this you can associate a named exception with a particular oracle error.

This gives you the ability to trap this error specifically, rather than via an OTHERS handler.

Syntax:

PRAGMA EXCEPTION_INIT(exception_name, oracle_error_number);

DECLARE

v_result NUMBER;

PRAGMA EXCEPTION_INIT(Invalid, -1476);

BEGIN

SELECT 453 / 0 INTO v_result FROM dual;

dbms_output.put_line('Result : ' || v_result);

EXCEPTION

WHEN INVALID THEN

dbms_output.put_line('Invalid Exception');

END;

RAISE_APPLICATION_ERROR

************************
You can use this built-in function to create your own error messages, which can be more
descriptive than named exceptions.

Error Number :

Oracle Error Range : From -00000 to -19999

User Error Range : From -20000 to -20999

DECLARE

v_gender CHAR := '&gender';

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE_APPLICATION_ERROR(-20003, 'Enter valid gender');

END IF;

dbms_output.put_line('Gender : ' || v_gender);

END;

Posted 21st October 2014 by Unknown

1 View comments
Loading

Dynamic Views theme. Powered by Blogger.

Oracle sql & Pl/sql

search

Home Sql and pl/sql Sql Interview Questions

JUL

20

INLINE view in Oracle with 12c New Features

Named sub Query in FROM clause is call it as INLINE VIEW.

Oracle process a inline view faster than sub query

Inline View in Oracle

--Query to display all the employees who are all getting salary more than their department
average salary

SELECT First_name

, last_name

, salary

, department_id

FROM employees a , ( SELECT b.department_id

, AVG(b.salary) avg_sal

FROM employees b
GROUP BY b.department_id

)b

WHERE a.department_id = b.department_id

AND a.salary > b.avg_salary;

Display all the customer who have placed more number of orders by using INLINE view

CREATE TABLE customer_order_det_tb

( custm_id NUMBER ,

custm_nm VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

ttl_amt NUMBER(7,2)

);

BEGIN

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '11-Jul-15' , 45000.00);

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '14-Jul-15' , 27000.00);

INSERT INTO customer_order_det_tb VALUES(101, 'Raja' , '13-Jul-15' , 17000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 34000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 38000.00);

COMMIT;

END;
SELECT c.*

FROM customer_order_det_tb c;

--------------------------------------------

custm_id custm_nm order_dt ttl_amt

--------------------------------------------

100 Murugappan 7/11/2015 45000.00

100 Murugappan 7/14/2015 27000.00

101 Raja 7/13/2015 17000.00

102 Ramesh 7/15/2015 34000.00

102 Ramesh 7/15/2015 38000.00

--------------------------------------------

--Writing a Quer to display all the customer who have placed maximum number of order

--Query #1 for inline view

SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC;

--------------------------------

custm_id custm_nm total_odr

--------------------------------
100 Murugappan 2

102 Ramesh 2

101 Raja 1

--------------------------------

--Query #2 for inline view

SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm;

----------

total_odr

----------

----------

Inline view to find all the customers who have placed maximum number of orders

/****************************************

Syntax

SELECT * FROM <query1> x, <query2> y

WHERE contition;

****************************************/
SELECT query1.* FROM

( SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC

) query1,

( SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm

) query2

WHERE query1.total_odr = query2.total_odr;

-------------------------------

custm_id custm_nm total_odr

-------------------------------

100 Murugappan 2

102 Ramesh 2

-------------------------------

DROP TABLE customer_order_det_tb;

--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT
SELECT first_name, salary

FROM ( SELECT first_name, salary

FROM employees e

WHERE job_id NOT IN ('SALESMAN','PRESIDENT')

ORDER BY salary DESC

WHERE ROWNUM < 4;

New Oracle 12c Inline view Syntax

LATERAL clause for In-line views

Allows for columns in the inline view to be accessed!!

Example :

--in 11g

SELECT * FROM employees e, (

SELECT *

FROM departments d

WHERE e.department_id = d.department_id);

ORA-0090: "E"."DEPARTMENT_ID": Invalid Identifier


--in 12c

SELECT * FROM employees e, LATERAL(

SELECT *

FROM departments d

WHERE e.department_id = d.department_id

);

--in 11g

WITH t

AS

( SELECT LEVEL a

FROM dual

CONNECT BY LEVEL <= 30)

SELECT *

FROM t, (SELECT *

FROM employees

WHERE department_id = t.a

);

ORA-00904: "T"."A": invalid Identifier

--in 12c

WITH t
AS

(SELECT LEVEL a FROM dual CONNECT BY LEVEL <= 30)

SELECT * FROM t,

LATERAL(SELECT *

FROM employees

WHERE department_id = t.a);

Hope you have enjoyed this little article

Feed backs are always Welcome :) (:

Posted 20th July 2015 by Unknown

0 Add a comment

JAN

23

Salary Related Questions in Oracle

--creating table

CREATE TABLE employee_data

(
eid NUMBER(4),

ename VARCHAR2(30),

depno NUMBER(3),

salary NUMBER(8)

);

BEGIN

--Inserting records

INSERT INTO employee_data VALUES(1000,'Name01',90,30000);

INSERT INTO employee_data VALUES(1001,'Name02',90,6000);

INSERT INTO employee_data VALUES(1002,'Name03',90,23000);

INSERT INTO employee_data VALUES(1003,'Name04',60,35000);

INSERT INTO employee_data VALUES(1004,'Name05',60,60000);

INSERT INTO employee_data VALUES(1005,'Name06',60,30000);

INSERT INTO employee_data VALUES(1006,'Name07',80,36000);

INSERT INTO employee_data VALUES(1007,'Name08',80,29000);

INSERT INTO employee_data VALUES(1008,'Name09',80,37000);

INSERT INTO employee_data VALUES(1009,'Name10',80,41000);

COMMIT;

END;

/
SELECT * FROM employee_data

ORDER BY salary DESC;

--query to find maximum salary from employee_data table

SELECT MAX(salary) FROM employee_data;

--query to find minimum salary from employee_data table

SELECT MIN(salary) FROM employee_data;

--query to find second maximum salary from employee_data table

SELECT MAX(salary)

FROM employee_data

WHERE salary NOT IN (SELECT MAX(salary)

FROM employee_data);

--query to select 5th maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)


WHERE rownum <= 5);

--query to select nth maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= &n);

--query to select all the details of the employee whose getting nth maximum salary

SELECT *

FROM (SELECT emp.*,

rownum rn

FROM (SELECT *

FROM employee_data

ORDER BY salary DESC) emp)

WHERE rn = 9;

--same query using row_numbr( ) function


SELECT *

FROM (SELECT emp.*,

row_number() over(ORDER BY salary) rank

FROM employee_data emp)

WHERE rank = 9;

--same query using rank( ) function

SELECT *

FROM (SELECT emp.*,

rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--same query using dense_rank( ) function

SELECT *

FROM (SELECT emp.*,

dense_rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--query to display display maximum salary in all the department


SELECT e.depno "Department id",

MAX(salary) "Maximum Salary"

FROM employee_data e

GROUP BY e.depno;

--query to display all the employees who are all getting salary more than average salary of the
company

SELECT e.* FROM employee_data e

WHERE salary > (SELECT AVG(salary) FROM employee_data);

--query to display all the employees who are all getting salary more than their department
average salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE department_id = OUT.department_id);

--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE employee_id = OUT.manager_id);

Documented By : Murugappan Annamalai

Posted on : 23-Jan-15 16:34:00 IST.

Hope you have enjoyed this little article

Feed backs are always welcome :)

Posted 23rd January 2015 by Unknown

7 View comments

JAN

22

Why prefer COALESCE over NVL


Documented By : Nimish Garg

I prefer using "COALESCE" over "NVL" is some of the scenarios. Last week One of my friend
asked me what is the advantage of using "COALESCE" where we can simply use "NVL". I simply
gave him the reply from Oracle Docs i.e. NVL lets you replace null (returned as a blank) with a
string in the results of a query and COALESCE returns the first non-null expr in the expression list.
Oracle Database uses short-circuit evaluation with "COALESCE".

He replied that he knows the difference, he knows that "COALESCE" can take multiple arguments
and so on. He was more interested in understanding "short-circuit evaluation" of "COALESCE"
and the scenarios where I prefer using "COALESCE" over "NVL".

To make him understand I created following function which takes One second in every execution
and simply returns '--null--' and executed 2 very similar queries one with NVL and other with
COALESCE.

SQL> create or replace function f_null return varchar2

2 is

3 begin

4 dbms_lock.sleep(1);

5 return '--null--';

6 end;

7 /

Function created.

Following are the queries which I used to demonstrate that NVL evaluates both arguments even
if the second argument is not used and COALESCE uses short-circuit evaluation i.e. it only
evaluates the arguments only if they are needed.

SQL> select e.empno, e.ename ename, nvl(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.
Elapsed: 00:00:14.01

SQL> select e.empno, e.ename ename, coalesce(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.
Elapsed: 00:00:01.01

Here we can see easily that the first query with NVL took 14+ seconds, one second for each
record even if the "f_null" value was used only in one record. On the contrary as mentioned in
Oracle Documentation "COALESCE" uses its "short-circuit evaluation" and "f_null" was called
only once and so second query took only One Second. "COALESCE" is certainly use less resources
than NVL.

Posted 22nd January 2015 by Unknown

0 Add a comment

DEC

21

Constraints

It Enforce Rule On Table

We can create constraint at the time of Creating Table

1. Column Level Declaration

2. Table Level Declaration


1. We can provide own name.

Format : [part_of_project_name-table_name-column_name-constraint_type]

Example : gmind_emp_id_pk _uk _ck _f

2. system name name

Format : sys_cn

Example : SYS_C405323

We can create constraint after the table has been created

Types

Primary Key

Not allowed Null value

Not allowed you to enter duplicate value

Ex : Employee_id, Student_id

Unique Key
allowed Null value

Not allowed you to enter duplicate value

Ex : Contact_no, email

Foreign Key

It will allowed you to enter NULL and Duplicate value.

c1(pk) : 1 2 3

c2(f) : 1 1 2 3 4 Not allowed

Allowed you to enter duplicate value and null value

Not Null

It will not allowed you to enter null value

Check

You can check your own condition

Simple Table for understanding


------------------------------------

Duplicate NULL

------------------------------------

Primary Key X X

Unique Key X Allowed

Foreign Key Allowed Allowed

------------------------------------

creating table with all constraint type

Create table my_stu_details

S_id Number(2),

S_name Varchar2(30) Not Null, --SYS_Cn

s_mail Varchar2(30),

s_gender char(1),

s_did Number(3),

Constraint my_stu_sid_pk PRIMARY KEY (s_id),

constraint my_stu_mail_uk UNIQUE (s_mail) ,

Constraint my_stu_gen_ck CHECK (s_gender IN ('M', 'F', 'm', 'f')),

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

);
DESC my_stu_details;

------------------------------------

Name Type Nullable

------------------------------------

S_ID NUMBER(2)

S_NAME VARCHAR2(30)

S_MAIL VARCHAR2(30) Y

S_GENDER CHAR(1) Y

S_DID NUMBER(3) Y

------------------------------------

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name1' , 'name1@gmail.com' , 'm' , 60 );

Select * from my_stu_details;

Validating Primary Key


Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-00001: unique constraint (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (NULL, 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-01400: cannot insert NULL into (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (2 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

Validating NOT NULL Constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , NULL , 'name3@gmail.com' , 'F' , 80 );


ORA-01400: cannot insert NULL into ("HR"."MY_STU_DETAILS"."S_NAME")

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , 'Name3' , 'name3@gmail.com' , 'F' , 80 );

Select * from my_stu_details;

Validating Unique Key Constraint

--Duplicate Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , 'name3@gmail.com' , 'F' , 80 );

ORA-00001: unique constraint (HR.MY_STU_MAIL_UK) violated

--Null Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , null , 'M' , 70 );


Select * from my_stu_details;

Validating Check constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'j' , 70 );

ORA-02290: check constraint (HR.MY_STU_GEN_CK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'M' , 70 );

Select * from my_stu_details;

Validating Foreign Key

Select * from Departments;


Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 3 );

ORA-02291: integrity constraint (HR.MY_STU_DID_FK) violated - parent key not found

Departments table : parent table

my_stu_details : Child table

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

--------------------------------------------------------

s_id s_name s_mail s_gender s_did

--------------------------------------------------------

1 name1 name1@gmail.com m 60

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 M 70
5 Name5 name5@gmail.com M 70

6 Name6 name6@gmail.com F 90

--------------------------------------------------------

Deleting the Primary key value which is referred by Foreign Key

Select * from Departments;

DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID

------------------------------------------------------------

60 IT 103 1400 <---- Delete

-- don't execute this query

--Delete From Departments

--Where Department_id = 60;

1) ON DELETE SET NULL

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID


-------------------------------------------------

6 Name6 name6@gmail.com F 90

1 name1 name1@gmail.com m -

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

2) ON DELETE SET CASCADE

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

Syntax

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE CASCADE
Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE SET NULL

Constraint Related Data Dictionary Table information.

To view constraint Information

SELECT c.owner,

c.constraint_name,

c.constraint_type,

c.table_name,

c.r_constraint_name,

c.status

FROM user_constraints c

WHERE c.table_name = 'MY_STU_DETAILS';

------------------------------------------------------------------------------------

owner constraint_name constraint_type table_name r_constraint_name status

------------------------------------------------------------------------------------

HR SYS_C004023 C MY_STU_DETAILS ENABLED

HR MY_STU_GEN_CK C MY_STU_DETAILS ENABLED


HR MY_STU_SID_PK P MY_STU_DETAILS ENABLED

HR MY_STU_MAIL_UK U MY_STU_DETAILS ENABLED

HR MY_STU_DID_FK R MY_STU_DETAILS DEPT_ID_PK ENABLED

------------------------------------------------------------------------------------

To view constraint name with corresponding column name

SELECT * FROM user_cons_columns c

WHERE c.table_name = 'MY_STU_DETAILS';

-------------------------------------------------------------

owner constraint_name table_name column_name position

-------------------------------------------------------------

HR MY_STU_MAIL_UK MY_STU_DETAILS S_MAIL 1

HR MY_STU_SID_PK MY_STU_DETAILS S_ID 1

HR MY_STU_GEN_CK MY_STU_DETAILS S_GENDER

HR SYS_C004023 MY_STU_DETAILS S_NAME

HR MY_STU_DID_FK MY_STU_DETAILS S_DID 1

-------------------------------------------------------------

Creating Composite Primary Key


Creating Primary Key with more than one number of column

ALTER TABLE table_name

ADD CONSTRAINT constraint_name PRIMARY KEY(column1, column_2 , column3);

In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.

creating constraint after the table creation

ALTER TABLE table_name

ADD CONSTRAINT constraint_name CONSTRAINT_TYPE(column_name);

ALTER TABLE table_name

DROP CONSTRAINT constraint_name;

ALTER TABLE table_name

DROP PRIMARY KEY;

To drop related foreign key


ALTER TABLE table_name

DROP PRIMARY KEY CASCADE;

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name;

Disable constraint with related foreign key constraint

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name CASCADE;

ALTER TABLE table_name

ENABLE CONSTRAINT constraint_name;

Interview Questions

What are all the type of constraint available in oracle?

Difference between PRIMARY KEY and UNIQUE key.

Difference between PRIMARY KEY ans FOREIGN KEY.

Difference between UNIQUE key and FOREIGN KEY.


Is it possible to create tow primary key in single table.

Write a syntax to create FOREIGN constraint.

How to create constraint after the table has been created?

How to enable and disable a constraint.

Which data dictionary table contains information about constraints?

Which Data Dictionary table contains information about constraint with corresponding column
name?

What is composite primary key?

Explain ON DELETE CASCADE and ON DELETE SET NULL option.

~Thanks For Reading~

Post your valuable feedback below

Posted 21st December 2014 by Unknown

1 View comments

UnknownMay 22, 2017 at 12:39 AM

good

Reply
DEC

listagg in Oracle 11g

Oracle 11gR2 listagg built-in function allows for many table columns to be displayed within a
single row, a non-first-normal form display

Syntax :

listagg(column_value,'delimiter') WITHIN GROUP(ORDER BY column_name)

--Example 1:

CREATE TABLE test_ins(empid NUMBER,product VARCHAR2(30));

BEGIN

INSERT INTO test_ins VALUES( 101,'pendrive');

INSERT INTO test_ins VALUES( 102,'toy');

INSERT INTO test_ins VALUES( 101,'ipod');

INSERT INTO test_ins VALUES( 102,'hat');

INSERT INTO test_ins VALUES( 103,'cpu');

INSERT INTO test_ins VALUES( 104,'pen');

INSERT INTO test_ins VALUES( 104,'car');

INSERT INTO test_ins VALUES( 104,'mat');

INSERT INTO test_ins VALUES( 105,'tv');


INSERT INTO test_ins VALUES( 106,'laptop');

commit;

END;

SELECT * FROM test_ins;

SELECT empid "Employee",

listagg(product,

',') within

GROUP (ORDER BY empid) "Products"

FROM test_ins

GROUP BY empid;

-->-- Result set --<--


DROP TABLE test_ins;

-->-- Example 2

select department_id "Department id", listagg(first_name,', ') WITHIN GROUP(ORDER BY


employee_id) "Employees"

FROM employees

WHERE department_id IN (10,20,30,60)

GROUP BY department_id;

-->-- Result set --<--

Posted 4th December 2014 by Unknown

0 Add a comment

NOV

Condition and Looping Statement


IF

IF ELSE

Multiple IF ELSE

LOOP

FOR LOOP

WHILE LOOP

create table test_udt(id NUMBER, salary NUMBER);

BEGIN

INSERT INTO test_udt VALUES(001,23000);

INSERT INTO test_udt VALUES(002,43000);

INSERT INTO test_udt VALUES(003,78000);

INSERT INTO test_udt VALUES(004,25000);

INSERT INTO test_udt VALUES(005,26000);

INSERT INTO test_udt VALUES(006,90000);

Commit;

END;

select * from test_udt;


IF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 1;

IF v_salary > 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

END IF;

commit;

END;

IF ELSE
DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

ELSE

UPDATE test_udt t

SET t.salary = v_salary+20007

WHERE t.id = v_id ;

END IF;

commit;

END;

--same example with less number of lines


DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

v_salary := v_salary+10005;

ELSE

v_salary := v_salary+20007;

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;


Multiple IF ELSIF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 3;

IF v_id = 1 THEN

v_salary := 1000;

dbms_output.put_line('1 inside');

ELSIF v_id = 2 THEN

v_salary := 2000;

dbms_output.put_line('2 inside');

ELSIF v_id = 3 THEN

v_salary := 3000;

dbms_output.put_line('3 inside');

ELSIF v_id = 4 THEN

v_salary := 4000;

dbms_output.put_line('4 inside');

END IF;
UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

LOOP

--syntax

LOOP

--statements

--increment

--exit statement

END LOOP;

CREATE TABLE prod_details (pid VARCHAR2(3), pname VARCHAR2(30));

DECLARE

i NUMBER := 1;
x VARCHAR2(3);

BEGIN

LOOP

x := lpad(i,3,'0');

dbms_output.put_line('x value : '|| x);

INSERT INTO prod_details VALUES(i, 'Product '||i);

EXIT WHEN i >900;

i := i+1;

IF MOD(i,100) = 0 THEN

commit;

dbms_output.put_line('commit executed');

END IF;

END LOOP;

END;

SELECT * FROM prod_details ORDER BY 1;

DROP TABLE prod_details;

FOR LOOP

BEGIN

FOR I in 1..5
LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

FOR LOOP - Reverse

BEGIN

FOR I in REVERSE 14..50

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

WHILE LOOP

DECLARE

i_val NUMBER:=0;

BEGIN

WHILE (i_val < 11)

LOOP

dbms_output.put_line('The value of I is '||i_val);

i_val := i_val + 1;
END LOOP;

END;

sample output:

The value of I is 0

The value of I is 1

The value of I is 2

The value of I is 3

The value of I is 4

The value of I is 5

The value of I is 6

The value of I is 7

The value of I is 8

The value of I is 9

The value of I is 10

Posted 8th November 2014 by Unknown

0 Add a comment

OCT
21

Bulk Collect

This is used for array fetches

With this you can retrieve multiple rows of data with a single round trip.

This reduces the number of context switches between the pl/sql and sql engines.

You can use bulk collect in both dynamic and static sql.

You can use bulk collect in select, fetch into and returning into clauses.

SQL engine automatically initializes and extends the collections you reference in the bulk
collect clause.

You can fetch into multiple collections with one column each.

You can use the limit clause of bulk collect to restrict the no of rows retrieved.

SELECT * FROM product_details;

-->-- Bulk collect in FETCH INTO --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN
OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Bulk collect in SELECT clause --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

BEGIN

SELECT * BULK COLLECT INTO dta FROM product_details;

FOR i IN dta.FIRST .. dta.LAST LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;
-->-- LIMIT in Bulk collect --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta LIMIT 30;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Multiple fetches in INTO clause --<--

SELECT * FROM product_details;


DECLARE

TYPE alldata_typ1 IS TABLE OF product_details.p_id%TYPE;

TYPE alldata_typ2 IS TABLE OF product_details.p_name%TYPE;

dta1 alldata_typ1;

dta2 alldata_typ2;

CURSOR proddt_cur IS

SELECT p_id, p_name FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta1, dta2;

CLOSE proddt_cur;

FOR i IN dta1.FIRST .. dta1.COUNT LOOP

dbms_output.put_line('Department Id : ' || dta1(i));

END LOOP;

FOR i IN dta2.FIRST .. dta2.COUNT LOOP

dbms_output.put_line('Department Name : ' || dta2(i));

END LOOP;

END;

/
DROP TABLE dep_details;

DROP TABLE product_details;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Ref Cursor

This is unconstrained cursor which will return different types depends upon the user input.

Ref cursors cannot be closed implicitly.

Ref cursor with return type is called strong cursor.

Ref cursor without return type is called weak cursor.

You can declare ref cursor type in package spec as well as body.

You can declare ref cursor types in local subprograms or anonymous blocks.

CREATE OR REPLACE PROCEDURE ref_c_sp(dep_det_c IN OUT SYS_REFCURSOR)

AS

BEGIN

OPEN dep_det_c
FOR

SELECT * FROM dep_details d;

END;

DECLARE

dep_det_c SYS_REFCURSOR;

tab_data dep_details%ROWTYPE;

BEGIN

ref_c_sp(dep_det_c);

LOOP

FETCH dep_det_c INTO tab_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department Name : '|| tab_data.d_name);

END LOOP;

CLOSE dep_det_c;

END;

/*sample output*/

Department Name : Admin

Department Name : HR
Department Name : Sales

Department Name : Marketing

DROP PROCEDURE ref_c_sp;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Cursor

SQL Private work Area where the query get passed and executed.

Types

******

Implicit(SQL)

Explicit

-->-- advanced cursor types --<--

Parametrized Cursor

Ref Cursor
Implicit

********

ORACLE implicitly opens a cursor to process each SQL statement not associated with an
explicitly declared cursor.

PL/SQL lets you refer to the most recent implicit cursor as the SQL” cursor. So, although you
cannot use the OPEN,

FETCH, and CLOSE statements to control an implicit cursor, you can still use cursor attributes to
access information

about the most recently executed SQL statement.

Cursor Stages

**************

OPEN cursor_name

FETCH (with in loop)

CLOSE cursor_name

Explicit

The set of rows returned by a query can consist of zero, one, or multiple rows,

depending on how many rows meet your search criteria. When a query returns multiple rows,

you can explicitly define a cursor to process the rows. You use three commands to control the
cursor
Cursor Attributes

*****************

%FOUND

%NOTFOUND

%ISOPEN

%ROWCOUNT

%BULK_ROWCOUNT --<-- used to handle error while using bulk collection.

%BULK_EXCEPTIONS --<-- used to handle error while using bulk collection.

Cursor Declaration

DECLARE

CURSOR <cursor_name>

IS

<SELECT statement>

BEGIN

--> some stmt

END;

Cursor Loop

Loop

While Loop

For Loop
Cursor Clauses

Return

For update

Where current of

Bulk collect

-->-- creating table

create table product_details

p_id NUMBER,

p_name VARCHAR2(30),

p_order_dt DATE

);

-->-- Inserting data

BEGIN

FOR i IN 1 .. 75 LOOP

INSERT INTO product_details VALUES (i, 'prod_name_' || i, SYSDATE + i);

END LOOP;

commit;

END;
-->-- selecting data

SELECT * FROM product_details;

---------------------------------------------

p_id p_name p_order_dt

---------------------------------------------

1 prod_name_1 10/11/2014 3:48:32 PM

2 prod_name_2 10/12/2014 3:48:32 PM

3 prod_name_3 10/13/2014 3:48:32 PM

4 prod_name_4 10/14/2014 3:48:32 PM

5 prod_name_5 10/15/2014 3:48:32 PM

6 prod_name_6 10/16/2014 3:48:32 PM

7 prod_name_7 10/17/2014 3:48:32 PM

8 prod_name_8 10/18/2014 3:48:32 PM

9 prod_name_9 10/19/2014 3:48:32 PM

10 prod_name_10 10/20/2014 3:48:32 PM

11 prod_name_11 10/21/2014 3:48:32 PM

12 prod_name_12 10/22/2014 3:48:32 PM

13 prod_name_13 10/23/2014 3:48:32 PM

14 prod_name_14 10/24/2014 3:48:32 PM

15 prod_name_15 10/25/2014 3:48:32 PM

16 prod_name_16 10/26/2014 3:48:32 PM


17 prod_name_17 10/27/2014 3:48:32 PM

18 prod_name_18 10/28/2014 3:48:32 PM

19 prod_name_19 10/29/2014 3:48:32 PM

20 prod_name_20 10/30/2014 3:48:32 PM

---------------------------------------------

----------------------------------------------

Implicit Cursor

----------------------------------------------

--will update soon

----------------------------------------------

Explicit Cursor

----------------------------------------------

**********************************************

Processing cursor data by using LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS
SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND; --<-- if next record not found means control will
come out from the loop

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )


DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

EXIT WHEN prod_detail_cur%FOUND; --<-- if next record found means control will come
out from the loop

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )


DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;
END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor Already closed

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP
FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

-->-- CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )


Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor closed

**********************************************

Processing cursor data by using WHILE LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

OPEN prod_detail_cur;

FETCH prod_detail_cur

INTO all_data;

WHILE prod_detail_cur%FOUND LOOP

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');


FETCH prod_detail_cur

INTO all_data;

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

************************************************************

Processing cursor data by using FOR LOOP - CURSOR FOR LOOP

************************************************************

DECLARE

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

FOR i IN prod_detail_cur
LOOP

dbms_output.put_line('Product id : ' || i.p_id ||

' Product Name : ' || i.p_name ||

' ( Orderd on : ' || TRIM(i.p_order_dt) || ' )');

END LOOP;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

Parameterized Cursor

*********************

This was used when you are going to use the cursor in more than one place with different
values for the same where clause.

Cursor parameters must be in mode.

Cursor parameters may have default values.

The scope of cursor parameter is within the select statement.


CREATE TABLE dep_details(d_id NUMBER,d_name VARCHAR2(30), location_id NUMBER);

BEGIN

INSRT INTO dep_details VALUES(001,'Admin',1010);

INSRT INTO dep_details VALUES(002,'HR',1010);

INSRT INTO dep_details VALUES(003,'Sales',1020);

INSRT INTO dep_details VALUES(004,'Marketing',1020);

commit;

END;

SELECT * FROM dep_details;

----------------------------

d_id d_name location_id

----------------------------

1 Admin 1010

2 HR 1010

3 Sales 1020

4 Marketing 1020

----------------------------
DECLARE

-->--Declaring parameterized cursor

CURSOR dep_det_c(p_location_id NUMBER) IS

SELECT * FROM dep_details d WHERE d.location_id = p_location_id;

all_data dep_details%ROWTYPE;

BEGIN

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

OPEN dep_det_c(1010);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

-->-- opening same cursor with different input value

OPEN dep_det_c(1020);

LOOP

FETCH dep_det_c

INTO all_data;
EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

END;

/*sample output*/

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 1 Department Name : Admin

Department id : 2 Department Name : HR

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 3 Department Name : Sales

Department id : 4 Department Name : Marketing

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Posted 21st October 2014 by Unknown

0 Add a comment
OCT

21

Handling Exception

Error Handling in oracle

ERROR

Any departure from the expected behavior of the system or program,

which stops the working of the system is an error.

Types : compile time error

Run time error

EXCEPTION

Any error or problem which one can handle and continue to work normally.

Handling Exception

When exception is raised, control passes to the exception section of the block.

i.e. EXCEPTION

WHEN name_of_exception THEN

Types : Pre Defined Exceptions

User Defined Exceptions


Predefined Exception

*********************

Oracle has predefined several exceptions that correspond to the most common oracle errors.

------------------------------------------------------------------------

Exception Oracle Error SQL Code Value

------------------------------------------------------------------------

ZERO_DIVIDE ORA-01476 -1476

NO_DATA_FOUND ORA-01403 +100

DUP_VAL_ON_INDEX ORA-00001 -1

TOO_MANY_ROWS ORA-01422 -1422

VALUE_ERROR ORA-06502 -6502

CURSOR_ALREADY_OPEN ORA-06511 -6511

OTHERS

------------------------------------------------------------------------

-->-- ZERO_DIVIDE --<--

Your program attempts to divide a number by zero.

DECLARE

v_result NUMBER;
BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN ZERO_DIVIDE THEN

dbms_output.put_line('Divisor is equal to zero');

END;

-->-- NO_DATA_FOUND --<--

Single row SELECT returned no rows or your program referenced a deleted element in a nested
table

or an uninitialized element in an associative array (index-by table).

CREATE TABLE test_tb(id NUMBER PRIMARY KEY);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN NO_DATA_FOUND THEN

dbms_output.put_line('There is no data inside the table');

END;
-->-- DUP_VAL_ON_INDEX --<--

A program attempted to insert duplicate values in a column that is constrained by a unique


index.

INSERT INTO test_tb VALUES (1);

INSERT INTO test_tb VALUES (2);

commit;

BEGIN

INSERT INTO test_tb VALUES (2);

EXCEPTION

WHEN DUP_VAL_ON_INDEX THEN

dbms_output.put_line('Duplicate values are not allowed');

END;

-->-- TOO_MANY_ROWS --<--

Single row SELECT returned multiple rows.

DECLARE

v_id NUMBER;
BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN TOO_MANY_ROWS THEN

dbms_output.put_line('Query returning more than one row');

END;

DROP TABLE test_tb;

-->-- VALUE_ERROR --<--

An arithmetic, conversion, truncation, or size constraint error occurred.

DECLARE

num1 NUMBER(2);

BEGIN

num1 := 345;

EXCEPTION

WHEN VALUE_ERROR THEN

dbms_output.put_line('check the size of the variable');

END;

-->-- CURSOR_ALREADY_OPEN --<--


A program attempted to open an already opened cursor.

CREATE TABLE emp(id NUMBER, name VARCHAR2(30));

BEGIN

INSERT INTO emp VALUES(1,'Name1');

INSERT INTO emp VALUES(2,'Name2');

INSERT INTO emp VALUES(3,'Name3');

INSERT INTO emp VALUES(4,'Name4');

COMMIT;

END;

SELECT * FROM emp;

DECLARE

cursor emp_c IS

SELECT * FROM emp;

all_data emp%ROWTYPE;

BEGIN

OPEN emp_c;

OPEN emp_c;

NULL;
CLOSE emp_c;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

END;

DROP TABLE emp;

-->-- OTHERS --<--

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

WHEN OTHERS THEN

dbms_output.put_line('Some other error ' || SQLERRM);

END;

User Defined Exception

**********************
A user-defined exception is an error that is defined by the programmer.

User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,

exceptions have a type EXCEPTION and scope.

DECLARE

v_gender CHAR := '&gender';

gender_ex EXCEPTION;

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE gender_ex;

END IF;

dbms_output.put_line('Gender : '||v_gender);

EXCEPTION

WHEN gender_ex THEN

dbms_output.put_line('Please Enter valid gender');

END;

create table test_insert (id NUMBER, Name VARCHAR2(30));

DECLARE

abort_ex EXCEPTION;
BEGIN

FOR i IN 1..100

LOOP

BEGIN

IF mod(i,10)=0 THEN

RAISE abort_ex;

END IF;

INSERT INTO test_insert VALUES(i, 'Name'||i);

EXCEPTION

WHEN abort_ex THEN

NULL;

END;

END LOOP;

COMMIT;

END;

SELECT * FROM test_insert;

DROP TABLE test_insert;

SQLERRM and SQLCODE

********************

SQLCODE returns the current error code, and SQLERRM returns the current error message
text;
For user-defined exception SQLCODE returns 1 and SQLERRM returns “user-defined
exception”.

SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.

CREATE TABLE test_tb (id NUMBER);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

dbms_output.put_line(v_id);

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('SQLERRM : ' || SQLERRM);

dbms_output.put_line('SQLCODE : ' || SQLCODE);

END;

/*sample output*/

SQLERRM : ORA-01403: no data found

SQLCODE : 100

DROP TABLE test_tb;


PRAGMA EXCEPTION_INIT

*********************

Using this you can associate a named exception with a particular oracle error.

This gives you the ability to trap this error specifically, rather than via an OTHERS handler.

Syntax:

PRAGMA EXCEPTION_INIT(exception_name, oracle_error_number);

DECLARE

v_result NUMBER;

PRAGMA EXCEPTION_INIT(Invalid, -1476);

BEGIN

SELECT 453 / 0 INTO v_result FROM dual;

dbms_output.put_line('Result : ' || v_result);

EXCEPTION

WHEN INVALID THEN

dbms_output.put_line('Invalid Exception');

END;

RAISE_APPLICATION_ERROR
************************

You can use this built-in function to create your own error messages, which can be more
descriptive than named exceptions.

Error Number :

Oracle Error Range : From -00000 to -19999

User Error Range : From -20000 to -20999

DECLARE

v_gender CHAR := '&gender';

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE_APPLICATION_ERROR(-20003, 'Enter valid gender');

END IF;

dbms_output.put_line('Gender : ' || v_gender);

END;

Posted 21st October 2014 by Unknown

1 View comments
Loading

Dynamic Views theme. Powered by Blogger.

Oracle sql & Pl/sql

search

Home Sql and pl/sql Sql Interview Questions

JUL

20

INLINE view in Oracle with 12c New Features

Named sub Query in FROM clause is call it as INLINE VIEW.

Oracle process a inline view faster than sub query

Inline View in Oracle

--Query to display all the employees who are all getting salary more than their department
average salary

SELECT First_name

, last_name

, salary

, department_id

FROM employees a , ( SELECT b.department_id


, AVG(b.salary) avg_sal

FROM employees b

GROUP BY b.department_id

)b

WHERE a.department_id = b.department_id

AND a.salary > b.avg_salary;

Display all the customer who have placed more number of orders by using INLINE view

CREATE TABLE customer_order_det_tb

( custm_id NUMBER ,

custm_nm VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

ttl_amt NUMBER(7,2)

);

BEGIN

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '11-Jul-15' , 45000.00);

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '14-Jul-15' , 27000.00);

INSERT INTO customer_order_det_tb VALUES(101, 'Raja' , '13-Jul-15' , 17000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 34000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 38000.00);

COMMIT;

END;
SELECT c.*

FROM customer_order_det_tb c;

--------------------------------------------

custm_id custm_nm order_dt ttl_amt

--------------------------------------------

100 Murugappan 7/11/2015 45000.00

100 Murugappan 7/14/2015 27000.00

101 Raja 7/13/2015 17000.00

102 Ramesh 7/15/2015 34000.00

102 Ramesh 7/15/2015 38000.00

--------------------------------------------

--Writing a Quer to display all the customer who have placed maximum number of order

--Query #1 for inline view

SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC;

--------------------------------
custm_id custm_nm total_odr

--------------------------------

100 Murugappan 2

102 Ramesh 2

101 Raja 1

--------------------------------

--Query #2 for inline view

SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm;

----------

total_odr

----------

----------

Inline view to find all the customers who have placed maximum number of orders

/****************************************

Syntax

SELECT * FROM <query1> x, <query2> y


WHERE contition;

****************************************/

SELECT query1.* FROM

( SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC

) query1,

( SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm

) query2

WHERE query1.total_odr = query2.total_odr;

-------------------------------

custm_id custm_nm total_odr

-------------------------------

100 Murugappan 2

102 Ramesh 2

-------------------------------

DROP TABLE customer_order_det_tb;

--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT
SELECT first_name, salary

FROM ( SELECT first_name, salary

FROM employees e

WHERE job_id NOT IN ('SALESMAN','PRESIDENT')

ORDER BY salary DESC

WHERE ROWNUM < 4;

New Oracle 12c Inline view Syntax

LATERAL clause for In-line views

Allows for columns in the inline view to be accessed!!

Example :

--in 11g

SELECT * FROM employees e, (

SELECT *

FROM departments d

WHERE e.department_id = d.department_id);


ORA-0090: "E"."DEPARTMENT_ID": Invalid Identifier

--in 12c

SELECT * FROM employees e, LATERAL(

SELECT *

FROM departments d

WHERE e.department_id = d.department_id

);

--in 11g

WITH t

AS

( SELECT LEVEL a

FROM dual

CONNECT BY LEVEL <= 30)

SELECT *

FROM t, (SELECT *

FROM employees

WHERE department_id = t.a

);

ORA-00904: "T"."A": invalid Identifier


--in 12c

WITH t

AS

(SELECT LEVEL a FROM dual CONNECT BY LEVEL <= 30)

SELECT * FROM t,

LATERAL(SELECT *

FROM employees

WHERE department_id = t.a);

Hope you have enjoyed this little article

Feed backs are always Welcome :) (:

Posted 20th July 2015 by Unknown

0 Add a comment

JAN

23

Salary Related Questions in Oracle

--creating table
CREATE TABLE employee_data

eid NUMBER(4),

ename VARCHAR2(30),

depno NUMBER(3),

salary NUMBER(8)

);

BEGIN

--Inserting records

INSERT INTO employee_data VALUES(1000,'Name01',90,30000);

INSERT INTO employee_data VALUES(1001,'Name02',90,6000);

INSERT INTO employee_data VALUES(1002,'Name03',90,23000);

INSERT INTO employee_data VALUES(1003,'Name04',60,35000);

INSERT INTO employee_data VALUES(1004,'Name05',60,60000);

INSERT INTO employee_data VALUES(1005,'Name06',60,30000);

INSERT INTO employee_data VALUES(1006,'Name07',80,36000);

INSERT INTO employee_data VALUES(1007,'Name08',80,29000);

INSERT INTO employee_data VALUES(1008,'Name09',80,37000);

INSERT INTO employee_data VALUES(1009,'Name10',80,41000);

COMMIT;

END;

/
SELECT * FROM employee_data

ORDER BY salary DESC;

--query to find maximum salary from employee_data table

SELECT MAX(salary) FROM employee_data;

--query to find minimum salary from employee_data table

SELECT MIN(salary) FROM employee_data;

--query to find second maximum salary from employee_data table

SELECT MAX(salary)

FROM employee_data

WHERE salary NOT IN (SELECT MAX(salary)

FROM employee_data);

--query to select 5th maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary


FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= 5);

--query to select nth maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= &n);

--query to select all the details of the employee whose getting nth maximum salary

SELECT *

FROM (SELECT emp.*,

rownum rn

FROM (SELECT *

FROM employee_data

ORDER BY salary DESC) emp)

WHERE rn = 9;
--same query using row_numbr( ) function

SELECT *

FROM (SELECT emp.*,

row_number() over(ORDER BY salary) rank

FROM employee_data emp)

WHERE rank = 9;

--same query using rank( ) function

SELECT *

FROM (SELECT emp.*,

rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--same query using dense_rank( ) function

SELECT *

FROM (SELECT emp.*,

dense_rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;
--query to display display maximum salary in all the department

SELECT e.depno "Department id",

MAX(salary) "Maximum Salary"

FROM employee_data e

GROUP BY e.depno;

--query to display all the employees who are all getting salary more than average salary of the
company

SELECT e.* FROM employee_data e

WHERE salary > (SELECT AVG(salary) FROM employee_data);

--query to display all the employees who are all getting salary more than their department
average salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE department_id = OUT.department_id);

--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE employee_id = OUT.manager_id);

Documented By : Murugappan Annamalai

Posted on : 23-Jan-15 16:34:00 IST.

Hope you have enjoyed this little article

Feed backs are always welcome :)

Posted 23rd January 2015 by Unknown

7 View comments

JAN

22
Why prefer COALESCE over NVL

Documented By : Nimish Garg

I prefer using "COALESCE" over "NVL" is some of the scenarios. Last week One of my friend
asked me what is the advantage of using "COALESCE" where we can simply use "NVL". I simply
gave him the reply from Oracle Docs i.e. NVL lets you replace null (returned as a blank) with a
string in the results of a query and COALESCE returns the first non-null expr in the expression list.
Oracle Database uses short-circuit evaluation with "COALESCE".

He replied that he knows the difference, he knows that "COALESCE" can take multiple arguments
and so on. He was more interested in understanding "short-circuit evaluation" of "COALESCE"
and the scenarios where I prefer using "COALESCE" over "NVL".

To make him understand I created following function which takes One second in every execution
and simply returns '--null--' and executed 2 very similar queries one with NVL and other with
COALESCE.

SQL> create or replace function f_null return varchar2

2 is

3 begin

4 dbms_lock.sleep(1);

5 return '--null--';

6 end;

7 /

Function created.
Following are the queries which I used to demonstrate that NVL evaluates both arguments even
if the second argument is not used and COALESCE uses short-circuit evaluation i.e. it only
evaluates the arguments only if they are needed.

SQL> select e.empno, e.ename ename, nvl(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--


14 rows selected.

Elapsed: 00:00:14.01

SQL> select e.empno, e.ename ename, coalesce(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--


14 rows selected.

Elapsed: 00:00:01.01

Here we can see easily that the first query with NVL took 14+ seconds, one second for each
record even if the "f_null" value was used only in one record. On the contrary as mentioned in
Oracle Documentation "COALESCE" uses its "short-circuit evaluation" and "f_null" was called
only once and so second query took only One Second. "COALESCE" is certainly use less resources
than NVL.

Posted 22nd January 2015 by Unknown

0 Add a comment

DEC

21

Constraints

It Enforce Rule On Table

We can create constraint at the time of Creating Table

1. Column Level Declaration


2. Table Level Declaration

1. We can provide own name.

Format : [part_of_project_name-table_name-column_name-constraint_type]

Example : gmind_emp_id_pk _uk _ck _f

2. system name name

Format : sys_cn

Example : SYS_C405323

We can create constraint after the table has been created

Types

Primary Key

Not allowed Null value

Not allowed you to enter duplicate value

Ex : Employee_id, Student_id
Unique Key

allowed Null value

Not allowed you to enter duplicate value

Ex : Contact_no, email

Foreign Key

It will allowed you to enter NULL and Duplicate value.

c1(pk) : 1 2 3

c2(f) : 1 1 2 3 4 Not allowed

Allowed you to enter duplicate value and null value

Not Null

It will not allowed you to enter null value

Check

You can check your own condition

Simple Table for understanding


------------------------------------

Duplicate NULL

------------------------------------

Primary Key X X

Unique Key X Allowed

Foreign Key Allowed Allowed

------------------------------------

creating table with all constraint type

Create table my_stu_details

S_id Number(2),

S_name Varchar2(30) Not Null, --SYS_Cn

s_mail Varchar2(30),

s_gender char(1),

s_did Number(3),

Constraint my_stu_sid_pk PRIMARY KEY (s_id),

constraint my_stu_mail_uk UNIQUE (s_mail) ,

Constraint my_stu_gen_ck CHECK (s_gender IN ('M', 'F', 'm', 'f')),

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)


);

DESC my_stu_details;

------------------------------------

Name Type Nullable

------------------------------------

S_ID NUMBER(2)

S_NAME VARCHAR2(30)

S_MAIL VARCHAR2(30) Y

S_GENDER CHAR(1) Y

S_DID NUMBER(3) Y

------------------------------------

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name1' , 'name1@gmail.com' , 'm' , 60 );

Select * from my_stu_details;


Validating Primary Key

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-00001: unique constraint (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (NULL, 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-01400: cannot insert NULL into (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (2 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

Validating NOT NULL Constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , NULL , 'name3@gmail.com' , 'F' , 80 );


ORA-01400: cannot insert NULL into ("HR"."MY_STU_DETAILS"."S_NAME")

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , 'Name3' , 'name3@gmail.com' , 'F' , 80 );

Select * from my_stu_details;

Validating Unique Key Constraint

--Duplicate Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , 'name3@gmail.com' , 'F' , 80 );

ORA-00001: unique constraint (HR.MY_STU_MAIL_UK) violated

--Null Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)


values (4 , 'Name4' , null , 'M' , 70 );

Select * from my_stu_details;

Validating Check constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'j' , 70 );

ORA-02290: check constraint (HR.MY_STU_GEN_CK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'M' , 70 );

Select * from my_stu_details;

Validating Foreign Key


Select * from Departments;

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 3 );

ORA-02291: integrity constraint (HR.MY_STU_DID_FK) violated - parent key not found

Departments table : parent table

my_stu_details : Child table

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

--------------------------------------------------------

s_id s_name s_mail s_gender s_did

--------------------------------------------------------

1 name1 name1@gmail.com m 60

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80
4 Name4 M 70

5 Name5 name5@gmail.com M 70

6 Name6 name6@gmail.com F 90

--------------------------------------------------------

Deleting the Primary key value which is referred by Foreign Key

Select * from Departments;

DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID

------------------------------------------------------------

60 IT 103 1400 <---- Delete

-- don't execute this query

--Delete From Departments

--Where Department_id = 60;

1) ON DELETE SET NULL

-------------------------------------------------
S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

1 name1 name1@gmail.com m -

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

2) ON DELETE SET CASCADE

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

Syntax

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)


ON DELETE CASCADE

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE SET NULL

Constraint Related Data Dictionary Table information.

To view constraint Information

SELECT c.owner,

c.constraint_name,

c.constraint_type,

c.table_name,

c.r_constraint_name,

c.status

FROM user_constraints c

WHERE c.table_name = 'MY_STU_DETAILS';

------------------------------------------------------------------------------------

owner constraint_name constraint_type table_name r_constraint_name status

------------------------------------------------------------------------------------

HR SYS_C004023 C MY_STU_DETAILS ENABLED


HR MY_STU_GEN_CK C MY_STU_DETAILS ENABLED

HR MY_STU_SID_PK P MY_STU_DETAILS ENABLED

HR MY_STU_MAIL_UK U MY_STU_DETAILS ENABLED

HR MY_STU_DID_FK R MY_STU_DETAILS DEPT_ID_PK ENABLED

------------------------------------------------------------------------------------

To view constraint name with corresponding column name

SELECT * FROM user_cons_columns c

WHERE c.table_name = 'MY_STU_DETAILS';

-------------------------------------------------------------

owner constraint_name table_name column_name position

-------------------------------------------------------------

HR MY_STU_MAIL_UK MY_STU_DETAILS S_MAIL 1

HR MY_STU_SID_PK MY_STU_DETAILS S_ID 1

HR MY_STU_GEN_CK MY_STU_DETAILS S_GENDER

HR SYS_C004023 MY_STU_DETAILS S_NAME

HR MY_STU_DID_FK MY_STU_DETAILS S_DID 1

-------------------------------------------------------------

Creating Composite Primary Key


Creating Primary Key with more than one number of column

ALTER TABLE table_name

ADD CONSTRAINT constraint_name PRIMARY KEY(column1, column_2 , column3);

In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.

creating constraint after the table creation

ALTER TABLE table_name

ADD CONSTRAINT constraint_name CONSTRAINT_TYPE(column_name);

ALTER TABLE table_name

DROP CONSTRAINT constraint_name;

ALTER TABLE table_name

DROP PRIMARY KEY;

To drop related foreign key


ALTER TABLE table_name

DROP PRIMARY KEY CASCADE;

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name;

Disable constraint with related foreign key constraint

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name CASCADE;

ALTER TABLE table_name

ENABLE CONSTRAINT constraint_name;

Interview Questions

What are all the type of constraint available in oracle?

Difference between PRIMARY KEY and UNIQUE key.

Difference between PRIMARY KEY ans FOREIGN KEY.


Difference between UNIQUE key and FOREIGN KEY.

Is it possible to create tow primary key in single table.

Write a syntax to create FOREIGN constraint.

How to create constraint after the table has been created?

How to enable and disable a constraint.

Which data dictionary table contains information about constraints?

Which Data Dictionary table contains information about constraint with corresponding column
name?

What is composite primary key?

Explain ON DELETE CASCADE and ON DELETE SET NULL option.

~Thanks For Reading~

Post your valuable feedback below

Posted 21st December 2014 by Unknown

1 View comments

UnknownMay 22, 2017 at 12:39 AM

good

Reply
DEC

listagg in Oracle 11g

Oracle 11gR2 listagg built-in function allows for many table columns to be displayed within a
single row, a non-first-normal form display

Syntax :

listagg(column_value,'delimiter') WITHIN GROUP(ORDER BY column_name)

--Example 1:

CREATE TABLE test_ins(empid NUMBER,product VARCHAR2(30));

BEGIN

INSERT INTO test_ins VALUES( 101,'pendrive');

INSERT INTO test_ins VALUES( 102,'toy');

INSERT INTO test_ins VALUES( 101,'ipod');

INSERT INTO test_ins VALUES( 102,'hat');

INSERT INTO test_ins VALUES( 103,'cpu');

INSERT INTO test_ins VALUES( 104,'pen');

INSERT INTO test_ins VALUES( 104,'car');

INSERT INTO test_ins VALUES( 104,'mat');


INSERT INTO test_ins VALUES( 105,'tv');

INSERT INTO test_ins VALUES( 106,'laptop');

commit;

END;

SELECT * FROM test_ins;

SELECT empid "Employee",

listagg(product,

',') within

GROUP (ORDER BY empid) "Products"

FROM test_ins

GROUP BY empid;

-->-- Result set --<--


DROP TABLE test_ins;

-->-- Example 2

select department_id "Department id", listagg(first_name,', ') WITHIN GROUP(ORDER BY


employee_id) "Employees"

FROM employees

WHERE department_id IN (10,20,30,60)

GROUP BY department_id;

-->-- Result set --<--

Posted 4th December 2014 by Unknown

0 Add a comment

NOV

Condition and Looping Statement


IF

IF ELSE

Multiple IF ELSE

LOOP

FOR LOOP

WHILE LOOP

create table test_udt(id NUMBER, salary NUMBER);

BEGIN

INSERT INTO test_udt VALUES(001,23000);

INSERT INTO test_udt VALUES(002,43000);

INSERT INTO test_udt VALUES(003,78000);

INSERT INTO test_udt VALUES(004,25000);

INSERT INTO test_udt VALUES(005,26000);

INSERT INTO test_udt VALUES(006,90000);

Commit;

END;
select * from test_udt;

IF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 1;

IF v_salary > 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

END IF;

commit;

END;

IF ELSE
DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

ELSE

UPDATE test_udt t

SET t.salary = v_salary+20007

WHERE t.id = v_id ;

END IF;

commit;

END;

--same example with less number of lines


DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

v_salary := v_salary+10005;

ELSE

v_salary := v_salary+20007;

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;


Multiple IF ELSIF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 3;

IF v_id = 1 THEN

v_salary := 1000;

dbms_output.put_line('1 inside');

ELSIF v_id = 2 THEN

v_salary := 2000;

dbms_output.put_line('2 inside');

ELSIF v_id = 3 THEN

v_salary := 3000;

dbms_output.put_line('3 inside');

ELSIF v_id = 4 THEN

v_salary := 4000;

dbms_output.put_line('4 inside');

END IF;
UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

LOOP

--syntax

LOOP

--statements

--increment

--exit statement

END LOOP;

CREATE TABLE prod_details (pid VARCHAR2(3), pname VARCHAR2(30));

DECLARE
i NUMBER := 1;

x VARCHAR2(3);

BEGIN

LOOP

x := lpad(i,3,'0');

dbms_output.put_line('x value : '|| x);

INSERT INTO prod_details VALUES(i, 'Product '||i);

EXIT WHEN i >900;

i := i+1;

IF MOD(i,100) = 0 THEN

commit;

dbms_output.put_line('commit executed');

END IF;

END LOOP;

END;

SELECT * FROM prod_details ORDER BY 1;

DROP TABLE prod_details;

FOR LOOP

BEGIN
FOR I in 1..5

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

FOR LOOP - Reverse

BEGIN

FOR I in REVERSE 14..50

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

WHILE LOOP

DECLARE

i_val NUMBER:=0;

BEGIN

WHILE (i_val < 11)

LOOP

dbms_output.put_line('The value of I is '||i_val);


i_val := i_val + 1;

END LOOP;

END;

sample output:

The value of I is 0

The value of I is 1

The value of I is 2

The value of I is 3

The value of I is 4

The value of I is 5

The value of I is 6

The value of I is 7

The value of I is 8

The value of I is 9

The value of I is 10

Posted 8th November 2014 by Unknown

0 Add a comment
OCT

21

Bulk Collect

This is used for array fetches

With this you can retrieve multiple rows of data with a single round trip.

This reduces the number of context switches between the pl/sql and sql engines.

You can use bulk collect in both dynamic and static sql.

You can use bulk collect in select, fetch into and returning into clauses.

SQL engine automatically initializes and extends the collections you reference in the bulk
collect clause.

You can fetch into multiple collections with one column each.

You can use the limit clause of bulk collect to restrict the no of rows retrieved.

SELECT * FROM product_details;

-->-- Bulk collect in FETCH INTO --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;


BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Bulk collect in SELECT clause --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

BEGIN

SELECT * BULK COLLECT INTO dta FROM product_details;

FOR i IN dta.FIRST .. dta.LAST LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;
-->-- LIMIT in Bulk collect --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta LIMIT 30;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Multiple fetches in INTO clause --<--


SELECT * FROM product_details;

DECLARE

TYPE alldata_typ1 IS TABLE OF product_details.p_id%TYPE;

TYPE alldata_typ2 IS TABLE OF product_details.p_name%TYPE;

dta1 alldata_typ1;

dta2 alldata_typ2;

CURSOR proddt_cur IS

SELECT p_id, p_name FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta1, dta2;

CLOSE proddt_cur;

FOR i IN dta1.FIRST .. dta1.COUNT LOOP

dbms_output.put_line('Department Id : ' || dta1(i));

END LOOP;

FOR i IN dta2.FIRST .. dta2.COUNT LOOP

dbms_output.put_line('Department Name : ' || dta2(i));

END LOOP;

END;

/
DROP TABLE dep_details;

DROP TABLE product_details;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Ref Cursor

This is unconstrained cursor which will return different types depends upon the user input.

Ref cursors cannot be closed implicitly.

Ref cursor with return type is called strong cursor.

Ref cursor without return type is called weak cursor.

You can declare ref cursor type in package spec as well as body.

You can declare ref cursor types in local subprograms or anonymous blocks.

CREATE OR REPLACE PROCEDURE ref_c_sp(dep_det_c IN OUT SYS_REFCURSOR)

AS

BEGIN
OPEN dep_det_c

FOR

SELECT * FROM dep_details d;

END;

DECLARE

dep_det_c SYS_REFCURSOR;

tab_data dep_details%ROWTYPE;

BEGIN

ref_c_sp(dep_det_c);

LOOP

FETCH dep_det_c INTO tab_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department Name : '|| tab_data.d_name);

END LOOP;

CLOSE dep_det_c;

END;

/*sample output*/

Department Name : Admin


Department Name : HR

Department Name : Sales

Department Name : Marketing

DROP PROCEDURE ref_c_sp;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Cursor

SQL Private work Area where the query get passed and executed.

Types

******

Implicit(SQL)

Explicit

-->-- advanced cursor types --<--

Parametrized Cursor
Ref Cursor

Implicit

********

ORACLE implicitly opens a cursor to process each SQL statement not associated with an
explicitly declared cursor.

PL/SQL lets you refer to the most recent implicit cursor as the SQL” cursor. So, although you
cannot use the OPEN,

FETCH, and CLOSE statements to control an implicit cursor, you can still use cursor attributes to
access information

about the most recently executed SQL statement.

Cursor Stages

**************

OPEN cursor_name

FETCH (with in loop)

CLOSE cursor_name

Explicit

The set of rows returned by a query can consist of zero, one, or multiple rows,

depending on how many rows meet your search criteria. When a query returns multiple rows,

you can explicitly define a cursor to process the rows. You use three commands to control the
cursor
Cursor Attributes

*****************

%FOUND

%NOTFOUND

%ISOPEN

%ROWCOUNT

%BULK_ROWCOUNT --<-- used to handle error while using bulk collection.

%BULK_EXCEPTIONS --<-- used to handle error while using bulk collection.

Cursor Declaration

DECLARE

CURSOR <cursor_name>

IS

<SELECT statement>

BEGIN

--> some stmt

END;

Cursor Loop

Loop

While Loop
For Loop

Cursor Clauses

Return

For update

Where current of

Bulk collect

-->-- creating table

create table product_details

p_id NUMBER,

p_name VARCHAR2(30),

p_order_dt DATE

);

-->-- Inserting data

BEGIN

FOR i IN 1 .. 75 LOOP

INSERT INTO product_details VALUES (i, 'prod_name_' || i, SYSDATE + i);

END LOOP;

commit;
END;

-->-- selecting data

SELECT * FROM product_details;

---------------------------------------------

p_id p_name p_order_dt

---------------------------------------------

1 prod_name_1 10/11/2014 3:48:32 PM

2 prod_name_2 10/12/2014 3:48:32 PM

3 prod_name_3 10/13/2014 3:48:32 PM

4 prod_name_4 10/14/2014 3:48:32 PM

5 prod_name_5 10/15/2014 3:48:32 PM

6 prod_name_6 10/16/2014 3:48:32 PM

7 prod_name_7 10/17/2014 3:48:32 PM

8 prod_name_8 10/18/2014 3:48:32 PM

9 prod_name_9 10/19/2014 3:48:32 PM

10 prod_name_10 10/20/2014 3:48:32 PM

11 prod_name_11 10/21/2014 3:48:32 PM

12 prod_name_12 10/22/2014 3:48:32 PM

13 prod_name_13 10/23/2014 3:48:32 PM

14 prod_name_14 10/24/2014 3:48:32 PM

15 prod_name_15 10/25/2014 3:48:32 PM


16 prod_name_16 10/26/2014 3:48:32 PM

17 prod_name_17 10/27/2014 3:48:32 PM

18 prod_name_18 10/28/2014 3:48:32 PM

19 prod_name_19 10/29/2014 3:48:32 PM

20 prod_name_20 10/30/2014 3:48:32 PM

---------------------------------------------

----------------------------------------------

Implicit Cursor

----------------------------------------------

--will update soon

----------------------------------------------

Explicit Cursor

----------------------------------------------

**********************************************

Processing cursor data by using LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration
CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND; --<-- if next record not found means control will
come out from the loop

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )


DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

EXIT WHEN prod_detail_cur%FOUND; --<-- if next record found means control will come
out from the loop

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )


DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');


END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor Already closed

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;
LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

-->-- CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )


Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor closed

**********************************************

Processing cursor data by using WHILE LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

OPEN prod_detail_cur;

FETCH prod_detail_cur

INTO all_data;

WHILE prod_detail_cur%FOUND LOOP

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||


' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

FETCH prod_detail_cur

INTO all_data;

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

************************************************************

Processing cursor data by using FOR LOOP - CURSOR FOR LOOP

************************************************************

DECLARE

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN
FOR i IN prod_detail_cur

LOOP

dbms_output.put_line('Product id : ' || i.p_id ||

' Product Name : ' || i.p_name ||

' ( Orderd on : ' || TRIM(i.p_order_dt) || ' )');

END LOOP;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

Parameterized Cursor

*********************

This was used when you are going to use the cursor in more than one place with different
values for the same where clause.

Cursor parameters must be in mode.

Cursor parameters may have default values.


The scope of cursor parameter is within the select statement.

CREATE TABLE dep_details(d_id NUMBER,d_name VARCHAR2(30), location_id NUMBER);

BEGIN

INSRT INTO dep_details VALUES(001,'Admin',1010);

INSRT INTO dep_details VALUES(002,'HR',1010);

INSRT INTO dep_details VALUES(003,'Sales',1020);

INSRT INTO dep_details VALUES(004,'Marketing',1020);

commit;

END;

SELECT * FROM dep_details;

----------------------------

d_id d_name location_id

----------------------------

1 Admin 1010

2 HR 1010

3 Sales 1020

4 Marketing 1020

----------------------------
DECLARE

-->--Declaring parameterized cursor

CURSOR dep_det_c(p_location_id NUMBER) IS

SELECT * FROM dep_details d WHERE d.location_id = p_location_id;

all_data dep_details%ROWTYPE;

BEGIN

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

OPEN dep_det_c(1010);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

-->-- opening same cursor with different input value

OPEN dep_det_c(1020);

LOOP

FETCH dep_det_c
INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

END;

/*sample output*/

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 1 Department Name : Admin

Department id : 2 Department Name : HR

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 3 Department Name : Sales

Department id : 4 Department Name : Marketing

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Posted 21st October 2014 by Unknown

0 Add a comment
OCT

21

Handling Exception

Error Handling in oracle

ERROR

Any departure from the expected behavior of the system or program,

which stops the working of the system is an error.

Types : compile time error

Run time error

EXCEPTION

Any error or problem which one can handle and continue to work normally.

Handling Exception

When exception is raised, control passes to the exception section of the block.

i.e. EXCEPTION

WHEN name_of_exception THEN

Types : Pre Defined Exceptions

User Defined Exceptions


Predefined Exception

*********************

Oracle has predefined several exceptions that correspond to the most common oracle errors.

------------------------------------------------------------------------

Exception Oracle Error SQL Code Value

------------------------------------------------------------------------

ZERO_DIVIDE ORA-01476 -1476

NO_DATA_FOUND ORA-01403 +100

DUP_VAL_ON_INDEX ORA-00001 -1

TOO_MANY_ROWS ORA-01422 -1422

VALUE_ERROR ORA-06502 -6502

CURSOR_ALREADY_OPEN ORA-06511 -6511

OTHERS

------------------------------------------------------------------------

-->-- ZERO_DIVIDE --<--

Your program attempts to divide a number by zero.

DECLARE
v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN ZERO_DIVIDE THEN

dbms_output.put_line('Divisor is equal to zero');

END;

-->-- NO_DATA_FOUND --<--

Single row SELECT returned no rows or your program referenced a deleted element in a nested
table

or an uninitialized element in an associative array (index-by table).

CREATE TABLE test_tb(id NUMBER PRIMARY KEY);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN NO_DATA_FOUND THEN

dbms_output.put_line('There is no data inside the table');

END;
-->-- DUP_VAL_ON_INDEX --<--

A program attempted to insert duplicate values in a column that is constrained by a unique


index.

INSERT INTO test_tb VALUES (1);

INSERT INTO test_tb VALUES (2);

commit;

BEGIN

INSERT INTO test_tb VALUES (2);

EXCEPTION

WHEN DUP_VAL_ON_INDEX THEN

dbms_output.put_line('Duplicate values are not allowed');

END;

-->-- TOO_MANY_ROWS --<--

Single row SELECT returned multiple rows.

DECLARE
v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN TOO_MANY_ROWS THEN

dbms_output.put_line('Query returning more than one row');

END;

DROP TABLE test_tb;

-->-- VALUE_ERROR --<--

An arithmetic, conversion, truncation, or size constraint error occurred.

DECLARE

num1 NUMBER(2);

BEGIN

num1 := 345;

EXCEPTION

WHEN VALUE_ERROR THEN

dbms_output.put_line('check the size of the variable');

END;
-->-- CURSOR_ALREADY_OPEN --<--

A program attempted to open an already opened cursor.

CREATE TABLE emp(id NUMBER, name VARCHAR2(30));

BEGIN

INSERT INTO emp VALUES(1,'Name1');

INSERT INTO emp VALUES(2,'Name2');

INSERT INTO emp VALUES(3,'Name3');

INSERT INTO emp VALUES(4,'Name4');

COMMIT;

END;

SELECT * FROM emp;

DECLARE

cursor emp_c IS

SELECT * FROM emp;

all_data emp%ROWTYPE;

BEGIN

OPEN emp_c;

OPEN emp_c;
NULL;

CLOSE emp_c;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

END;

DROP TABLE emp;

-->-- OTHERS --<--

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

WHEN OTHERS THEN

dbms_output.put_line('Some other error ' || SQLERRM);

END;

User Defined Exception


**********************

A user-defined exception is an error that is defined by the programmer.

User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,

exceptions have a type EXCEPTION and scope.

DECLARE

v_gender CHAR := '&gender';

gender_ex EXCEPTION;

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE gender_ex;

END IF;

dbms_output.put_line('Gender : '||v_gender);

EXCEPTION

WHEN gender_ex THEN

dbms_output.put_line('Please Enter valid gender');

END;

create table test_insert (id NUMBER, Name VARCHAR2(30));

DECLARE
abort_ex EXCEPTION;

BEGIN

FOR i IN 1..100

LOOP

BEGIN

IF mod(i,10)=0 THEN

RAISE abort_ex;

END IF;

INSERT INTO test_insert VALUES(i, 'Name'||i);

EXCEPTION

WHEN abort_ex THEN

NULL;

END;

END LOOP;

COMMIT;

END;

SELECT * FROM test_insert;

DROP TABLE test_insert;

SQLERRM and SQLCODE

********************
SQLCODE returns the current error code, and SQLERRM returns the current error message
text;

For user-defined exception SQLCODE returns 1 and SQLERRM returns “user-defined


exception”.

SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.

CREATE TABLE test_tb (id NUMBER);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

dbms_output.put_line(v_id);

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('SQLERRM : ' || SQLERRM);

dbms_output.put_line('SQLCODE : ' || SQLCODE);

END;

/*sample output*/

SQLERRM : ORA-01403: no data found

SQLCODE : 100

DROP TABLE test_tb;


PRAGMA EXCEPTION_INIT

*********************

Using this you can associate a named exception with a particular oracle error.

This gives you the ability to trap this error specifically, rather than via an OTHERS handler.

Syntax:

PRAGMA EXCEPTION_INIT(exception_name, oracle_error_number);

DECLARE

v_result NUMBER;

PRAGMA EXCEPTION_INIT(Invalid, -1476);

BEGIN

SELECT 453 / 0 INTO v_result FROM dual;

dbms_output.put_line('Result : ' || v_result);

EXCEPTION

WHEN INVALID THEN

dbms_output.put_line('Invalid Exception');

END;
RAISE_APPLICATION_ERROR

************************

You can use this built-in function to create your own error messages, which can be more
descriptive than named exceptions.

Error Number :

Oracle Error Range : From -00000 to -19999

User Error Range : From -20000 to -20999

DECLARE

v_gender CHAR := '&gender';

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE_APPLICATION_ERROR(-20003, 'Enter valid gender');

END IF;

dbms_output.put_line('Gender : ' || v_gender);

END;

Posted 21st October 2014 by Unknown

1 View comments
RajmohanMarch 13, 2018 at 6:49 AM

How to get the two table data without using Joins and sub query,union?

Reply

OCT

Package

1. You can groups logical related subprogram (procedures and functions)

2. It consist of two parts

I) specification

II) Body

3. It allows the oracle server to read multiple object in to a memory once

4. You can declare global variable,cursor, user define exeption

5. Overloading

6. we can't create anonyms block inside the package

create table err_log(sno NUMBER, u_name VARCHAR2(30), error_msg CLOB, hap_tm


TIMESTAMP);
select * from err_log;

--stand alone procedure

CREATE OR REPLACE PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id


%TYPE) IS

v_salary employees.salary%TYPE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT salary,

first_name

INTO v_salary,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line('Salary of ' || v_first_name || ' is ' || v_salary);

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,
systimestamp);

commit;

END emp_sal_sp;

BEGIN

-- Call the procedure

emp_sal_sp(p_employee_id => :p_employee_id);

END;

CREATE OR REPLACE PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id


%TYPE) IS

v_hire_date DATE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT hire_date,

first_name

INTO v_hire_date,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line(v_first_name || ' hired on ' || to_char(v_hire_date,'month ddth,


yyyy'));

EXCEPTION
WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_hdt_sp;

BEGIN

-- Call the procedure

emp_hdt_sp(p_employee_id => :p_employee_id);

END;

create or replace function sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER

IS

v_c NUMBER;

BEGIN

v_c := p_a + p_b;


RETURN v_c;

END;

--Specification Part

CREATE OR REPLACE PACKAGE emp_pkg

IS

PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id%TYPE);

PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id%TYPE);

FUNCTION sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER;

END emp_pkg ;

--Body Part

CREATE OR REPLACE PACKAGE BODY emp_pkg

IS

PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id%TYPE) IS


v_salary employees.salary%TYPE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT salary,

first_name

INTO v_salary,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line('Salary of ' || v_first_name || ' is ' || v_salary);

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_sal_sp;

PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id%TYPE) IS


v_hire_date DATE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT hire_date,

first_name

INTO v_hire_date,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line(v_first_name || ' hired on ' || to_char(v_hire_date,'month ddth,


yyyy'));

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_hdt_sp;

FUNCTION sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER
IS

v_c NUMBER;

BEGIN

v_c := p_a + p_b;

RETURN v_c;

END;

END emp_pkg;

A package specification can exist without a package body, but

a package body can't exist without a package specification.

--Executing procedure inside the package

BEGIN

emp_pkg.emp_sal_sp(120);

END;

--Executing function inside the package

SELECT emp_pkg.sum_fn(23,567) FROM dual;


-- You can declare global variable,cursor, user define exeption

create or replace package all_detail

as

PROCEDURE emp2sal (a IN NUMBER);

PROCEDURE emp2exep (a IN NUMBER);

FUNCTION add2num (a IN NUMBER, b IN NUMBER)

RETURN NUMBER;

c NUMBER(8); --global declaration

abort_ex EXCEPTION; --global exception declaration

CURSOR emp_rec --global cursor declaration

IS

SELECT first_name, salary, hire_date, department_id

FROM employees;

End all_detail;

create or replace package body all_detail

as
PROCEDURE emp2sal (a IN NUMBER)

AS

BEGIN

SELECT salary

INTO c

FROM Employees

WHERE Employee_id = a;

Dbms_output.put_line('Salary of Employee ' || a || ' is ' || c);

EXCEPTION

WHEN no_data_found THEN

Dbms_output.put_line('Please enter valid id');

END emp2sal;

PROCEDURE emp2exep (a IN NUMBER)

AS

BEGIN

SELECT Round(Months_between(sysdate,hire_date)/12)

INTO c

FROM Employees

WHERE Employee_id = a;

Dbms_output.put_line( c || ' Years');


EXCEPTION

WHEN no_data_found THEN

Dbms_output.put_line('Please enter valid id');

END emp2exep;

FUNCTION add2num (a IN NUMBER, b IN NUMBER)

RETURN NUMBER

AS

BEGIN

c := a+b;

RETURN C;

END;

End all_detail;

/*Declaring a Bodiless Package */

CREATE OR REPLACE PACKAGE global_constant

IS

mile_2_kilo CONSTANT NUMBER := 1.6093;

kilo_2_mile CONSTANT NUMBER := 0.6214;


yard_2_meter CONSTANT NUMBER := 0.9144;

meter_2_yard CONSTANT NUMBER := 1.0936;

END global_constant;

BEGIN

DBMS_OUTPUT.PUT_LINE('20 miles = ' || 20*global_constant.mile_2_kilo||' km');

END;

/*Forward Declaration in package */

DECLARE

PROCEDURE P2; -- forward declaration

PROCEDURE P3;

PROCEDURE P1 IS

BEGIN

dbms_output.put_line('From procedure p1');

p2;

END P1;

PROCEDURE P2 IS

BEGIN

dbms_output.put_line('From procedure p2');


p3;

END P2;

PROCEDURE P3 IS

BEGIN

dbms_output.put_line('From procedure p3');

END P3;

BEGIN

p1;

END;

sample output:

From procedure p1

From procedure p2

From procedure p3

Drop package package_name;

Drop package body package_name;

SELECT text FROM user_source u

WHERE u.name = 'EMP_PKG';


Interview Questions:

What is package?

Advantage of package

Is it possible to create package body with out package specification?

what is package overloading?

what is forward declaration in package?

which data dictionary table contain source code of package?

How to declare global variable, exception and cursor?

How to execute procedure and function inside the package?

Posted 4th October 2014 by Unknown

0 Add a comment

OCT

%TYPE and %ROWTYPE

--%type is used to fetch the data type of the particular column


create table product_details

p_id NUMBER(3),

p_nm VARCHAR2(30),

p_qty NUMBER(8),

order_dt DATE

);

BEGIN

INSERT INTO product_details VALUES(100,'Name0',400,'23-Mar-13');

INSERT INTO product_details VALUES(101,'Name1',600,'26-Apr-13');

INSERT INTO product_details VALUES(102,'Name2',800,'27-Jan-12');

INSERT INTO product_details VALUES(103,'Name3',300,'23-Jul-11');

INSERT INTO product_details VALUES(104,'Name4',200,'22-Aug-11');

INSERT INTO product_details VALUES(105,'Name5',500,'25-Oct-12');

commit;

END;

SELECT * FROM product_details;

------------------------------------
P_ID P_NM P_QTY ORDER_DT

------------------------------------

100 Name0 400 03/23/2013

101 Name1 600 04/26/2013

102 Name2 800 01/27/2012

103 Name3 300 07/23/2011

104 Name4 200 08/22/2011

105 Name5 500 10/25/2012

------------------------------------

DECLARE

v_name VARCHAR2(4);

BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 100;

dbms_output.put_line('Product Name : ' || v_name);

--error numeric or value error

END;

DECLARE
v_name VARCHAR2(5);

BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 100;

dbms_output.put_line('Product Name : ' || v_name);

END;

ALTER TABLE product_details

MODIFY p_nm VARCHAR2(15);

INSERT INTO product_details

VALUES

(106,

'name6',

700,

'26-Dec-12');

commit;
106 name6 700 12/26/2012

DECLARE

v_name VARCHAR2(5);

BEGIN

SELECT p_nm INTO v_name

FROM product_details

WHERE p_id = 106;

dbms_output.put_line('Product Name : ' || v_name);

--error

END;

DECLARE

v_name product_details.p_nm%TYPE;

BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 106;

dbms_output.put_line('Product Name : ' || v_name);


END;

DROP TABLE product_details;

DECLARE

dep_id departments.department_id%TYPE;

dep_name departments.department_name%TYPE;

dep_man_id departments.manager_id%TYPE;

dep_loc_id departments.location_id%TYPE;

BEGIN

SELECT department_id,

department_name,

manager_id,

location_id

INTO dep_id,

dep_name,

dep_man_id,

dep_loc_id

FROM departments
WHERE department_id = 10;

dbms_output.put_line('Department_id : ' || dep_id);

dbms_output.put_line('Department_name : ' || dep_name);

dbms_output.put_line('Manager_id : ' || dep_man_id);

dbms_output.put_line('Location_id : ' || dep_loc_id);

END;

--%rowtype is used to fetch the data type of all the column

--Insted of using %type if we use %rowtype means we can reduce the no of variables that we
declare

DECLARE

dep_detail departments%ROWTYPE;

BEGIN

SELECT *

INTO dep_detail

FROM departments

WHERE department_id = 10;


dbms_output.put_line('Department_id : ' || dep_detail.department_id);

dbms_output.put_line('Department_name : ' || dep_detail.department_name);

dbms_output.put_line('Manager_id : ' || dep_detail.manager_id);

dbms_output.put_line('Location_id : ' || dep_detail.location_id);

END;

DROP TABLE dept_details;

CREATE TABLE dept_details

dept_id number(3) ,

dept_name varchar2(30),

dept_manager_name varchar2(30)

);

insert into dept_details values(10,'dept1','manager_name1');

insert into dept_details values(20,'dept2','manager_name2');

SELECT * FROM dept_details;

-------------------------------------------------------
| DEPT_ID | DEPT_NAME | DEPT_MANAGER_NAME |

+------------+-----------------------+-----------------

| 10 | dept1 | manager_name1 |

| 20 | dept2 | manager_name2 |

------------+-----------------------+------------------

DECLARE

all_data dept_details%ROWTYPE;

BEGIN

all_data.dept_id := 100;

all_data.dept_name := 'Admin';

all_data.dept_manager_name := 'John';

UPDATE dept_details

SET ROW = all_data

WHERE dept_id = 10;

dbms_output.put_line(SQL%ROWCOUNT || ' Row(s) get updated');

END;

/
1 Row(s) get updated

select * from dept_details;

---------------------------------------------------

| DEPT_ID | DEPT_NAME | DEPT_MANAGER_NAME|

---------------------------------------------------

| 100 | Admin | John |

| 20 | dept2 | manager_name2 |

---------------------------------------------------

Interview Question :

1. What is the use of %TYPE?

2. What is the use of %ROWTYPE?

3. Difference between %TYPE and %ROWTYPE?

Posted 2nd October 2014 by Unknown

0 Add a comment
SEP

29

BULK Exceptions

/************************************************************************

* Handling Exceptions in Bulk Operations *

* Documented on 29-SEP-14 04.35.35.980894 PM +05:30 *

* Document By : Murugappan Annamalai *

* Reference : http://www.dba-oracle.com/plsql/t_plsql_exceptions.htm *

************************************************************************/

CREATE TABLE bulk_tb (ran_num NUMBER NOT NULL);

--inserting data using bulk collect

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;
v_dat(v_dat.LAST) := i;

END LOOP;

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

commit;

END;

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

200

TRUNCATE TABLE bulk_tb;

sample2.sql --without exception part

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;


v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

commit;

END;

/*

Error Message :

ORA-01400: cannot insert NULL into ("HR"."bulk_tb"."ran_num")

ORA-06512: at line 15

*/
sample2.sql --with exception part

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

BEGIN

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

COMMIT;

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('Error while inserting bulk record '||SQLERRM);

END;
END;

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

99

SQL%BULK_EXCEPTIONS(i).ERROR_INDEX

Holds the iteration (not the subscript) of the original FORALL statement that raised the
exception.

In sparsely populated collections,

the exception row must be found by looping through the original collection the correct
number of times.

SQL%BULK_EXCEPTIONS(i).ERROR_CODE

Holds the exceptions error code.

The total number of exceptions can be returned using the collections COUNT method,
which returns zero if no exceptions were raised. The save_exceptions.sql script,

a modified version of the handled_exception.sql script, demonstrates this functionality.

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

v_ex_count NUMBER(4);

abort_ex EXCEPTION;

PRAGMA EXCEPTION_INIT(abort_ex, -24381);

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

v_dat(150) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

EXECUTE IMMEDIATE 'TRUNCATE TABLE bulk_tb';


BEGIN

FORALL i IN v_dat.FIRST..v_dat.LAST SAVE EXCEPTIONS

INSERT INTO bulk_tb VALUES(v_dat(i));

COMMIT;

EXCEPTION

WHEN abort_ex THEN

v_ex_count := SQL%BULK_EXCEPTIONS.COUNT;

FOR i IN 1..v_ex_count LOOP

dbms_output.put_line('Error: ' || i ||' Array Index: ' || SQL


%BULK_EXCEPTIONS(i).error_index ||

' Message: ' || SQLERRM(SQL%BULK_EXCEPTIONS(i).ERROR_CODE));

END LOOP;

END;

END;

/*

Sample output:

Error: 1 Array Index: 100 Message: -1400: non-ORACLE exception

Error: 2 Array Index: 150 Message: -1400: non-ORACLE exception

*/
SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

198

SAVE EXCEPTIONS clause being removed, in the above script now traps a different error number.

The output from this script is listed below.

/*

Sample output:

Error: 1 Array Index: 100 Message: -1400: non-ORACLE exception

*/

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

99
SELECT COUNT(*) FROM bulk_tb;

DROP TABLE bulk_tb;

Posted 29th September 2014 by Unknown

0 Add a comment

SEP

29

Cursor - FOR UPDATE

/************************************************************************

* FOR UPDATE clause in oracle *

* Document By : Murugappan Annamalai *

************************************************************************/

create table prod_details(p_id VARCHAR2(30), P_name VARCHAR2(30));


BEGIN

--Inserting data into prod_details table

FOR i IN 1..50 LOOP

INSERT INTO prod_details VALUES(i,'pname'||i);

END LOOP;

commit;

END;

SELECT * FROM prod_details;

DECLARE

CURSOR PROD_DTLS_C IS

SELECT * FROM PROD_DETAILS T1 FOR UPDATE OF P_ID;

V_PID PROD_DETAILS.P_ID%TYPE;

V_PRDNAME PROD_DETAILS.P_NAME%TYPE;

BEGIN

OPEN PROD_DTLS_C;

LOOP

FETCH PROD_DTLS_C INTO V_PID, V_PRDNAME;


IF PROD_DTLS_C%NOTFOUND THEN

EXIT;

ELSE

UPDATE PROD_DETAILS P

SET P.P_ID = LPAD(P_ID, 10, 0)

WHERE CURRENT OF PROD_DTLS_C;

END IF;

END LOOP;

CLOSE PROD_DTLS_C;

COMMIT;

END;

select * from PROD_DETAILS;

TRUNCATE TABLE prod_details;

BEGIN

--Inserting data into prod_details table

FOR i IN 1..50 LOOP

INSERT INTO prod_details VALUES(i,'pname'||i);


END LOOP;

commit;

END;

DECLARE

CURSOR PROD_DTLS_C IS

SELECT * FROM PROD_DETAILS T1 FOR UPDATE OF P_ID;

V_PID PROD_DETAILS.P_ID%TYPE;

V_PRDNAME PROD_DETAILS.P_NAME%TYPE;

BEGIN

OPEN PROD_DTLS_C;

LOOP

FETCH PROD_DTLS_C INTO V_PID, V_PRDNAME;

IF PROD_DTLS_C%NOTFOUND THEN

EXIT;

ELSE

UPDATE PROD_DETAILS P
SET P.P_ID = LPAD(P_ID, 10, 0)

WHERE CURRENT OF PROD_DTLS_C;

END IF;

COMMIT;

END LOOP;

CLOSE PROD_DTLS_C;

--COMMIT;

END;

select * from PROD_DETAILS;

Posted 29th September 2014 by Unknown

0 Add a comment

MAY

28

Escape Sequence in Oracle

Escape special characters when writing SQL queries


--to include single '

SELECT 'Steven's salary is more than 50k INR' AS "SAL_DETAILS"

FROM Dual;

ORA-01756 : quoted string not properly terminated

SELECT 'Steven''s salary is more than 50k INR' AS "SAL_DETAILS"

FROM Dual;

SAL_DETAILS

---------------------------------------

Steven's salary is more than 50k INR

--to include double '

SELECT 'You can print double quot ('''') in oracle' "Info"

FROM Dual;

Info

---------------------------------------
You can print double quot ('') in oracle

SELECT q'[some test ' some test ' some text ']' AS "In 10g"

FROM dual;

In 10g

------------------------------------

some test ' some test ' some text '

--Escape wild card characters ( _ and % )

The LIKE keyword allows for string searches.

The '_' wild card character is used to match exactly one character

While '%' is used to match zero or more occurrences of any characters.

These characters can be escaped in SQL as follows.

WITH mail_ids AS

SELECT 'an.murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an_murugappan@gmail.com' mail FROM Dual

UNION
SELECT 'an%murugappan@gmail.com' mail FROM Dual

SELECT * FROM mail_ids

WHERE mail LIKE '__$_%' ESCAPE '$';

mail

----------------------------------

an_murugappan@gmail.com

WITH mail_ids AS

SELECT 'an.murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an_murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an%murugappan@gmail.com' mail FROM Dual

SELECT * FROM mail_ids

WHERE mail LIKE '__/%%' ESCAPE '/';

mail

----------------------------------

an%murugappan@gmail.com
Escape ampersand (&) characters in SQL*Plus

SQL> select '&a' FROM dual;

'23'

----

23

SQL> SET ESCAPE '\'

SQL> select '\&a' FROM dual;

'&A'

----

&a

SQL> SET SCAN OFF;

SQL> select '&a' FROM dual;

'&A'

----

&a
SQL> SET SCAN ON;

SQL> select '&a' FROM dual;

'45'

----

45

Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Data Manipulation Language

Data Manipulation Language (DML) statements are used for managing data within schema
objects. Some examples:

INSERT - insert data into a table

UPDATE - updates existing data within a table

DELETE - deletes all records from a table, the space for the records remain

MERGE - UPSERT operation (insert or update)


CREATE TABLE prod_details

prod_id NUMBER(4) ,

prod_name VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

Deliver_dt DATE DEFAULT SYSDATE+3 ,

comments VARCHAR2(300)

);

SELECT * FROM prod_details;

no_data_found

INSERT

INSERT INTO prod_details(prod_id,prod_name,order_dt,deliver_dt,comments)

VALUES(100,'Apple iphone 5s','21-May-14','24-May-14','Color : Black');

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black


---------------------------------------------------------------------------

--Inserting records with out mentioning column name

INSERT INTO prod_details

VALUES(101,'Samsung Galaxy III','20-Aug-14','23-Aug-14','Color : White');

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

---------------------------------------------------------------------------

--Inserting selective number of values

INSERT INTO prod_details

VALUES(103,'Moto X','11-May-14','13-May-14');

ORA-00947 : not enough values

--While inserting selective number of values mentioning column name is compulsory.


INSERT INTO prod_details (prod_id,prod_name,order_dt,deliver_dt)

VALUES(103,'Moto X','11-May-14','13-May-14');

SELECT * FROM prod_details;

--------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

--------------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

--------------------------------------------------------------------------------

--Inserting NULL value.

--If you want to insert NULL value you can ignore that column at the time of inserting

--or we can use NULL keyword to insert NULL.

INSERT INTO prod_details

VALUES(104,'Moto G','19-May-14','22-May-14',NULL);

SELECT * FROM prod_details;

---------------------------------------------------------------------------
PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Noto G 5/19/2014 5/22/2014

---------------------------------------------------------------------------

--if you are not providing values for order_dt and deliver_dt column default value can be taken.

INSERT INTO prod_details(prod_id,prod_name,comments)

VALUES(105,'Nokia Lumis 720p','Color : Red');

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

----------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Moto G 5/19/2014 5/22/2014

105 Nokia Lumis 720p 5/26/2014 5/29/2014 Color : Red

---------------------------------------------------------------------------
--Inserting data by using sub query

CREATE TABLE test_tab (id NUMBER, Name VARCHAR2(30));

INSERT INTO test_tab VALUES(1,'Name1');

INSERT INTO test_tab VALUES(2,'Name2');

INSERT INTO test_tab VALUES(3,'Name3');

SELECT COUNT(*) FROM test_tab;

COUNT(*)

-------

--creating table by using sub query (with out data)

CREATE TABLE ins_chk

SELECT * FROM test_tab

WHERE id = 900;
SELECT COUNT(*) FROM ins_chk;

COUNT(*)

-------

--Inserting data by using sub query

--copying data from test_tab to ins_chk

INSERT INTO ins_chk (SELECT * FROM test_tab);

3 rows inserted in 0.047 seconds.

SELECT COUNT(*) FROM ins_chk;

COUNT(*)

-------

DROP TABLE test_tab;

DROP TABLE ins_chk;


UPDATE

Syntax :

UPDATE table_name

SET column1_name = column1_value,

column2_name = column2_value,

column2_name = column3_value,

columnn_name = columnn_value

WHERE condition(s);

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

----------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Moto G 5/19/2014 5/22/2014

105 Nokia Lumis 720p 5/26/2014 5/29/2014 Color : Red

---------------------------------------------------------------------------
UPDATE prod_details ps

SET ps.prod_name = 'iphone 5s'

WHERE ps.prod_id = 100;

1 row updated in 0.031 seconds

SELECT *

FROM prod_details ps

WHERE ps.prod_id = 100;

--------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

--------------------------------------------------------------------

100 iphone 5s 5/21/2014 5/24/2014 Color : Black

--------------------------------------------------------------------

--update statement with out condition

--If you try to execute update statement without condition it'll update all the records inside the
table.

UPDATE prod_details ps

SET ps.comments = 'None';

5 row updated in 0.031 seconds


SELECT *

FROM prod_details ps;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 None

101 Samsung Galaxy III 8/20/2014 8/23/2014 None

103 Moto X 5/11/2014 5/24/2014 None

104 Moto G 5/19/2014 5/22/2014 None

105 Nokia Lumis 720p 5/26/2014 5/29/2014 None

----------------------------------------------------------------------

--if your update text contain ' means you can use following metnod (use '')

UPDATE prod_details ps

SET ps.comments = 'Some product''s are not available'

WHERE ps.prod_id = 100;

1 row updated in 0.031 seconds

SELECT *

FROM prod_details ps
WHERE ps.prod_id = 100;

------------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

------------------------------------------------------------------------------------

100 iphone 5s 5/21/2014 5/24/2014 Some product's are not available

------------------------------------------------------------------------------------

DELETE

Syntax:

DELETE FROM table_name

WHERE condition(s);

DELETE FROM prod_details

WHERE prod_id IN (104, 105);

2 row(S) deleted in 0.032 seconds

SELECT *

FROM prod_details ps;


---------------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Some product's are not available

101 Samsung Galaxy III 8/20/2014 8/23/2014 None

103 Moto X 5/11/2014 5/24/2014 None

---------------------------------------------------------------------------------------

DELETE FROM prod_details;

3 row(s) deleted in 0.062 seconds.

SELECT * FROM prod_details;

no rows selected.

DROP TABLE prod_details;

MERGE = Insert + Update

-- will update soon.

Posted 28th May 2014 by Unknown


0 Add a comment

MAY

28

Data Define Language

Data Definition Language (DDL) statements are used to define the database structure or schema.

Some examples:

CREATE - to create objects in the database.

ALTER - alters the structure of the database.

ADD

RENAME

MODIFY

DROP

DROP - delete objects from the database

TRUNCATE - remove all records from a table,

including all spaces allocated for the records are removed.

COMMENT - add comments to the data dictionary.

RENAME - rename an object.


Creating Table

--------------------------------------------------------------------------

Data Types Size Default Size Explanation

--------------------------------------------------------------------------

NUMBER(P,S) P: 1 to 38 we can store number between 0-9

S: -84 to 127

VARCHAR2 4000 Bytes we can store 0-9, a-z, A-Z and special characters

CHAR 2000 Bytes 1

DATE 7 Used to store Date

TIMESTAMP Includes year, month, day, hour, minute, and seconds.

LONG 2 GB Only one long column is allowed in a table.

We can't use this column in ORDER BY clause.

CLOB 4 GB Character Large Object

BLOB Binary Larger Object

--------------------------------------------------------------------------

CREATE

ALTER : ADD RENAME MODIFY DROP RENAME

RENAME

DROP

TRUNCATE
--creating table

CREATE TABLE friends_details_tb

Name VARCHAR2(30) ,

Phone NUMBER(10) ,

Gender CHAR ,

dob DATE ,

other_details LONG ,

make_dtm TIMESTAMP

);

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

-----------------------------
--maximum you can keep 255 columns in a table

ALTER : Colum level operations

ADD RENAME MODIFY DROP

ADD : Used to add a column after the table hase been created

ALTER TABLE friends_details_tb

ADD email VARCHAR2(30);

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

EMAIL VARCHAR2(30)
-----------------------------

--adding multiple columns by using single ALTER statement

SYNTAX

ALTER TABLE friends_details_tb

ADD (

column_1 Data_type(size),

column_2 Data_type(size),

column_3 Data_type(size),

column_4 Data_type(size)

);

RENAME : Used to Rename a column

ALTER TABLE friends_details_tb

RENAME COLUMN email TO email_id;

DESC friends_details_tb;

-----------------------------
NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

MODIFY : Used to change the data type or size of the data type.

ALTER TABLE friends_details_tb

MODIFY other_details CLOB;

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)
GENDER CHAR(1)

DOB DATE

OTHER_DETAILS CLOB

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

--Modifying multiple columns at a time

ALTER TABLE friends_details_tb

MODIFY ( column_name_1 old_datatype(new_size),

column_name_2 new_datatype(old_size),

column_name_3 new_datatype(new_size)

);

DROP : Used to drop the column after the table has been created.

ALTER TABLE friends_details_tb

DROP COLUMN other_details;

DESC friends_details_tb;

-----------------------------
NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

RENAME : Used to Rename a particular table.

SYNTAX

RENAME old_table_name TO new_table_name;

RENAME friends_details_tb TO fnd_det;

DESCRIBE fnd_det;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)
PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

TRUNCATE : Used to remove the entire content of the table (not a structure)

SYNTAX

TRUNCATE TABLE table_name;

TRUNCATE TABLE fnd_det;

DROP : Used to drop the tabel (Data + stucture of the table get removed from the database )

DROP TABLE fnd_det;

*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Statements in Oracle

Data Definition Language (DDL)

DDL statements are used to define the database structure or schema. Some examples:

CREATE - to create objects in the database

ALTER - alters the structure of the database

ADD

RENAME

MODIFY

DROP

DROP - delete objects from the database

TRUNCATE - remove all records from a table,

including all spaces allocated for the records are removed

RENAME - rename an object

Data Manipulation Language (DML)


DML statements are used for managing data within schema objects. Some examples:

INSERT - insert data into a table

UPDATE - updates existing data within a table

DELETE - deletes all records from a table, the space for the records remain

MERGE - UPSERT operation (insert or update)

Data Control Language (DCL)

DCL statements. Some examples:

GRANT - gives users access privileges to database

REVOKE - withdraw access privileges given with the GRANT command

Transaction Control (TCL)

TCL statements are used to manage the changes made by DML statements. It allows
statements to be grouped together into logical transactions.

COMMIT - save work done

SAVEPOINT - identify a point in a transaction to which you can later roll back

ROLLBACK - restore database to original since the last COMMIT


Posted 28th May 2014 by Unknown

0 Add a comment

MAY

19

DECODE and CASE statement

CREATE TABLE students (

roll_no NUMBER(4) ,

Name VARCHAR2(30) ,

dept_cd VARCHAR2(20) ,

total_marks NUMBER(3)

);

BEGIN

INSERT INTO students VALUES (2000,'Rahul','CSE',480);

INSERT INTO students VALUES (2001,'Bala','IT', 390);

INSERT INTO students VALUES (2002,'Ramesh','CSE',250);

INSERT INTO students VALUES (2003,'Karthi','EEE',185);

INSERT INTO students VALUES (2004,'Ravi','IT',345);

END;
/

SELECT * FROM students;

DECODE

Decode is a function. Its a Oracle one.

Works like IF-THEN-ELSE.

You can use DECODE only in SELECT clause.

In DECODE you can include 255 things include Exep, search , result and default value.

Example

SELECT roll_no,

NAME,

dept_cd,

DECODE(dept_cd,

'CSE',

'Computer Science and Engineering',

'IT',

'Information Technology',

'Default Value') AS "DEPARTMENT NAME"

FROM students;

Sample Output
------------------------------------------------------------

ROLL_NO NAME DEPT_CD DEPARTMENT NAME

------------------------------------------------------------

2000 Rahul CSE Computer Science and Engineering

2001 Bala IT Information Technology

2002 Ramesh CSE Computer Science and Engineering

2003 Karthi EEE Default Value

2004 Ravi IT Information Technology

------------------------------------------------------------

CASE

CASE is an expression. Its a ANSI standard.

Compare to DECODE case will be more faster.

Example

SELECT roll_no,

NAME,

dept_cd,

total_marks,

CASE

WHEN total_marks > 500 THEN

'A Grade'

WHEN total_marks > 400 THEN

'B Grade'
WHEN total_marks > 300 THEN

'C Grade'

ELSE

'U Grade'

END AS "GRADE"

FROM students;

-----------------------------------------------

ROLL_NO NAME DEPT_CD TOTAL_MARKS GRADE

-----------------------------------------------

2000 Rahul CSE 480 B Grade

2001 Bala IT 390 C Grade

2002 Ramesh CSE 250 U Grade

2003 Karthi EEE 185 U Grade

2004 Ravi IT 345 C Grade

-----------------------------------------------

Interview Questions:

What is DECODE?

What is CASE?

Difference between CASE and DECODE? Which one is faster?

Posted 19th May 2014 by Unknown


0 Add a comment

MAY

19

Sub Query

Query with in another query

1. Single Row sub query

2. Multi row Sub query

select * from employees;

Want to fetch the person Who are all getting salary more than Neena's salary ?

Neena's Salary : 17000

Select First_name, salary

From Employees

Where salary > 17000;


--change in Neena's salary won't work for the above query.

Select salary From Employees

Where First_name = 'Neena';

Sub Query :

Select First_name, salary

From Employees

Where salary > (

Select salary From Employees

Where First_name = 'Neena'

);

Select * from employees;

Select salary From Employees

Where First_name = 'Alexander';

Sub Query Returns one value it is called as Single row sub query
Sub Query Returns more than one value it is called as Multi row sub query

Single row sub query operators :

> < >= <= = <>

Multiple Row Sub query operators :

IN ALL ANY

Who are all getting salary more than the average salary?

Select

First_name,

Salary

From

Employees

WHERE

Salary > (

SELECT Round(avg(salary),0)

FROM Employees

);
Multiple Row Sub query (In ANY ALL)

Select First_name,Department_id, salary

From Employees

Where salary in(

Select Salary From Employees

Where First_name = 'Alexander'

);

Any : Minimum Value will be taken (3100)

Select First_name,Department_id, salary

From Employees

Where salary > ANY(

Select Salary From Employees

Where First_name = 'Alexander'

);

All : Maximum Value will be taken (9000)

Select First_name,Department_id, salary

From Employees

Where salary > All(

Select Salary From Employees

Where First_name = 'Alexander'


);

We can use sub query in all the classes except Group by and order by class.

Select

From

Where

-----------Group by

having

-----------Order by

SELECT

( Select Count(*) from Employees Where Department_id = 90 )Executive,

( Select Count(*) from Employees Where Department_id = 60 ) IT,

( Select Count(*) from Employees Where Department_id = 10 ) Administration,

( Select Count(*) from Employees Where Department_id = 100) Finance

FROM

Dual;

Select Min(salary) From Employees;

Select Min(salary) from

(
Select * from Employees

Where Department_id = 60

);

What is INLINE VIEW?

If u use sub query in From it is call it is as INLINE VIEW.

Intermediate result set

Correlated sub query

SELECT employee_number, name

FROM employees Bob

WHERE salary > (

SELECT AVG(salary)

FROM employees

WHERE department = Bob.department

);

Posted 19th May 2014 by Unknown

0 Add a comment
Loading

Dynamic Views theme. Powered by Blogger.

Oracle sql & Pl/sql

search

Home Sql and pl/sql Sql Interview Questions

JUL

20

INLINE view in Oracle with 12c New Features

Named sub Query in FROM clause is call it as INLINE VIEW.

Oracle process a inline view faster than sub query

Inline View in Oracle

--Query to display all the employees who are all getting salary more than their department
average salary

SELECT First_name

, last_name

, salary

, department_id
FROM employees a , ( SELECT b.department_id

, AVG(b.salary) avg_sal

FROM employees b

GROUP BY b.department_id

)b

WHERE a.department_id = b.department_id

AND a.salary > b.avg_salary;

Display all the customer who have placed more number of orders by using INLINE view

CREATE TABLE customer_order_det_tb

( custm_id NUMBER ,

custm_nm VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

ttl_amt NUMBER(7,2)

);

BEGIN

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '11-Jul-15' , 45000.00);

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '14-Jul-15' , 27000.00);

INSERT INTO customer_order_det_tb VALUES(101, 'Raja' , '13-Jul-15' , 17000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 34000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 38000.00);

COMMIT;
END;

SELECT c.*

FROM customer_order_det_tb c;

--------------------------------------------

custm_id custm_nm order_dt ttl_amt

--------------------------------------------

100 Murugappan 7/11/2015 45000.00

100 Murugappan 7/14/2015 27000.00

101 Raja 7/13/2015 17000.00

102 Ramesh 7/15/2015 34000.00

102 Ramesh 7/15/2015 38000.00

--------------------------------------------

--Writing a Quer to display all the customer who have placed maximum number of order

--Query #1 for inline view

SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC;


--------------------------------

custm_id custm_nm total_odr

--------------------------------

100 Murugappan 2

102 Ramesh 2

101 Raja 1

--------------------------------

--Query #2 for inline view

SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm;

----------

total_odr

----------

----------

Inline view to find all the customers who have placed maximum number of orders

/****************************************

Syntax
SELECT * FROM <query1> x, <query2> y

WHERE contition;

****************************************/

SELECT query1.* FROM

( SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC

) query1,

( SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm

) query2

WHERE query1.total_odr = query2.total_odr;

-------------------------------

custm_id custm_nm total_odr

-------------------------------

100 Murugappan 2

102 Ramesh 2

-------------------------------

DROP TABLE customer_order_det_tb;


--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT

SELECT first_name, salary

FROM ( SELECT first_name, salary

FROM employees e

WHERE job_id NOT IN ('SALESMAN','PRESIDENT')

ORDER BY salary DESC

WHERE ROWNUM < 4;

New Oracle 12c Inline view Syntax

LATERAL clause for In-line views

Allows for columns in the inline view to be accessed!!

Example :

--in 11g

SELECT * FROM employees e, (

SELECT *

FROM departments d

WHERE e.department_id = d.department_id);


ORA-0090: "E"."DEPARTMENT_ID": Invalid Identifier

--in 12c

SELECT * FROM employees e, LATERAL(

SELECT *

FROM departments d

WHERE e.department_id = d.department_id

);

--in 11g

WITH t

AS

( SELECT LEVEL a

FROM dual

CONNECT BY LEVEL <= 30)

SELECT *

FROM t, (SELECT *

FROM employees

WHERE department_id = t.a

);

ORA-00904: "T"."A": invalid Identifier


--in 12c

WITH t

AS

(SELECT LEVEL a FROM dual CONNECT BY LEVEL <= 30)

SELECT * FROM t,

LATERAL(SELECT *

FROM employees

WHERE department_id = t.a);

Hope you have enjoyed this little article

Feed backs are always Welcome :) (:

Posted 20th July 2015 by Unknown

0 Add a comment

JAN

23

Salary Related Questions in Oracle

--creating table
CREATE TABLE employee_data

eid NUMBER(4),

ename VARCHAR2(30),

depno NUMBER(3),

salary NUMBER(8)

);

BEGIN

--Inserting records

INSERT INTO employee_data VALUES(1000,'Name01',90,30000);

INSERT INTO employee_data VALUES(1001,'Name02',90,6000);

INSERT INTO employee_data VALUES(1002,'Name03',90,23000);

INSERT INTO employee_data VALUES(1003,'Name04',60,35000);

INSERT INTO employee_data VALUES(1004,'Name05',60,60000);

INSERT INTO employee_data VALUES(1005,'Name06',60,30000);

INSERT INTO employee_data VALUES(1006,'Name07',80,36000);

INSERT INTO employee_data VALUES(1007,'Name08',80,29000);

INSERT INTO employee_data VALUES(1008,'Name09',80,37000);

INSERT INTO employee_data VALUES(1009,'Name10',80,41000);

COMMIT;

END;
/

SELECT * FROM employee_data

ORDER BY salary DESC;

--query to find maximum salary from employee_data table

SELECT MAX(salary) FROM employee_data;

--query to find minimum salary from employee_data table

SELECT MIN(salary) FROM employee_data;

--query to find second maximum salary from employee_data table

SELECT MAX(salary)

FROM employee_data

WHERE salary NOT IN (SELECT MAX(salary)

FROM employee_data);

--query to select 5th maximum salary

SELECT MIN(salary)

FROM (SELECT salary


FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= 5);

--query to select nth maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= &n);

--query to select all the details of the employee whose getting nth maximum salary

SELECT *

FROM (SELECT emp.*,

rownum rn

FROM (SELECT *

FROM employee_data

ORDER BY salary DESC) emp)

WHERE rn = 9;
--same query using row_numbr( ) function

SELECT *

FROM (SELECT emp.*,

row_number() over(ORDER BY salary) rank

FROM employee_data emp)

WHERE rank = 9;

--same query using rank( ) function

SELECT *

FROM (SELECT emp.*,

rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--same query using dense_rank( ) function

SELECT *

FROM (SELECT emp.*,

dense_rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;
--query to display display maximum salary in all the department

SELECT e.depno "Department id",

MAX(salary) "Maximum Salary"

FROM employee_data e

GROUP BY e.depno;

--query to display all the employees who are all getting salary more than average salary of the
company

SELECT e.* FROM employee_data e

WHERE salary > (SELECT AVG(salary) FROM employee_data);

--query to display all the employees who are all getting salary more than their department
average salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE department_id = OUT.department_id);


--query to display all the employees who are all getting salary more than their manager salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE employee_id = OUT.manager_id);

Documented By : Murugappan Annamalai

Posted on : 23-Jan-15 16:34:00 IST.

Hope you have enjoyed this little article

Feed backs are always welcome :)

Posted 23rd January 2015 by Unknown

7 View comments

JAN
22

Why prefer COALESCE over NVL

Documented By : Nimish Garg

I prefer using "COALESCE" over "NVL" is some of the scenarios. Last week One of my friend
asked me what is the advantage of using "COALESCE" where we can simply use "NVL". I simply
gave him the reply from Oracle Docs i.e. NVL lets you replace null (returned as a blank) with a
string in the results of a query and COALESCE returns the first non-null expr in the expression list.
Oracle Database uses short-circuit evaluation with "COALESCE".

He replied that he knows the difference, he knows that "COALESCE" can take multiple arguments
and so on. He was more interested in understanding "short-circuit evaluation" of "COALESCE"
and the scenarios where I prefer using "COALESCE" over "NVL".

To make him understand I created following function which takes One second in every execution
and simply returns '--null--' and executed 2 very similar queries one with NVL and other with
COALESCE.

SQL> create or replace function f_null return varchar2

2 is

3 begin

4 dbms_lock.sleep(1);

5 return '--null--';

6 end;

7 /

Function created.
Following are the queries which I used to demonstrate that NVL evaluates both arguments even
if the second argument is not used and COALESCE uses short-circuit evaluation i.e. it only
evaluates the arguments only if they are needed.

SQL> select e.empno, e.ename ename, nvl(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--


14 rows selected.

Elapsed: 00:00:14.01

SQL> select e.empno, e.ename ename, coalesce(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--


14 rows selected.

Elapsed: 00:00:01.01

Here we can see easily that the first query with NVL took 14+ seconds, one second for each
record even if the "f_null" value was used only in one record. On the contrary as mentioned in
Oracle Documentation "COALESCE" uses its "short-circuit evaluation" and "f_null" was called
only once and so second query took only One Second. "COALESCE" is certainly use less resources
than NVL.

Posted 22nd January 2015 by Unknown

0 Add a comment

DEC

21

Constraints

It Enforce Rule On Table

We can create constraint at the time of Creating Table


1. Column Level Declaration

2. Table Level Declaration

1. We can provide own name.

Format : [part_of_project_name-table_name-column_name-constraint_type]

Example : gmind_emp_id_pk _uk _ck _f

2. system name name

Format : sys_cn

Example : SYS_C405323

We can create constraint after the table has been created

Types

Primary Key

Not allowed Null value

Not allowed you to enter duplicate value

Ex : Employee_id, Student_id
Unique Key

allowed Null value

Not allowed you to enter duplicate value

Ex : Contact_no, email

Foreign Key

It will allowed you to enter NULL and Duplicate value.

c1(pk) : 1 2 3

c2(f) : 1 1 2 3 4 Not allowed

Allowed you to enter duplicate value and null value

Not Null

It will not allowed you to enter null value

Check

You can check your own condition


Simple Table for understanding

------------------------------------

Duplicate NULL

------------------------------------

Primary Key X X

Unique Key X Allowed

Foreign Key Allowed Allowed

------------------------------------

creating table with all constraint type

Create table my_stu_details

S_id Number(2),

S_name Varchar2(30) Not Null, --SYS_Cn

s_mail Varchar2(30),

s_gender char(1),

s_did Number(3),

Constraint my_stu_sid_pk PRIMARY KEY (s_id),

constraint my_stu_mail_uk UNIQUE (s_mail) ,

Constraint my_stu_gen_ck CHECK (s_gender IN ('M', 'F', 'm', 'f')),


Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

);

DESC my_stu_details;

------------------------------------

Name Type Nullable

------------------------------------

S_ID NUMBER(2)

S_NAME VARCHAR2(30)

S_MAIL VARCHAR2(30) Y

S_GENDER CHAR(1) Y

S_DID NUMBER(3) Y

------------------------------------

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name1' , 'name1@gmail.com' , 'm' , 60 );

Select * from my_stu_details;


Validating Primary Key

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-00001: unique constraint (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (NULL, 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-01400: cannot insert NULL into (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (2 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

Validating NOT NULL Constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)


values (3 , NULL , 'name3@gmail.com' , 'F' , 80 );

ORA-01400: cannot insert NULL into ("HR"."MY_STU_DETAILS"."S_NAME")

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , 'Name3' , 'name3@gmail.com' , 'F' , 80 );

Select * from my_stu_details;

Validating Unique Key Constraint

--Duplicate Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , 'name3@gmail.com' , 'F' , 80 );

ORA-00001: unique constraint (HR.MY_STU_MAIL_UK) violated

--Null Check
Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , null , 'M' , 70 );

Select * from my_stu_details;

Validating Check constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'j' , 70 );

ORA-02290: check constraint (HR.MY_STU_GEN_CK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'M' , 70 );

Select * from my_stu_details;

Validating Foreign Key


Select * from Departments;

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 3 );

ORA-02291: integrity constraint (HR.MY_STU_DID_FK) violated - parent key not found

Departments table : parent table

my_stu_details : Child table

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

--------------------------------------------------------

s_id s_name s_mail s_gender s_did

--------------------------------------------------------

1 name1 name1@gmail.com m 60

2 name2 name2@gmail.com F 90
3 Name3 name3@gmail.com F 80

4 Name4 M 70

5 Name5 name5@gmail.com M 70

6 Name6 name6@gmail.com F 90

--------------------------------------------------------

Deleting the Primary key value which is referred by Foreign Key

Select * from Departments;

DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID

------------------------------------------------------------

60 IT 103 1400 <---- Delete

-- don't execute this query

--Delete From Departments

--Where Department_id = 60;

1) ON DELETE SET NULL


-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

1 name1 name1@gmail.com m -

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

2) ON DELETE SET CASCADE

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

Syntax
Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE CASCADE

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE SET NULL

Constraint Related Data Dictionary Table information.

To view constraint Information

SELECT c.owner,

c.constraint_name,

c.constraint_type,

c.table_name,

c.r_constraint_name,

c.status

FROM user_constraints c

WHERE c.table_name = 'MY_STU_DETAILS';

------------------------------------------------------------------------------------

owner constraint_name constraint_type table_name r_constraint_name status

------------------------------------------------------------------------------------
HR SYS_C004023 C MY_STU_DETAILS ENABLED

HR MY_STU_GEN_CK C MY_STU_DETAILS ENABLED

HR MY_STU_SID_PK P MY_STU_DETAILS ENABLED

HR MY_STU_MAIL_UK U MY_STU_DETAILS ENABLED

HR MY_STU_DID_FK R MY_STU_DETAILS DEPT_ID_PK ENABLED

------------------------------------------------------------------------------------

To view constraint name with corresponding column name

SELECT * FROM user_cons_columns c

WHERE c.table_name = 'MY_STU_DETAILS';

-------------------------------------------------------------

owner constraint_name table_name column_name position

-------------------------------------------------------------

HR MY_STU_MAIL_UK MY_STU_DETAILS S_MAIL 1

HR MY_STU_SID_PK MY_STU_DETAILS S_ID 1

HR MY_STU_GEN_CK MY_STU_DETAILS S_GENDER

HR SYS_C004023 MY_STU_DETAILS S_NAME

HR MY_STU_DID_FK MY_STU_DETAILS S_DID 1

-------------------------------------------------------------
Creating Composite Primary Key

Creating Primary Key with more than one number of column

ALTER TABLE table_name

ADD CONSTRAINT constraint_name PRIMARY KEY(column1, column_2 , column3);

In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.

creating constraint after the table creation

ALTER TABLE table_name

ADD CONSTRAINT constraint_name CONSTRAINT_TYPE(column_name);

ALTER TABLE table_name

DROP CONSTRAINT constraint_name;

ALTER TABLE table_name

DROP PRIMARY KEY;

To drop related foreign key


ALTER TABLE table_name

DROP PRIMARY KEY CASCADE;

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name;

Disable constraint with related foreign key constraint

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name CASCADE;

ALTER TABLE table_name

ENABLE CONSTRAINT constraint_name;

Interview Questions

What are all the type of constraint available in oracle?

Difference between PRIMARY KEY and UNIQUE key.


Difference between PRIMARY KEY ans FOREIGN KEY.

Difference between UNIQUE key and FOREIGN KEY.

Is it possible to create tow primary key in single table.

Write a syntax to create FOREIGN constraint.

How to create constraint after the table has been created?

How to enable and disable a constraint.

Which data dictionary table contains information about constraints?

Which Data Dictionary table contains information about constraint with corresponding column
name?

What is composite primary key?

Explain ON DELETE CASCADE and ON DELETE SET NULL option.

~Thanks For Reading~

Post your valuable feedback below

Posted 21st December 2014 by Unknown

1 View comments

UnknownMay 22, 2017 at 12:39 AM

good
Reply

DEC

listagg in Oracle 11g

Oracle 11gR2 listagg built-in function allows for many table columns to be displayed within a
single row, a non-first-normal form display

Syntax :

listagg(column_value,'delimiter') WITHIN GROUP(ORDER BY column_name)

--Example 1:

CREATE TABLE test_ins(empid NUMBER,product VARCHAR2(30));

BEGIN

INSERT INTO test_ins VALUES( 101,'pendrive');

INSERT INTO test_ins VALUES( 102,'toy');

INSERT INTO test_ins VALUES( 101,'ipod');

INSERT INTO test_ins VALUES( 102,'hat');

INSERT INTO test_ins VALUES( 103,'cpu');

INSERT INTO test_ins VALUES( 104,'pen');

INSERT INTO test_ins VALUES( 104,'car');


INSERT INTO test_ins VALUES( 104,'mat');

INSERT INTO test_ins VALUES( 105,'tv');

INSERT INTO test_ins VALUES( 106,'laptop');

commit;

END;

SELECT * FROM test_ins;

SELECT empid "Employee",

listagg(product,

',') within

GROUP (ORDER BY empid) "Products"

FROM test_ins

GROUP BY empid;

-->-- Result set --<--


DROP TABLE test_ins;

-->-- Example 2

select department_id "Department id", listagg(first_name,', ') WITHIN GROUP(ORDER BY


employee_id) "Employees"

FROM employees

WHERE department_id IN (10,20,30,60)

GROUP BY department_id;

-->-- Result set --<--

Posted 4th December 2014 by Unknown

0 Add a comment

NOV

8
Condition and Looping Statement

IF

IF ELSE

Multiple IF ELSE

LOOP

FOR LOOP

WHILE LOOP

create table test_udt(id NUMBER, salary NUMBER);

BEGIN

INSERT INTO test_udt VALUES(001,23000);

INSERT INTO test_udt VALUES(002,43000);

INSERT INTO test_udt VALUES(003,78000);

INSERT INTO test_udt VALUES(004,25000);

INSERT INTO test_udt VALUES(005,26000);

INSERT INTO test_udt VALUES(006,90000);

Commit;

END;
select * from test_udt;

IF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 1;

IF v_salary > 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

END IF;

commit;

END;

/
IF ELSE

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

ELSE

UPDATE test_udt t

SET t.salary = v_salary+20007

WHERE t.id = v_id ;

END IF;

commit;

END;

/
--same example with less number of lines

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

v_salary := v_salary+10005;

ELSE

v_salary := v_salary+20007;

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

/
select * from test_udt;

Multiple IF ELSIF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 3;

IF v_id = 1 THEN

v_salary := 1000;

dbms_output.put_line('1 inside');

ELSIF v_id = 2 THEN

v_salary := 2000;

dbms_output.put_line('2 inside');

ELSIF v_id = 3 THEN

v_salary := 3000;

dbms_output.put_line('3 inside');

ELSIF v_id = 4 THEN

v_salary := 4000;

dbms_output.put_line('4 inside');
END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

LOOP

--syntax

LOOP

--statements

--increment

--exit statement

END LOOP;

CREATE TABLE prod_details (pid VARCHAR2(3), pname VARCHAR2(30));


DECLARE

i NUMBER := 1;

x VARCHAR2(3);

BEGIN

LOOP

x := lpad(i,3,'0');

dbms_output.put_line('x value : '|| x);

INSERT INTO prod_details VALUES(i, 'Product '||i);

EXIT WHEN i >900;

i := i+1;

IF MOD(i,100) = 0 THEN

commit;

dbms_output.put_line('commit executed');

END IF;

END LOOP;

END;

SELECT * FROM prod_details ORDER BY 1;

DROP TABLE prod_details;

FOR LOOP
BEGIN

FOR I in 1..5

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

FOR LOOP - Reverse

BEGIN

FOR I in REVERSE 14..50

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

WHILE LOOP

DECLARE

i_val NUMBER:=0;

BEGIN

WHILE (i_val < 11)

LOOP
dbms_output.put_line('The value of I is '||i_val);

i_val := i_val + 1;

END LOOP;

END;

sample output:

The value of I is 0

The value of I is 1

The value of I is 2

The value of I is 3

The value of I is 4

The value of I is 5

The value of I is 6

The value of I is 7

The value of I is 8

The value of I is 9

The value of I is 10

Posted 8th November 2014 by Unknown

0 Add a comment
OCT

21

Bulk Collect

This is used for array fetches

With this you can retrieve multiple rows of data with a single round trip.

This reduces the number of context switches between the pl/sql and sql engines.

You can use bulk collect in both dynamic and static sql.

You can use bulk collect in select, fetch into and returning into clauses.

SQL engine automatically initializes and extends the collections you reference in the bulk
collect clause.

You can fetch into multiple collections with one column each.

You can use the limit clause of bulk collect to restrict the no of rows retrieved.

SELECT * FROM product_details;

-->-- Bulk collect in FETCH INTO --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS
SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Bulk collect in SELECT clause --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

BEGIN

SELECT * BULK COLLECT INTO dta FROM product_details;

FOR i IN dta.FIRST .. dta.LAST LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;
-->-- LIMIT in Bulk collect --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta LIMIT 30;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Multiple fetches in INTO clause --<--


SELECT * FROM product_details;

DECLARE

TYPE alldata_typ1 IS TABLE OF product_details.p_id%TYPE;

TYPE alldata_typ2 IS TABLE OF product_details.p_name%TYPE;

dta1 alldata_typ1;

dta2 alldata_typ2;

CURSOR proddt_cur IS

SELECT p_id, p_name FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta1, dta2;

CLOSE proddt_cur;

FOR i IN dta1.FIRST .. dta1.COUNT LOOP

dbms_output.put_line('Department Id : ' || dta1(i));

END LOOP;

FOR i IN dta2.FIRST .. dta2.COUNT LOOP

dbms_output.put_line('Department Name : ' || dta2(i));

END LOOP;

END;
/

DROP TABLE dep_details;

DROP TABLE product_details;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Ref Cursor

This is unconstrained cursor which will return different types depends upon the user input.

Ref cursors cannot be closed implicitly.

Ref cursor with return type is called strong cursor.

Ref cursor without return type is called weak cursor.

You can declare ref cursor type in package spec as well as body.

You can declare ref cursor types in local subprograms or anonymous blocks.

CREATE OR REPLACE PROCEDURE ref_c_sp(dep_det_c IN OUT SYS_REFCURSOR)

AS
BEGIN

OPEN dep_det_c

FOR

SELECT * FROM dep_details d;

END;

DECLARE

dep_det_c SYS_REFCURSOR;

tab_data dep_details%ROWTYPE;

BEGIN

ref_c_sp(dep_det_c);

LOOP

FETCH dep_det_c INTO tab_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department Name : '|| tab_data.d_name);

END LOOP;

CLOSE dep_det_c;

END;

/*sample output*/
Department Name : Admin

Department Name : HR

Department Name : Sales

Department Name : Marketing

DROP PROCEDURE ref_c_sp;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Cursor

SQL Private work Area where the query get passed and executed.

Types

******

Implicit(SQL)

Explicit

-->-- advanced cursor types --<--


Parametrized Cursor

Ref Cursor

Implicit

********

ORACLE implicitly opens a cursor to process each SQL statement not associated with an
explicitly declared cursor.

PL/SQL lets you refer to the most recent implicit cursor as the SQL” cursor. So, although you
cannot use the OPEN,

FETCH, and CLOSE statements to control an implicit cursor, you can still use cursor attributes to
access information

about the most recently executed SQL statement.

Cursor Stages

**************

OPEN cursor_name

FETCH (with in loop)

CLOSE cursor_name

Explicit

The set of rows returned by a query can consist of zero, one, or multiple rows,

depending on how many rows meet your search criteria. When a query returns multiple rows,

you can explicitly define a cursor to process the rows. You use three commands to control the
cursor

Cursor Attributes

*****************

%FOUND

%NOTFOUND

%ISOPEN

%ROWCOUNT

%BULK_ROWCOUNT --<-- used to handle error while using bulk collection.

%BULK_EXCEPTIONS --<-- used to handle error while using bulk collection.

Cursor Declaration

DECLARE

CURSOR <cursor_name>

IS

<SELECT statement>

BEGIN

--> some stmt

END;

Cursor Loop

Loop
While Loop

For Loop

Cursor Clauses

Return

For update

Where current of

Bulk collect

-->-- creating table

create table product_details

p_id NUMBER,

p_name VARCHAR2(30),

p_order_dt DATE

);

-->-- Inserting data

BEGIN

FOR i IN 1 .. 75 LOOP

INSERT INTO product_details VALUES (i, 'prod_name_' || i, SYSDATE + i);

END LOOP;
commit;

END;

-->-- selecting data

SELECT * FROM product_details;

---------------------------------------------

p_id p_name p_order_dt

---------------------------------------------

1 prod_name_1 10/11/2014 3:48:32 PM

2 prod_name_2 10/12/2014 3:48:32 PM

3 prod_name_3 10/13/2014 3:48:32 PM

4 prod_name_4 10/14/2014 3:48:32 PM

5 prod_name_5 10/15/2014 3:48:32 PM

6 prod_name_6 10/16/2014 3:48:32 PM

7 prod_name_7 10/17/2014 3:48:32 PM

8 prod_name_8 10/18/2014 3:48:32 PM

9 prod_name_9 10/19/2014 3:48:32 PM

10 prod_name_10 10/20/2014 3:48:32 PM

11 prod_name_11 10/21/2014 3:48:32 PM

12 prod_name_12 10/22/2014 3:48:32 PM

13 prod_name_13 10/23/2014 3:48:32 PM

14 prod_name_14 10/24/2014 3:48:32 PM


15 prod_name_15 10/25/2014 3:48:32 PM

16 prod_name_16 10/26/2014 3:48:32 PM

17 prod_name_17 10/27/2014 3:48:32 PM

18 prod_name_18 10/28/2014 3:48:32 PM

19 prod_name_19 10/29/2014 3:48:32 PM

20 prod_name_20 10/30/2014 3:48:32 PM

---------------------------------------------

----------------------------------------------

Implicit Cursor

----------------------------------------------

--will update soon

----------------------------------------------

Explicit Cursor

----------------------------------------------

**********************************************

Processing cursor data by using LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;
--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND; --<-- if next record not found means control will
come out from the loop

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )


DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

EXIT WHEN prod_detail_cur%FOUND; --<-- if next record found means control will come
out from the loop

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )


DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE
dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor Already closed

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN
OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

-->-- CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )


Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor closed

**********************************************

Processing cursor data by using WHILE LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

OPEN prod_detail_cur;

FETCH prod_detail_cur

INTO all_data;

WHILE prod_detail_cur%FOUND LOOP

dbms_output.put_line('Product id : ' || all_data.p_id ||


' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

FETCH prod_detail_cur

INTO all_data;

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

************************************************************

Processing cursor data by using FOR LOOP - CURSOR FOR LOOP

************************************************************

DECLARE

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;


BEGIN

FOR i IN prod_detail_cur

LOOP

dbms_output.put_line('Product id : ' || i.p_id ||

' Product Name : ' || i.p_name ||

' ( Orderd on : ' || TRIM(i.p_order_dt) || ' )');

END LOOP;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

Parameterized Cursor

*********************

This was used when you are going to use the cursor in more than one place with different
values for the same where clause.

Cursor parameters must be in mode.


Cursor parameters may have default values.

The scope of cursor parameter is within the select statement.

CREATE TABLE dep_details(d_id NUMBER,d_name VARCHAR2(30), location_id NUMBER);

BEGIN

INSRT INTO dep_details VALUES(001,'Admin',1010);

INSRT INTO dep_details VALUES(002,'HR',1010);

INSRT INTO dep_details VALUES(003,'Sales',1020);

INSRT INTO dep_details VALUES(004,'Marketing',1020);

commit;

END;

SELECT * FROM dep_details;

----------------------------

d_id d_name location_id

----------------------------

1 Admin 1010

2 HR 1010

3 Sales 1020

4 Marketing 1020

----------------------------
DECLARE

-->--Declaring parameterized cursor

CURSOR dep_det_c(p_location_id NUMBER) IS

SELECT * FROM dep_details d WHERE d.location_id = p_location_id;

all_data dep_details%ROWTYPE;

BEGIN

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

OPEN dep_det_c(1010);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

-->-- opening same cursor with different input value

OPEN dep_det_c(1020);

LOOP
FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

END;

/*sample output*/

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 1 Department Name : Admin

Department id : 2 Department Name : HR

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 3 Department Name : Sales

Department id : 4 Department Name : Marketing

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Posted 21st October 2014 by Unknown

0 Add a comment
OCT

21

Handling Exception

Error Handling in oracle

ERROR

Any departure from the expected behavior of the system or program,

which stops the working of the system is an error.

Types : compile time error

Run time error

EXCEPTION

Any error or problem which one can handle and continue to work normally.

Handling Exception

When exception is raised, control passes to the exception section of the block.

i.e. EXCEPTION

WHEN name_of_exception THEN

Types : Pre Defined Exceptions


User Defined Exceptions

Predefined Exception

*********************

Oracle has predefined several exceptions that correspond to the most common oracle errors.

------------------------------------------------------------------------

Exception Oracle Error SQL Code Value

------------------------------------------------------------------------

ZERO_DIVIDE ORA-01476 -1476

NO_DATA_FOUND ORA-01403 +100

DUP_VAL_ON_INDEX ORA-00001 -1

TOO_MANY_ROWS ORA-01422 -1422

VALUE_ERROR ORA-06502 -6502

CURSOR_ALREADY_OPEN ORA-06511 -6511

OTHERS

------------------------------------------------------------------------

-->-- ZERO_DIVIDE --<--

Your program attempts to divide a number by zero.


DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN ZERO_DIVIDE THEN

dbms_output.put_line('Divisor is equal to zero');

END;

-->-- NO_DATA_FOUND --<--

Single row SELECT returned no rows or your program referenced a deleted element in a nested
table

or an uninitialized element in an associative array (index-by table).

CREATE TABLE test_tb(id NUMBER PRIMARY KEY);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN NO_DATA_FOUND THEN

dbms_output.put_line('There is no data inside the table');


END;

-->-- DUP_VAL_ON_INDEX --<--

A program attempted to insert duplicate values in a column that is constrained by a unique


index.

INSERT INTO test_tb VALUES (1);

INSERT INTO test_tb VALUES (2);

commit;

BEGIN

INSERT INTO test_tb VALUES (2);

EXCEPTION

WHEN DUP_VAL_ON_INDEX THEN

dbms_output.put_line('Duplicate values are not allowed');

END;

-->-- TOO_MANY_ROWS --<--

Single row SELECT returned multiple rows.


DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN TOO_MANY_ROWS THEN

dbms_output.put_line('Query returning more than one row');

END;

DROP TABLE test_tb;

-->-- VALUE_ERROR --<--

An arithmetic, conversion, truncation, or size constraint error occurred.

DECLARE

num1 NUMBER(2);

BEGIN

num1 := 345;

EXCEPTION

WHEN VALUE_ERROR THEN

dbms_output.put_line('check the size of the variable');

END;
-->-- CURSOR_ALREADY_OPEN --<--

A program attempted to open an already opened cursor.

CREATE TABLE emp(id NUMBER, name VARCHAR2(30));

BEGIN

INSERT INTO emp VALUES(1,'Name1');

INSERT INTO emp VALUES(2,'Name2');

INSERT INTO emp VALUES(3,'Name3');

INSERT INTO emp VALUES(4,'Name4');

COMMIT;

END;

SELECT * FROM emp;

DECLARE

cursor emp_c IS

SELECT * FROM emp;

all_data emp%ROWTYPE;

BEGIN

OPEN emp_c;
OPEN emp_c;

NULL;

CLOSE emp_c;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

END;

DROP TABLE emp;

-->-- OTHERS --<--

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

WHEN OTHERS THEN

dbms_output.put_line('Some other error ' || SQLERRM);

END;
User Defined Exception

**********************

A user-defined exception is an error that is defined by the programmer.

User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,

exceptions have a type EXCEPTION and scope.

DECLARE

v_gender CHAR := '&gender';

gender_ex EXCEPTION;

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE gender_ex;

END IF;

dbms_output.put_line('Gender : '||v_gender);

EXCEPTION

WHEN gender_ex THEN

dbms_output.put_line('Please Enter valid gender');

END;

create table test_insert (id NUMBER, Name VARCHAR2(30));


DECLARE

abort_ex EXCEPTION;

BEGIN

FOR i IN 1..100

LOOP

BEGIN

IF mod(i,10)=0 THEN

RAISE abort_ex;

END IF;

INSERT INTO test_insert VALUES(i, 'Name'||i);

EXCEPTION

WHEN abort_ex THEN

NULL;

END;

END LOOP;

COMMIT;

END;

SELECT * FROM test_insert;

DROP TABLE test_insert;

SQLERRM and SQLCODE

********************
SQLCODE returns the current error code, and SQLERRM returns the current error message
text;

For user-defined exception SQLCODE returns 1 and SQLERRM returns “user-defined


exception”.

SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.

CREATE TABLE test_tb (id NUMBER);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

dbms_output.put_line(v_id);

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('SQLERRM : ' || SQLERRM);

dbms_output.put_line('SQLCODE : ' || SQLCODE);

END;

/*sample output*/

SQLERRM : ORA-01403: no data found

SQLCODE : 100
DROP TABLE test_tb;

PRAGMA EXCEPTION_INIT

*********************

Using this you can associate a named exception with a particular oracle error.

This gives you the ability to trap this error specifically, rather than via an OTHERS handler.

Syntax:

PRAGMA EXCEPTION_INIT(exception_name, oracle_error_number);

DECLARE

v_result NUMBER;

PRAGMA EXCEPTION_INIT(Invalid, -1476);

BEGIN

SELECT 453 / 0 INTO v_result FROM dual;

dbms_output.put_line('Result : ' || v_result);

EXCEPTION

WHEN INVALID THEN

dbms_output.put_line('Invalid Exception');

END;
RAISE_APPLICATION_ERROR

************************

You can use this built-in function to create your own error messages, which can be more
descriptive than named exceptions.

Error Number :

Oracle Error Range : From -00000 to -19999

User Error Range : From -20000 to -20999

DECLARE

v_gender CHAR := '&gender';

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE_APPLICATION_ERROR(-20003, 'Enter valid gender');

END IF;

dbms_output.put_line('Gender : ' || v_gender);

END;

Posted 21st October 2014 by Unknown


1 View comments

RajmohanMarch 13, 2018 at 6:49 AM

How to get the two table data without using Joins and sub query,union?

Reply

OCT

Package

1. You can groups logical related subprogram (procedures and functions)

2. It consist of two parts

I) specification

II) Body

3. It allows the oracle server to read multiple object in to a memory once

4. You can declare global variable,cursor, user define exeption

5. Overloading

6. we can't create anonyms block inside the package

create table err_log(sno NUMBER, u_name VARCHAR2(30), error_msg CLOB, hap_tm


TIMESTAMP);
select * from err_log;

--stand alone procedure

CREATE OR REPLACE PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id


%TYPE) IS

v_salary employees.salary%TYPE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT salary,

first_name

INTO v_salary,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line('Salary of ' || v_first_name || ' is ' || v_salary);

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,
v_error,

systimestamp);

commit;

END emp_sal_sp;

BEGIN

-- Call the procedure

emp_sal_sp(p_employee_id => :p_employee_id);

END;

CREATE OR REPLACE PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id


%TYPE) IS

v_hire_date DATE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT hire_date,

first_name

INTO v_hire_date,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line(v_first_name || ' hired on ' || to_char(v_hire_date,'month ddth,


yyyy'));
EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_hdt_sp;

BEGIN

-- Call the procedure

emp_hdt_sp(p_employee_id => :p_employee_id);

END;

create or replace function sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER

IS

v_c NUMBER;

BEGIN
v_c := p_a + p_b;

RETURN v_c;

END;

--Specification Part

CREATE OR REPLACE PACKAGE emp_pkg

IS

PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id%TYPE);

PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id%TYPE);

FUNCTION sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER;

END emp_pkg ;

--Body Part

CREATE OR REPLACE PACKAGE BODY emp_pkg

IS
PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id%TYPE) IS

v_salary employees.salary%TYPE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT salary,

first_name

INTO v_salary,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line('Salary of ' || v_first_name || ' is ' || v_salary);

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_sal_sp;
PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id%TYPE) IS

v_hire_date DATE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT hire_date,

first_name

INTO v_hire_date,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line(v_first_name || ' hired on ' || to_char(v_hire_date,'month ddth,


yyyy'));

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_hdt_sp;

FUNCTION sum_fn (p_a IN NUMBER, p_b IN NUMBER)


RETURN NUMBER

IS

v_c NUMBER;

BEGIN

v_c := p_a + p_b;

RETURN v_c;

END;

END emp_pkg;

A package specification can exist without a package body, but

a package body can't exist without a package specification.

--Executing procedure inside the package

BEGIN

emp_pkg.emp_sal_sp(120);

END;

--Executing function inside the package

SELECT emp_pkg.sum_fn(23,567) FROM dual;


-- You can declare global variable,cursor, user define exeption

create or replace package all_detail

as

PROCEDURE emp2sal (a IN NUMBER);

PROCEDURE emp2exep (a IN NUMBER);

FUNCTION add2num (a IN NUMBER, b IN NUMBER)

RETURN NUMBER;

c NUMBER(8); --global declaration

abort_ex EXCEPTION; --global exception declaration

CURSOR emp_rec --global cursor declaration

IS

SELECT first_name, salary, hire_date, department_id

FROM employees;

End all_detail;

create or replace package body all_detail

as
PROCEDURE emp2sal (a IN NUMBER)

AS

BEGIN

SELECT salary

INTO c

FROM Employees

WHERE Employee_id = a;

Dbms_output.put_line('Salary of Employee ' || a || ' is ' || c);

EXCEPTION

WHEN no_data_found THEN

Dbms_output.put_line('Please enter valid id');

END emp2sal;

PROCEDURE emp2exep (a IN NUMBER)

AS

BEGIN

SELECT Round(Months_between(sysdate,hire_date)/12)

INTO c

FROM Employees

WHERE Employee_id = a;
Dbms_output.put_line( c || ' Years');

EXCEPTION

WHEN no_data_found THEN

Dbms_output.put_line('Please enter valid id');

END emp2exep;

FUNCTION add2num (a IN NUMBER, b IN NUMBER)

RETURN NUMBER

AS

BEGIN

c := a+b;

RETURN C;

END;

End all_detail;

/*Declaring a Bodiless Package */

CREATE OR REPLACE PACKAGE global_constant

IS

mile_2_kilo CONSTANT NUMBER := 1.6093;


kilo_2_mile CONSTANT NUMBER := 0.6214;

yard_2_meter CONSTANT NUMBER := 0.9144;

meter_2_yard CONSTANT NUMBER := 1.0936;

END global_constant;

BEGIN

DBMS_OUTPUT.PUT_LINE('20 miles = ' || 20*global_constant.mile_2_kilo||' km');

END;

/*Forward Declaration in package */

DECLARE

PROCEDURE P2; -- forward declaration

PROCEDURE P3;

PROCEDURE P1 IS

BEGIN

dbms_output.put_line('From procedure p1');

p2;

END P1;

PROCEDURE P2 IS

BEGIN
dbms_output.put_line('From procedure p2');

p3;

END P2;

PROCEDURE P3 IS

BEGIN

dbms_output.put_line('From procedure p3');

END P3;

BEGIN

p1;

END;

sample output:

From procedure p1

From procedure p2

From procedure p3

Drop package package_name;

Drop package body package_name;

SELECT text FROM user_source u


WHERE u.name = 'EMP_PKG';

Interview Questions:

What is package?

Advantage of package

Is it possible to create package body with out package specification?

what is package overloading?

what is forward declaration in package?

which data dictionary table contain source code of package?

How to declare global variable, exception and cursor?

How to execute procedure and function inside the package?

Posted 4th October 2014 by Unknown

0 Add a comment

OCT

%TYPE and %ROWTYPE


--%type is used to fetch the data type of the particular column

create table product_details

p_id NUMBER(3),

p_nm VARCHAR2(30),

p_qty NUMBER(8),

order_dt DATE

);

BEGIN

INSERT INTO product_details VALUES(100,'Name0',400,'23-Mar-13');

INSERT INTO product_details VALUES(101,'Name1',600,'26-Apr-13');

INSERT INTO product_details VALUES(102,'Name2',800,'27-Jan-12');

INSERT INTO product_details VALUES(103,'Name3',300,'23-Jul-11');

INSERT INTO product_details VALUES(104,'Name4',200,'22-Aug-11');

INSERT INTO product_details VALUES(105,'Name5',500,'25-Oct-12');

commit;

END;

SELECT * FROM product_details;


------------------------------------

P_ID P_NM P_QTY ORDER_DT

------------------------------------

100 Name0 400 03/23/2013

101 Name1 600 04/26/2013

102 Name2 800 01/27/2012

103 Name3 300 07/23/2011

104 Name4 200 08/22/2011

105 Name5 500 10/25/2012

------------------------------------

DECLARE

v_name VARCHAR2(4);

BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 100;

dbms_output.put_line('Product Name : ' || v_name);

--error numeric or value error

END;
DECLARE

v_name VARCHAR2(5);

BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 100;

dbms_output.put_line('Product Name : ' || v_name);

END;

ALTER TABLE product_details

MODIFY p_nm VARCHAR2(15);

INSERT INTO product_details

VALUES

(106,

'name6',

700,

'26-Dec-12');

commit;
106 name6 700 12/26/2012

DECLARE

v_name VARCHAR2(5);

BEGIN

SELECT p_nm INTO v_name

FROM product_details

WHERE p_id = 106;

dbms_output.put_line('Product Name : ' || v_name);

--error

END;

DECLARE

v_name product_details.p_nm%TYPE;

BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 106;


dbms_output.put_line('Product Name : ' || v_name);

END;

DROP TABLE product_details;

DECLARE

dep_id departments.department_id%TYPE;

dep_name departments.department_name%TYPE;

dep_man_id departments.manager_id%TYPE;

dep_loc_id departments.location_id%TYPE;

BEGIN

SELECT department_id,

department_name,

manager_id,

location_id

INTO dep_id,

dep_name,

dep_man_id,

dep_loc_id
FROM departments

WHERE department_id = 10;

dbms_output.put_line('Department_id : ' || dep_id);

dbms_output.put_line('Department_name : ' || dep_name);

dbms_output.put_line('Manager_id : ' || dep_man_id);

dbms_output.put_line('Location_id : ' || dep_loc_id);

END;

--%rowtype is used to fetch the data type of all the column

--Insted of using %type if we use %rowtype means we can reduce the no of variables that we
declare

DECLARE

dep_detail departments%ROWTYPE;

BEGIN

SELECT *

INTO dep_detail

FROM departments

WHERE department_id = 10;


dbms_output.put_line('Department_id : ' || dep_detail.department_id);

dbms_output.put_line('Department_name : ' || dep_detail.department_name);

dbms_output.put_line('Manager_id : ' || dep_detail.manager_id);

dbms_output.put_line('Location_id : ' || dep_detail.location_id);

END;

DROP TABLE dept_details;

CREATE TABLE dept_details

dept_id number(3) ,

dept_name varchar2(30),

dept_manager_name varchar2(30)

);

insert into dept_details values(10,'dept1','manager_name1');

insert into dept_details values(20,'dept2','manager_name2');

SELECT * FROM dept_details;


-------------------------------------------------------

| DEPT_ID | DEPT_NAME | DEPT_MANAGER_NAME |

+------------+-----------------------+-----------------

| 10 | dept1 | manager_name1 |

| 20 | dept2 | manager_name2 |

------------+-----------------------+------------------

DECLARE

all_data dept_details%ROWTYPE;

BEGIN

all_data.dept_id := 100;

all_data.dept_name := 'Admin';

all_data.dept_manager_name := 'John';

UPDATE dept_details

SET ROW = all_data

WHERE dept_id = 10;

dbms_output.put_line(SQL%ROWCOUNT || ' Row(s) get updated');

END;

/
1 Row(s) get updated

select * from dept_details;

---------------------------------------------------

| DEPT_ID | DEPT_NAME | DEPT_MANAGER_NAME|

---------------------------------------------------

| 100 | Admin | John |

| 20 | dept2 | manager_name2 |

---------------------------------------------------

Interview Question :

1. What is the use of %TYPE?

2. What is the use of %ROWTYPE?

3. Difference between %TYPE and %ROWTYPE?

Posted 2nd October 2014 by Unknown

0 Add a comment
SEP

29

BULK Exceptions

/************************************************************************

* Handling Exceptions in Bulk Operations *

* Documented on 29-SEP-14 04.35.35.980894 PM +05:30 *

* Document By : Murugappan Annamalai *

* Reference : http://www.dba-oracle.com/plsql/t_plsql_exceptions.htm *

************************************************************************/

CREATE TABLE bulk_tb (ran_num NUMBER NOT NULL);

--inserting data using bulk collect

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200
LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

commit;

END;

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

200

TRUNCATE TABLE bulk_tb;

sample2.sql --without exception part


DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

commit;

END;

/*

Error Message :

ORA-01400: cannot insert NULL into ("HR"."bulk_tb"."ran_num")

ORA-06512: at line 15

*/
sample2.sql --with exception part

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

BEGIN

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

COMMIT;

EXCEPTION

WHEN OTHERS THEN


dbms_output.put_line('Error while inserting bulk record '||SQLERRM);

END;

END;

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

99

SQL%BULK_EXCEPTIONS(i).ERROR_INDEX

Holds the iteration (not the subscript) of the original FORALL statement that raised the
exception.

In sparsely populated collections,

the exception row must be found by looping through the original collection the correct
number of times.

SQL%BULK_EXCEPTIONS(i).ERROR_CODE

Holds the exceptions error code.


The total number of exceptions can be returned using the collections COUNT method,

which returns zero if no exceptions were raised. The save_exceptions.sql script,

a modified version of the handled_exception.sql script, demonstrates this functionality.

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

v_ex_count NUMBER(4);

abort_ex EXCEPTION;

PRAGMA EXCEPTION_INIT(abort_ex, -24381);

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

v_dat(150) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */


EXECUTE IMMEDIATE 'TRUNCATE TABLE bulk_tb';

BEGIN

FORALL i IN v_dat.FIRST..v_dat.LAST SAVE EXCEPTIONS

INSERT INTO bulk_tb VALUES(v_dat(i));

COMMIT;

EXCEPTION

WHEN abort_ex THEN

v_ex_count := SQL%BULK_EXCEPTIONS.COUNT;

FOR i IN 1..v_ex_count LOOP

dbms_output.put_line('Error: ' || i ||' Array Index: ' || SQL


%BULK_EXCEPTIONS(i).error_index ||

' Message: ' || SQLERRM(SQL%BULK_EXCEPTIONS(i).ERROR_CODE));

END LOOP;

END;

END;

/*

Sample output:

Error: 1 Array Index: 100 Message: -1400: non-ORACLE exception

Error: 2 Array Index: 150 Message: -1400: non-ORACLE exception

*/
SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

198

SAVE EXCEPTIONS clause being removed, in the above script now traps a different error number.

The output from this script is listed below.

/*

Sample output:

Error: 1 Array Index: 100 Message: -1400: non-ORACLE exception

*/

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------
99

SELECT COUNT(*) FROM bulk_tb;

DROP TABLE bulk_tb;

Posted 29th September 2014 by Unknown

0 Add a comment

SEP

29

Cursor - FOR UPDATE

/************************************************************************

* FOR UPDATE clause in oracle *

* Document By : Murugappan Annamalai *

************************************************************************/

create table prod_details(p_id VARCHAR2(30), P_name VARCHAR2(30));


BEGIN

--Inserting data into prod_details table

FOR i IN 1..50 LOOP

INSERT INTO prod_details VALUES(i,'pname'||i);

END LOOP;

commit;

END;

SELECT * FROM prod_details;

DECLARE

CURSOR PROD_DTLS_C IS

SELECT * FROM PROD_DETAILS T1 FOR UPDATE OF P_ID;

V_PID PROD_DETAILS.P_ID%TYPE;

V_PRDNAME PROD_DETAILS.P_NAME%TYPE;

BEGIN

OPEN PROD_DTLS_C;

LOOP
FETCH PROD_DTLS_C INTO V_PID, V_PRDNAME;

IF PROD_DTLS_C%NOTFOUND THEN

EXIT;

ELSE

UPDATE PROD_DETAILS P

SET P.P_ID = LPAD(P_ID, 10, 0)

WHERE CURRENT OF PROD_DTLS_C;

END IF;

END LOOP;

CLOSE PROD_DTLS_C;

COMMIT;

END;

select * from PROD_DETAILS;

TRUNCATE TABLE prod_details;

BEGIN

--Inserting data into prod_details table

FOR i IN 1..50 LOOP


INSERT INTO prod_details VALUES(i,'pname'||i);

END LOOP;

commit;

END;

DECLARE

CURSOR PROD_DTLS_C IS

SELECT * FROM PROD_DETAILS T1 FOR UPDATE OF P_ID;

V_PID PROD_DETAILS.P_ID%TYPE;

V_PRDNAME PROD_DETAILS.P_NAME%TYPE;

BEGIN

OPEN PROD_DTLS_C;

LOOP

FETCH PROD_DTLS_C INTO V_PID, V_PRDNAME;

IF PROD_DTLS_C%NOTFOUND THEN

EXIT;

ELSE
UPDATE PROD_DETAILS P

SET P.P_ID = LPAD(P_ID, 10, 0)

WHERE CURRENT OF PROD_DTLS_C;

END IF;

COMMIT;

END LOOP;

CLOSE PROD_DTLS_C;

--COMMIT;

END;

select * from PROD_DETAILS;

Posted 29th September 2014 by Unknown

0 Add a comment

MAY

28

Escape Sequence in Oracle

Escape special characters when writing SQL queries


--to include single '

SELECT 'Steven's salary is more than 50k INR' AS "SAL_DETAILS"

FROM Dual;

ORA-01756 : quoted string not properly terminated

SELECT 'Steven''s salary is more than 50k INR' AS "SAL_DETAILS"

FROM Dual;

SAL_DETAILS

---------------------------------------

Steven's salary is more than 50k INR

--to include double '

SELECT 'You can print double quot ('''') in oracle' "Info"

FROM Dual;

Info

---------------------------------------
You can print double quot ('') in oracle

SELECT q'[some test ' some test ' some text ']' AS "In 10g"

FROM dual;

In 10g

------------------------------------

some test ' some test ' some text '

--Escape wild card characters ( _ and % )

The LIKE keyword allows for string searches.

The '_' wild card character is used to match exactly one character

While '%' is used to match zero or more occurrences of any characters.

These characters can be escaped in SQL as follows.

WITH mail_ids AS

SELECT 'an.murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an_murugappan@gmail.com' mail FROM Dual

UNION
SELECT 'an%murugappan@gmail.com' mail FROM Dual

SELECT * FROM mail_ids

WHERE mail LIKE '__$_%' ESCAPE '$';

mail

----------------------------------

an_murugappan@gmail.com

WITH mail_ids AS

SELECT 'an.murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an_murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an%murugappan@gmail.com' mail FROM Dual

SELECT * FROM mail_ids

WHERE mail LIKE '__/%%' ESCAPE '/';

mail

----------------------------------

an%murugappan@gmail.com
Escape ampersand (&) characters in SQL*Plus

SQL> select '&a' FROM dual;

'23'

----

23

SQL> SET ESCAPE '\'

SQL> select '\&a' FROM dual;

'&A'

----

&a

SQL> SET SCAN OFF;

SQL> select '&a' FROM dual;

'&A'

----

&a
SQL> SET SCAN ON;

SQL> select '&a' FROM dual;

'45'

----

45

Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Data Manipulation Language

Data Manipulation Language (DML) statements are used for managing data within schema
objects. Some examples:

INSERT - insert data into a table

UPDATE - updates existing data within a table

DELETE - deletes all records from a table, the space for the records remain

MERGE - UPSERT operation (insert or update)


CREATE TABLE prod_details

prod_id NUMBER(4) ,

prod_name VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

Deliver_dt DATE DEFAULT SYSDATE+3 ,

comments VARCHAR2(300)

);

SELECT * FROM prod_details;

no_data_found

INSERT

INSERT INTO prod_details(prod_id,prod_name,order_dt,deliver_dt,comments)

VALUES(100,'Apple iphone 5s','21-May-14','24-May-14','Color : Black');

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------
100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

---------------------------------------------------------------------------

--Inserting records with out mentioning column name

INSERT INTO prod_details

VALUES(101,'Samsung Galaxy III','20-Aug-14','23-Aug-14','Color : White');

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

---------------------------------------------------------------------------

--Inserting selective number of values

INSERT INTO prod_details

VALUES(103,'Moto X','11-May-14','13-May-14');

ORA-00947 : not enough values

--While inserting selective number of values mentioning column name is compulsory.


INSERT INTO prod_details (prod_id,prod_name,order_dt,deliver_dt)

VALUES(103,'Moto X','11-May-14','13-May-14');

SELECT * FROM prod_details;

--------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

--------------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

--------------------------------------------------------------------------------

--Inserting NULL value.

--If you want to insert NULL value you can ignore that column at the time of inserting

--or we can use NULL keyword to insert NULL.

INSERT INTO prod_details

VALUES(104,'Moto G','19-May-14','22-May-14',NULL);

SELECT * FROM prod_details;


---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Noto G 5/19/2014 5/22/2014

---------------------------------------------------------------------------

--if you are not providing values for order_dt and deliver_dt column default value can be taken.

INSERT INTO prod_details(prod_id,prod_name,comments)

VALUES(105,'Nokia Lumis 720p','Color : Red');

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

----------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Moto G 5/19/2014 5/22/2014

105 Nokia Lumis 720p 5/26/2014 5/29/2014 Color : Red


---------------------------------------------------------------------------

--Inserting data by using sub query

CREATE TABLE test_tab (id NUMBER, Name VARCHAR2(30));

INSERT INTO test_tab VALUES(1,'Name1');

INSERT INTO test_tab VALUES(2,'Name2');

INSERT INTO test_tab VALUES(3,'Name3');

SELECT COUNT(*) FROM test_tab;

COUNT(*)

-------

--creating table by using sub query (with out data)

CREATE TABLE ins_chk

SELECT * FROM test_tab

WHERE id = 900;
SELECT COUNT(*) FROM ins_chk;

COUNT(*)

-------

--Inserting data by using sub query

--copying data from test_tab to ins_chk

INSERT INTO ins_chk (SELECT * FROM test_tab);

3 rows inserted in 0.047 seconds.

SELECT COUNT(*) FROM ins_chk;

COUNT(*)

-------

DROP TABLE test_tab;


DROP TABLE ins_chk;

UPDATE

Syntax :

UPDATE table_name

SET column1_name = column1_value,

column2_name = column2_value,

column2_name = column3_value,

columnn_name = columnn_value

WHERE condition(s);

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

----------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Moto G 5/19/2014 5/22/2014

105 Nokia Lumis 720p 5/26/2014 5/29/2014 Color : Red


---------------------------------------------------------------------------

UPDATE prod_details ps

SET ps.prod_name = 'iphone 5s'

WHERE ps.prod_id = 100;

1 row updated in 0.031 seconds

SELECT *

FROM prod_details ps

WHERE ps.prod_id = 100;

--------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

--------------------------------------------------------------------

100 iphone 5s 5/21/2014 5/24/2014 Color : Black

--------------------------------------------------------------------

--update statement with out condition

--If you try to execute update statement without condition it'll update all the records inside the
table.

UPDATE prod_details ps

SET ps.comments = 'None';

5 row updated in 0.031 seconds


SELECT *

FROM prod_details ps;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 None

101 Samsung Galaxy III 8/20/2014 8/23/2014 None

103 Moto X 5/11/2014 5/24/2014 None

104 Moto G 5/19/2014 5/22/2014 None

105 Nokia Lumis 720p 5/26/2014 5/29/2014 None

----------------------------------------------------------------------

--if your update text contain ' means you can use following metnod (use '')

UPDATE prod_details ps

SET ps.comments = 'Some product''s are not available'

WHERE ps.prod_id = 100;

1 row updated in 0.031 seconds

SELECT *
FROM prod_details ps

WHERE ps.prod_id = 100;

------------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

------------------------------------------------------------------------------------

100 iphone 5s 5/21/2014 5/24/2014 Some product's are not available

------------------------------------------------------------------------------------

DELETE

Syntax:

DELETE FROM table_name

WHERE condition(s);

DELETE FROM prod_details

WHERE prod_id IN (104, 105);

2 row(S) deleted in 0.032 seconds

SELECT *

FROM prod_details ps;


---------------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Some product's are not available

101 Samsung Galaxy III 8/20/2014 8/23/2014 None

103 Moto X 5/11/2014 5/24/2014 None

---------------------------------------------------------------------------------------

DELETE FROM prod_details;

3 row(s) deleted in 0.062 seconds.

SELECT * FROM prod_details;

no rows selected.

DROP TABLE prod_details;

MERGE = Insert + Update

-- will update soon.


Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Data Define Language

Data Definition Language (DDL) statements are used to define the database structure or schema.

Some examples:

CREATE - to create objects in the database.

ALTER - alters the structure of the database.

ADD

RENAME

MODIFY

DROP

DROP - delete objects from the database

TRUNCATE - remove all records from a table,

including all spaces allocated for the records are removed.

COMMENT - add comments to the data dictionary.

RENAME - rename an object.


Creating Table

--------------------------------------------------------------------------

Data Types Size Default Size Explanation

--------------------------------------------------------------------------

NUMBER(P,S) P: 1 to 38 we can store number between 0-9

S: -84 to 127

VARCHAR2 4000 Bytes we can store 0-9, a-z, A-Z and special characters

CHAR 2000 Bytes 1

DATE 7 Used to store Date

TIMESTAMP Includes year, month, day, hour, minute, and seconds.

LONG 2 GB Only one long column is allowed in a table.

We can't use this column in ORDER BY clause.

CLOB 4 GB Character Large Object

BLOB Binary Larger Object

--------------------------------------------------------------------------

CREATE

ALTER : ADD RENAME MODIFY DROP RENAME

RENAME

DROP

TRUNCATE
--creating table

CREATE TABLE friends_details_tb

Name VARCHAR2(30) ,

Phone NUMBER(10) ,

Gender CHAR ,

dob DATE ,

other_details LONG ,

make_dtm TIMESTAMP

);

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

-----------------------------
--maximum you can keep 255 columns in a table

ALTER : Colum level operations

ADD RENAME MODIFY DROP

ADD : Used to add a column after the table hase been created

ALTER TABLE friends_details_tb

ADD email VARCHAR2(30);

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

EMAIL VARCHAR2(30)
-----------------------------

--adding multiple columns by using single ALTER statement

SYNTAX

ALTER TABLE friends_details_tb

ADD (

column_1 Data_type(size),

column_2 Data_type(size),

column_3 Data_type(size),

column_4 Data_type(size)

);

RENAME : Used to Rename a column

ALTER TABLE friends_details_tb

RENAME COLUMN email TO email_id;

DESC friends_details_tb;

-----------------------------
NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

MODIFY : Used to change the data type or size of the data type.

ALTER TABLE friends_details_tb

MODIFY other_details CLOB;

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)
GENDER CHAR(1)

DOB DATE

OTHER_DETAILS CLOB

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

--Modifying multiple columns at a time

ALTER TABLE friends_details_tb

MODIFY ( column_name_1 old_datatype(new_size),

column_name_2 new_datatype(old_size),

column_name_3 new_datatype(new_size)

);

DROP : Used to drop the column after the table has been created.

ALTER TABLE friends_details_tb

DROP COLUMN other_details;

DESC friends_details_tb;

-----------------------------
NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

RENAME : Used to Rename a particular table.

SYNTAX

RENAME old_table_name TO new_table_name;

RENAME friends_details_tb TO fnd_det;

DESCRIBE fnd_det;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)
PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

TRUNCATE : Used to remove the entire content of the table (not a structure)

SYNTAX

TRUNCATE TABLE table_name;

TRUNCATE TABLE fnd_det;

DROP : Used to drop the tabel (Data + stucture of the table get removed from the database )

DROP TABLE fnd_det;

*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Statements in Oracle

Data Definition Language (DDL)

DDL statements are used to define the database structure or schema. Some examples:

CREATE - to create objects in the database

ALTER - alters the structure of the database

ADD

RENAME

MODIFY

DROP

DROP - delete objects from the database

TRUNCATE - remove all records from a table,

including all spaces allocated for the records are removed

RENAME - rename an object

Data Manipulation Language (DML)


DML statements are used for managing data within schema objects. Some examples:

INSERT - insert data into a table

UPDATE - updates existing data within a table

DELETE - deletes all records from a table, the space for the records remain

MERGE - UPSERT operation (insert or update)

Data Control Language (DCL)

DCL statements. Some examples:

GRANT - gives users access privileges to database

REVOKE - withdraw access privileges given with the GRANT command

Transaction Control (TCL)

TCL statements are used to manage the changes made by DML statements. It allows
statements to be grouped together into logical transactions.

COMMIT - save work done

SAVEPOINT - identify a point in a transaction to which you can later roll back

ROLLBACK - restore database to original since the last COMMIT


Posted 28th May 2014 by Unknown

0 Add a comment

MAY

19

DECODE and CASE statement

CREATE TABLE students (

roll_no NUMBER(4) ,

Name VARCHAR2(30) ,

dept_cd VARCHAR2(20) ,

total_marks NUMBER(3)

);

BEGIN

INSERT INTO students VALUES (2000,'Rahul','CSE',480);

INSERT INTO students VALUES (2001,'Bala','IT', 390);

INSERT INTO students VALUES (2002,'Ramesh','CSE',250);

INSERT INTO students VALUES (2003,'Karthi','EEE',185);

INSERT INTO students VALUES (2004,'Ravi','IT',345);

END;
/

SELECT * FROM students;

DECODE

Decode is a function. Its a Oracle one.

Works like IF-THEN-ELSE.

You can use DECODE only in SELECT clause.

In DECODE you can include 255 things include Exep, search , result and default value.

Example

SELECT roll_no,

NAME,

dept_cd,

DECODE(dept_cd,

'CSE',

'Computer Science and Engineering',

'IT',

'Information Technology',

'Default Value') AS "DEPARTMENT NAME"

FROM students;

Sample Output
------------------------------------------------------------

ROLL_NO NAME DEPT_CD DEPARTMENT NAME

------------------------------------------------------------

2000 Rahul CSE Computer Science and Engineering

2001 Bala IT Information Technology

2002 Ramesh CSE Computer Science and Engineering

2003 Karthi EEE Default Value

2004 Ravi IT Information Technology

------------------------------------------------------------

CASE

CASE is an expression. Its a ANSI standard.

Compare to DECODE case will be more faster.

Example

SELECT roll_no,

NAME,

dept_cd,

total_marks,

CASE

WHEN total_marks > 500 THEN

'A Grade'

WHEN total_marks > 400 THEN

'B Grade'
WHEN total_marks > 300 THEN

'C Grade'

ELSE

'U Grade'

END AS "GRADE"

FROM students;

-----------------------------------------------

ROLL_NO NAME DEPT_CD TOTAL_MARKS GRADE

-----------------------------------------------

2000 Rahul CSE 480 B Grade

2001 Bala IT 390 C Grade

2002 Ramesh CSE 250 U Grade

2003 Karthi EEE 185 U Grade

2004 Ravi IT 345 C Grade

-----------------------------------------------

Interview Questions:

What is DECODE?

What is CASE?

Difference between CASE and DECODE? Which one is faster?

Posted 19th May 2014 by Unknown


0 Add a comment

MAY

19

Sub Query

Query with in another query

1. Single Row sub query

2. Multi row Sub query

select * from employees;

Want to fetch the person Who are all getting salary more than Neena's salary ?

Neena's Salary : 17000

Select First_name, salary

From Employees

Where salary > 17000;

--change in Neena's salary won't work for the above query.


Select salary From Employees

Where First_name = 'Neena';

Sub Query :

Select First_name, salary

From Employees

Where salary > (

Select salary From Employees

Where First_name = 'Neena'

);

Select * from employees;

Select salary From Employees

Where First_name = 'Alexander';

Sub Query Returns one value it is called as Single row sub query

Sub Query Returns more than one value it is called as Multi row sub query
Single row sub query operators :

> < >= <= = <>

Multiple Row Sub query operators :

IN ALL ANY

Who are all getting salary more than the average salary?

Select

First_name,

Salary

From

Employees

WHERE

Salary > (

SELECT Round(avg(salary),0)

FROM Employees

);

Multiple Row Sub query (In ANY ALL)


Select First_name,Department_id, salary

From Employees

Where salary in(

Select Salary From Employees

Where First_name = 'Alexander'

);

Any : Minimum Value will be taken (3100)

Select First_name,Department_id, salary

From Employees

Where salary > ANY(

Select Salary From Employees

Where First_name = 'Alexander'

);

All : Maximum Value will be taken (9000)

Select First_name,Department_id, salary

From Employees

Where salary > All(

Select Salary From Employees

Where First_name = 'Alexander'

);
We can use sub query in all the classes except Group by and order by class.

Select

From

Where

-----------Group by

having

-----------Order by

SELECT

( Select Count(*) from Employees Where Department_id = 90 )Executive,

( Select Count(*) from Employees Where Department_id = 60 ) IT,

( Select Count(*) from Employees Where Department_id = 10 ) Administration,

( Select Count(*) from Employees Where Department_id = 100) Finance

FROM

Dual;

Select Min(salary) From Employees;

Select Min(salary) from

Select * from Employees


Where Department_id = 60

);

What is INLINE VIEW?

If u use sub query in From it is call it is as INLINE VIEW.

Intermediate result set

Correlated sub query

SELECT employee_number, name

FROM employees Bob

WHERE salary > (

SELECT AVG(salary)

FROM employees

WHERE department = Bob.department

);

Posted 19th May 2014 by Unknown

0 Add a comment
Loading

Dynamic Views theme. Powered by Blogger.

Oracle sql & Pl/sql

search

Home Sql and pl/sql Sql Interview Questions

JUL

20

INLINE view in Oracle with 12c New Features

Named sub Query in FROM clause is call it as INLINE VIEW.

Oracle process a inline view faster than sub query

Inline View in Oracle

--Query to display all the employees who are all getting salary more than their department
average salary

SELECT First_name

, last_name

, salary

, department_id

FROM employees a , ( SELECT b.department_id

, AVG(b.salary) avg_sal
FROM employees b

GROUP BY b.department_id

)b

WHERE a.department_id = b.department_id

AND a.salary > b.avg_salary;

Display all the customer who have placed more number of orders by using INLINE view

CREATE TABLE customer_order_det_tb

( custm_id NUMBER ,

custm_nm VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

ttl_amt NUMBER(7,2)

);

BEGIN

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '11-Jul-15' , 45000.00);

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '14-Jul-15' , 27000.00);

INSERT INTO customer_order_det_tb VALUES(101, 'Raja' , '13-Jul-15' , 17000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 34000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 38000.00);

COMMIT;

END;
SELECT c.*

FROM customer_order_det_tb c;

--------------------------------------------

custm_id custm_nm order_dt ttl_amt

--------------------------------------------

100 Murugappan 7/11/2015 45000.00

100 Murugappan 7/14/2015 27000.00

101 Raja 7/13/2015 17000.00

102 Ramesh 7/15/2015 34000.00

102 Ramesh 7/15/2015 38000.00

--------------------------------------------

--Writing a Quer to display all the customer who have placed maximum number of order

--Query #1 for inline view

SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC;

--------------------------------

custm_id custm_nm total_odr


--------------------------------

100 Murugappan 2

102 Ramesh 2

101 Raja 1

--------------------------------

--Query #2 for inline view

SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm;

----------

total_odr

----------

----------

Inline view to find all the customers who have placed maximum number of orders

/****************************************

Syntax

SELECT * FROM <query1> x, <query2> y

WHERE contition;
****************************************/

SELECT query1.* FROM

( SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC

) query1,

( SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm

) query2

WHERE query1.total_odr = query2.total_odr;

-------------------------------

custm_id custm_nm total_odr

-------------------------------

100 Murugappan 2

102 Ramesh 2

-------------------------------

DROP TABLE customer_order_det_tb;

--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT
SELECT first_name, salary

FROM ( SELECT first_name, salary

FROM employees e

WHERE job_id NOT IN ('SALESMAN','PRESIDENT')

ORDER BY salary DESC

WHERE ROWNUM < 4;

New Oracle 12c Inline view Syntax

LATERAL clause for In-line views

Allows for columns in the inline view to be accessed!!

Example :

--in 11g

SELECT * FROM employees e, (

SELECT *

FROM departments d

WHERE e.department_id = d.department_id);

ORA-0090: "E"."DEPARTMENT_ID": Invalid Identifier


--in 12c

SELECT * FROM employees e, LATERAL(

SELECT *

FROM departments d

WHERE e.department_id = d.department_id

);

--in 11g

WITH t

AS

( SELECT LEVEL a

FROM dual

CONNECT BY LEVEL <= 30)

SELECT *

FROM t, (SELECT *

FROM employees

WHERE department_id = t.a

);

ORA-00904: "T"."A": invalid Identifier

--in 12c
WITH t

AS

(SELECT LEVEL a FROM dual CONNECT BY LEVEL <= 30)

SELECT * FROM t,

LATERAL(SELECT *

FROM employees

WHERE department_id = t.a);

Hope you have enjoyed this little article

Feed backs are always Welcome :) (:

Posted 20th July 2015 by Unknown

0 Add a comment

JAN

23

Salary Related Questions in Oracle

--creating table

CREATE TABLE employee_data


(

eid NUMBER(4),

ename VARCHAR2(30),

depno NUMBER(3),

salary NUMBER(8)

);

BEGIN

--Inserting records

INSERT INTO employee_data VALUES(1000,'Name01',90,30000);

INSERT INTO employee_data VALUES(1001,'Name02',90,6000);

INSERT INTO employee_data VALUES(1002,'Name03',90,23000);

INSERT INTO employee_data VALUES(1003,'Name04',60,35000);

INSERT INTO employee_data VALUES(1004,'Name05',60,60000);

INSERT INTO employee_data VALUES(1005,'Name06',60,30000);

INSERT INTO employee_data VALUES(1006,'Name07',80,36000);

INSERT INTO employee_data VALUES(1007,'Name08',80,29000);

INSERT INTO employee_data VALUES(1008,'Name09',80,37000);

INSERT INTO employee_data VALUES(1009,'Name10',80,41000);

COMMIT;

END;

/
SELECT * FROM employee_data

ORDER BY salary DESC;

--query to find maximum salary from employee_data table

SELECT MAX(salary) FROM employee_data;

--query to find minimum salary from employee_data table

SELECT MIN(salary) FROM employee_data;

--query to find second maximum salary from employee_data table

SELECT MAX(salary)

FROM employee_data

WHERE salary NOT IN (SELECT MAX(salary)

FROM employee_data);

--query to select 5th maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data
ORDER BY salary DESC)

WHERE rownum <= 5);

--query to select nth maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= &n);

--query to select all the details of the employee whose getting nth maximum salary

SELECT *

FROM (SELECT emp.*,

rownum rn

FROM (SELECT *

FROM employee_data

ORDER BY salary DESC) emp)

WHERE rn = 9;

--same query using row_numbr( ) function


SELECT *

FROM (SELECT emp.*,

row_number() over(ORDER BY salary) rank

FROM employee_data emp)

WHERE rank = 9;

--same query using rank( ) function

SELECT *

FROM (SELECT emp.*,

rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--same query using dense_rank( ) function

SELECT *

FROM (SELECT emp.*,

dense_rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--query to display display maximum salary in all the department


SELECT e.depno "Department id",

MAX(salary) "Maximum Salary"

FROM employee_data e

GROUP BY e.depno;

--query to display all the employees who are all getting salary more than average salary of the
company

SELECT e.* FROM employee_data e

WHERE salary > (SELECT AVG(salary) FROM employee_data);

--query to display all the employees who are all getting salary more than their department
average salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE department_id = OUT.department_id);

--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE employee_id = OUT.manager_id);

Documented By : Murugappan Annamalai

Posted on : 23-Jan-15 16:34:00 IST.

Hope you have enjoyed this little article

Feed backs are always welcome :)

Posted 23rd January 2015 by Unknown

7 View comments

JAN

22

Why prefer COALESCE over NVL


Documented By : Nimish Garg

I prefer using "COALESCE" over "NVL" is some of the scenarios. Last week One of my friend
asked me what is the advantage of using "COALESCE" where we can simply use "NVL". I simply
gave him the reply from Oracle Docs i.e. NVL lets you replace null (returned as a blank) with a
string in the results of a query and COALESCE returns the first non-null expr in the expression list.
Oracle Database uses short-circuit evaluation with "COALESCE".

He replied that he knows the difference, he knows that "COALESCE" can take multiple arguments
and so on. He was more interested in understanding "short-circuit evaluation" of "COALESCE"
and the scenarios where I prefer using "COALESCE" over "NVL".

To make him understand I created following function which takes One second in every execution
and simply returns '--null--' and executed 2 very similar queries one with NVL and other with
COALESCE.

SQL> create or replace function f_null return varchar2

2 is

3 begin

4 dbms_lock.sleep(1);

5 return '--null--';

6 end;

7 /

Function created.

Following are the queries which I used to demonstrate that NVL evaluates both arguments even
if the second argument is not used and COALESCE uses short-circuit evaluation i.e. it only
evaluates the arguments only if they are needed.

SQL> select e.empno, e.ename ename, nvl(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.
Elapsed: 00:00:14.01

SQL> select e.empno, e.ename ename, coalesce(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.
Elapsed: 00:00:01.01

Here we can see easily that the first query with NVL took 14+ seconds, one second for each
record even if the "f_null" value was used only in one record. On the contrary as mentioned in
Oracle Documentation "COALESCE" uses its "short-circuit evaluation" and "f_null" was called
only once and so second query took only One Second. "COALESCE" is certainly use less resources
than NVL.

Posted 22nd January 2015 by Unknown

0 Add a comment

DEC

21

Constraints

It Enforce Rule On Table

We can create constraint at the time of Creating Table

1. Column Level Declaration

2. Table Level Declaration


1. We can provide own name.

Format : [part_of_project_name-table_name-column_name-constraint_type]

Example : gmind_emp_id_pk _uk _ck _f

2. system name name

Format : sys_cn

Example : SYS_C405323

We can create constraint after the table has been created

Types

Primary Key

Not allowed Null value

Not allowed you to enter duplicate value

Ex : Employee_id, Student_id

Unique Key
allowed Null value

Not allowed you to enter duplicate value

Ex : Contact_no, email

Foreign Key

It will allowed you to enter NULL and Duplicate value.

c1(pk) : 1 2 3

c2(f) : 1 1 2 3 4 Not allowed

Allowed you to enter duplicate value and null value

Not Null

It will not allowed you to enter null value

Check

You can check your own condition

Simple Table for understanding


------------------------------------

Duplicate NULL

------------------------------------

Primary Key X X

Unique Key X Allowed

Foreign Key Allowed Allowed

------------------------------------

creating table with all constraint type

Create table my_stu_details

S_id Number(2),

S_name Varchar2(30) Not Null, --SYS_Cn

s_mail Varchar2(30),

s_gender char(1),

s_did Number(3),

Constraint my_stu_sid_pk PRIMARY KEY (s_id),

constraint my_stu_mail_uk UNIQUE (s_mail) ,

Constraint my_stu_gen_ck CHECK (s_gender IN ('M', 'F', 'm', 'f')),

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

);
DESC my_stu_details;

------------------------------------

Name Type Nullable

------------------------------------

S_ID NUMBER(2)

S_NAME VARCHAR2(30)

S_MAIL VARCHAR2(30) Y

S_GENDER CHAR(1) Y

S_DID NUMBER(3) Y

------------------------------------

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name1' , 'name1@gmail.com' , 'm' , 60 );

Select * from my_stu_details;

Validating Primary Key


Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-00001: unique constraint (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (NULL, 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-01400: cannot insert NULL into (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (2 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

Validating NOT NULL Constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , NULL , 'name3@gmail.com' , 'F' , 80 );


ORA-01400: cannot insert NULL into ("HR"."MY_STU_DETAILS"."S_NAME")

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , 'Name3' , 'name3@gmail.com' , 'F' , 80 );

Select * from my_stu_details;

Validating Unique Key Constraint

--Duplicate Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , 'name3@gmail.com' , 'F' , 80 );

ORA-00001: unique constraint (HR.MY_STU_MAIL_UK) violated

--Null Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , null , 'M' , 70 );


Select * from my_stu_details;

Validating Check constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'j' , 70 );

ORA-02290: check constraint (HR.MY_STU_GEN_CK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'M' , 70 );

Select * from my_stu_details;

Validating Foreign Key

Select * from Departments;


Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 3 );

ORA-02291: integrity constraint (HR.MY_STU_DID_FK) violated - parent key not found

Departments table : parent table

my_stu_details : Child table

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

--------------------------------------------------------

s_id s_name s_mail s_gender s_did

--------------------------------------------------------

1 name1 name1@gmail.com m 60

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 M 70
5 Name5 name5@gmail.com M 70

6 Name6 name6@gmail.com F 90

--------------------------------------------------------

Deleting the Primary key value which is referred by Foreign Key

Select * from Departments;

DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID

------------------------------------------------------------

60 IT 103 1400 <---- Delete

-- don't execute this query

--Delete From Departments

--Where Department_id = 60;

1) ON DELETE SET NULL

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID


-------------------------------------------------

6 Name6 name6@gmail.com F 90

1 name1 name1@gmail.com m -

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

2) ON DELETE SET CASCADE

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

Syntax

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE CASCADE
Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE SET NULL

Constraint Related Data Dictionary Table information.

To view constraint Information

SELECT c.owner,

c.constraint_name,

c.constraint_type,

c.table_name,

c.r_constraint_name,

c.status

FROM user_constraints c

WHERE c.table_name = 'MY_STU_DETAILS';

------------------------------------------------------------------------------------

owner constraint_name constraint_type table_name r_constraint_name status

------------------------------------------------------------------------------------

HR SYS_C004023 C MY_STU_DETAILS ENABLED

HR MY_STU_GEN_CK C MY_STU_DETAILS ENABLED


HR MY_STU_SID_PK P MY_STU_DETAILS ENABLED

HR MY_STU_MAIL_UK U MY_STU_DETAILS ENABLED

HR MY_STU_DID_FK R MY_STU_DETAILS DEPT_ID_PK ENABLED

------------------------------------------------------------------------------------

To view constraint name with corresponding column name

SELECT * FROM user_cons_columns c

WHERE c.table_name = 'MY_STU_DETAILS';

-------------------------------------------------------------

owner constraint_name table_name column_name position

-------------------------------------------------------------

HR MY_STU_MAIL_UK MY_STU_DETAILS S_MAIL 1

HR MY_STU_SID_PK MY_STU_DETAILS S_ID 1

HR MY_STU_GEN_CK MY_STU_DETAILS S_GENDER

HR SYS_C004023 MY_STU_DETAILS S_NAME

HR MY_STU_DID_FK MY_STU_DETAILS S_DID 1

-------------------------------------------------------------

Creating Composite Primary Key


Creating Primary Key with more than one number of column

ALTER TABLE table_name

ADD CONSTRAINT constraint_name PRIMARY KEY(column1, column_2 , column3);

In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.

creating constraint after the table creation

ALTER TABLE table_name

ADD CONSTRAINT constraint_name CONSTRAINT_TYPE(column_name);

ALTER TABLE table_name

DROP CONSTRAINT constraint_name;

ALTER TABLE table_name

DROP PRIMARY KEY;

To drop related foreign key


ALTER TABLE table_name

DROP PRIMARY KEY CASCADE;

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name;

Disable constraint with related foreign key constraint

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name CASCADE;

ALTER TABLE table_name

ENABLE CONSTRAINT constraint_name;

Interview Questions

What are all the type of constraint available in oracle?

Difference between PRIMARY KEY and UNIQUE key.

Difference between PRIMARY KEY ans FOREIGN KEY.

Difference between UNIQUE key and FOREIGN KEY.


Is it possible to create tow primary key in single table.

Write a syntax to create FOREIGN constraint.

How to create constraint after the table has been created?

How to enable and disable a constraint.

Which data dictionary table contains information about constraints?

Which Data Dictionary table contains information about constraint with corresponding column
name?

What is composite primary key?

Explain ON DELETE CASCADE and ON DELETE SET NULL option.

~Thanks For Reading~

Post your valuable feedback below

Posted 21st December 2014 by Unknown

1 View comments

UnknownMay 22, 2017 at 12:39 AM

good

Reply
DEC

listagg in Oracle 11g

Oracle 11gR2 listagg built-in function allows for many table columns to be displayed within a
single row, a non-first-normal form display

Syntax :

listagg(column_value,'delimiter') WITHIN GROUP(ORDER BY column_name)

--Example 1:

CREATE TABLE test_ins(empid NUMBER,product VARCHAR2(30));

BEGIN

INSERT INTO test_ins VALUES( 101,'pendrive');

INSERT INTO test_ins VALUES( 102,'toy');

INSERT INTO test_ins VALUES( 101,'ipod');

INSERT INTO test_ins VALUES( 102,'hat');

INSERT INTO test_ins VALUES( 103,'cpu');

INSERT INTO test_ins VALUES( 104,'pen');

INSERT INTO test_ins VALUES( 104,'car');

INSERT INTO test_ins VALUES( 104,'mat');

INSERT INTO test_ins VALUES( 105,'tv');


INSERT INTO test_ins VALUES( 106,'laptop');

commit;

END;

SELECT * FROM test_ins;

SELECT empid "Employee",

listagg(product,

',') within

GROUP (ORDER BY empid) "Products"

FROM test_ins

GROUP BY empid;

-->-- Result set --<--


DROP TABLE test_ins;

-->-- Example 2

select department_id "Department id", listagg(first_name,', ') WITHIN GROUP(ORDER BY


employee_id) "Employees"

FROM employees

WHERE department_id IN (10,20,30,60)

GROUP BY department_id;

-->-- Result set --<--

Posted 4th December 2014 by Unknown

0 Add a comment

NOV

Condition and Looping Statement


IF

IF ELSE

Multiple IF ELSE

LOOP

FOR LOOP

WHILE LOOP

create table test_udt(id NUMBER, salary NUMBER);

BEGIN

INSERT INTO test_udt VALUES(001,23000);

INSERT INTO test_udt VALUES(002,43000);

INSERT INTO test_udt VALUES(003,78000);

INSERT INTO test_udt VALUES(004,25000);

INSERT INTO test_udt VALUES(005,26000);

INSERT INTO test_udt VALUES(006,90000);

Commit;

END;

select * from test_udt;


IF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 1;

IF v_salary > 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

END IF;

commit;

END;

IF ELSE
DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

ELSE

UPDATE test_udt t

SET t.salary = v_salary+20007

WHERE t.id = v_id ;

END IF;

commit;

END;

--same example with less number of lines


DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

v_salary := v_salary+10005;

ELSE

v_salary := v_salary+20007;

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;


Multiple IF ELSIF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 3;

IF v_id = 1 THEN

v_salary := 1000;

dbms_output.put_line('1 inside');

ELSIF v_id = 2 THEN

v_salary := 2000;

dbms_output.put_line('2 inside');

ELSIF v_id = 3 THEN

v_salary := 3000;

dbms_output.put_line('3 inside');

ELSIF v_id = 4 THEN

v_salary := 4000;

dbms_output.put_line('4 inside');

END IF;
UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

LOOP

--syntax

LOOP

--statements

--increment

--exit statement

END LOOP;

CREATE TABLE prod_details (pid VARCHAR2(3), pname VARCHAR2(30));

DECLARE

i NUMBER := 1;
x VARCHAR2(3);

BEGIN

LOOP

x := lpad(i,3,'0');

dbms_output.put_line('x value : '|| x);

INSERT INTO prod_details VALUES(i, 'Product '||i);

EXIT WHEN i >900;

i := i+1;

IF MOD(i,100) = 0 THEN

commit;

dbms_output.put_line('commit executed');

END IF;

END LOOP;

END;

SELECT * FROM prod_details ORDER BY 1;

DROP TABLE prod_details;

FOR LOOP

BEGIN

FOR I in 1..5
LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

FOR LOOP - Reverse

BEGIN

FOR I in REVERSE 14..50

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

WHILE LOOP

DECLARE

i_val NUMBER:=0;

BEGIN

WHILE (i_val < 11)

LOOP

dbms_output.put_line('The value of I is '||i_val);

i_val := i_val + 1;
END LOOP;

END;

sample output:

The value of I is 0

The value of I is 1

The value of I is 2

The value of I is 3

The value of I is 4

The value of I is 5

The value of I is 6

The value of I is 7

The value of I is 8

The value of I is 9

The value of I is 10

Posted 8th November 2014 by Unknown

0 Add a comment

OCT
21

Bulk Collect

This is used for array fetches

With this you can retrieve multiple rows of data with a single round trip.

This reduces the number of context switches between the pl/sql and sql engines.

You can use bulk collect in both dynamic and static sql.

You can use bulk collect in select, fetch into and returning into clauses.

SQL engine automatically initializes and extends the collections you reference in the bulk
collect clause.

You can fetch into multiple collections with one column each.

You can use the limit clause of bulk collect to restrict the no of rows retrieved.

SELECT * FROM product_details;

-->-- Bulk collect in FETCH INTO --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN
OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Bulk collect in SELECT clause --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

BEGIN

SELECT * BULK COLLECT INTO dta FROM product_details;

FOR i IN dta.FIRST .. dta.LAST LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;
-->-- LIMIT in Bulk collect --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta LIMIT 30;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Multiple fetches in INTO clause --<--

SELECT * FROM product_details;


DECLARE

TYPE alldata_typ1 IS TABLE OF product_details.p_id%TYPE;

TYPE alldata_typ2 IS TABLE OF product_details.p_name%TYPE;

dta1 alldata_typ1;

dta2 alldata_typ2;

CURSOR proddt_cur IS

SELECT p_id, p_name FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta1, dta2;

CLOSE proddt_cur;

FOR i IN dta1.FIRST .. dta1.COUNT LOOP

dbms_output.put_line('Department Id : ' || dta1(i));

END LOOP;

FOR i IN dta2.FIRST .. dta2.COUNT LOOP

dbms_output.put_line('Department Name : ' || dta2(i));

END LOOP;

END;

/
DROP TABLE dep_details;

DROP TABLE product_details;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Ref Cursor

This is unconstrained cursor which will return different types depends upon the user input.

Ref cursors cannot be closed implicitly.

Ref cursor with return type is called strong cursor.

Ref cursor without return type is called weak cursor.

You can declare ref cursor type in package spec as well as body.

You can declare ref cursor types in local subprograms or anonymous blocks.

CREATE OR REPLACE PROCEDURE ref_c_sp(dep_det_c IN OUT SYS_REFCURSOR)

AS

BEGIN

OPEN dep_det_c
FOR

SELECT * FROM dep_details d;

END;

DECLARE

dep_det_c SYS_REFCURSOR;

tab_data dep_details%ROWTYPE;

BEGIN

ref_c_sp(dep_det_c);

LOOP

FETCH dep_det_c INTO tab_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department Name : '|| tab_data.d_name);

END LOOP;

CLOSE dep_det_c;

END;

/*sample output*/

Department Name : Admin

Department Name : HR
Department Name : Sales

Department Name : Marketing

DROP PROCEDURE ref_c_sp;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Cursor

SQL Private work Area where the query get passed and executed.

Types

******

Implicit(SQL)

Explicit

-->-- advanced cursor types --<--

Parametrized Cursor

Ref Cursor
Implicit

********

ORACLE implicitly opens a cursor to process each SQL statement not associated with an
explicitly declared cursor.

PL/SQL lets you refer to the most recent implicit cursor as the SQL” cursor. So, although you
cannot use the OPEN,

FETCH, and CLOSE statements to control an implicit cursor, you can still use cursor attributes to
access information

about the most recently executed SQL statement.

Cursor Stages

**************

OPEN cursor_name

FETCH (with in loop)

CLOSE cursor_name

Explicit

The set of rows returned by a query can consist of zero, one, or multiple rows,

depending on how many rows meet your search criteria. When a query returns multiple rows,

you can explicitly define a cursor to process the rows. You use three commands to control the
cursor
Cursor Attributes

*****************

%FOUND

%NOTFOUND

%ISOPEN

%ROWCOUNT

%BULK_ROWCOUNT --<-- used to handle error while using bulk collection.

%BULK_EXCEPTIONS --<-- used to handle error while using bulk collection.

Cursor Declaration

DECLARE

CURSOR <cursor_name>

IS

<SELECT statement>

BEGIN

--> some stmt

END;

Cursor Loop

Loop

While Loop

For Loop
Cursor Clauses

Return

For update

Where current of

Bulk collect

-->-- creating table

create table product_details

p_id NUMBER,

p_name VARCHAR2(30),

p_order_dt DATE

);

-->-- Inserting data

BEGIN

FOR i IN 1 .. 75 LOOP

INSERT INTO product_details VALUES (i, 'prod_name_' || i, SYSDATE + i);

END LOOP;

commit;

END;
-->-- selecting data

SELECT * FROM product_details;

---------------------------------------------

p_id p_name p_order_dt

---------------------------------------------

1 prod_name_1 10/11/2014 3:48:32 PM

2 prod_name_2 10/12/2014 3:48:32 PM

3 prod_name_3 10/13/2014 3:48:32 PM

4 prod_name_4 10/14/2014 3:48:32 PM

5 prod_name_5 10/15/2014 3:48:32 PM

6 prod_name_6 10/16/2014 3:48:32 PM

7 prod_name_7 10/17/2014 3:48:32 PM

8 prod_name_8 10/18/2014 3:48:32 PM

9 prod_name_9 10/19/2014 3:48:32 PM

10 prod_name_10 10/20/2014 3:48:32 PM

11 prod_name_11 10/21/2014 3:48:32 PM

12 prod_name_12 10/22/2014 3:48:32 PM

13 prod_name_13 10/23/2014 3:48:32 PM

14 prod_name_14 10/24/2014 3:48:32 PM

15 prod_name_15 10/25/2014 3:48:32 PM

16 prod_name_16 10/26/2014 3:48:32 PM


17 prod_name_17 10/27/2014 3:48:32 PM

18 prod_name_18 10/28/2014 3:48:32 PM

19 prod_name_19 10/29/2014 3:48:32 PM

20 prod_name_20 10/30/2014 3:48:32 PM

---------------------------------------------

----------------------------------------------

Implicit Cursor

----------------------------------------------

--will update soon

----------------------------------------------

Explicit Cursor

----------------------------------------------

**********************************************

Processing cursor data by using LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS
SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND; --<-- if next record not found means control will
come out from the loop

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )


DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

EXIT WHEN prod_detail_cur%FOUND; --<-- if next record found means control will come
out from the loop

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )


DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;
END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor Already closed

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP
FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

-->-- CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )


Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor closed

**********************************************

Processing cursor data by using WHILE LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

OPEN prod_detail_cur;

FETCH prod_detail_cur

INTO all_data;

WHILE prod_detail_cur%FOUND LOOP

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');


FETCH prod_detail_cur

INTO all_data;

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

************************************************************

Processing cursor data by using FOR LOOP - CURSOR FOR LOOP

************************************************************

DECLARE

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

FOR i IN prod_detail_cur
LOOP

dbms_output.put_line('Product id : ' || i.p_id ||

' Product Name : ' || i.p_name ||

' ( Orderd on : ' || TRIM(i.p_order_dt) || ' )');

END LOOP;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

Parameterized Cursor

*********************

This was used when you are going to use the cursor in more than one place with different
values for the same where clause.

Cursor parameters must be in mode.

Cursor parameters may have default values.

The scope of cursor parameter is within the select statement.


CREATE TABLE dep_details(d_id NUMBER,d_name VARCHAR2(30), location_id NUMBER);

BEGIN

INSRT INTO dep_details VALUES(001,'Admin',1010);

INSRT INTO dep_details VALUES(002,'HR',1010);

INSRT INTO dep_details VALUES(003,'Sales',1020);

INSRT INTO dep_details VALUES(004,'Marketing',1020);

commit;

END;

SELECT * FROM dep_details;

----------------------------

d_id d_name location_id

----------------------------

1 Admin 1010

2 HR 1010

3 Sales 1020

4 Marketing 1020

----------------------------
DECLARE

-->--Declaring parameterized cursor

CURSOR dep_det_c(p_location_id NUMBER) IS

SELECT * FROM dep_details d WHERE d.location_id = p_location_id;

all_data dep_details%ROWTYPE;

BEGIN

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

OPEN dep_det_c(1010);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

-->-- opening same cursor with different input value

OPEN dep_det_c(1020);

LOOP

FETCH dep_det_c

INTO all_data;
EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

END;

/*sample output*/

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 1 Department Name : Admin

Department id : 2 Department Name : HR

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 3 Department Name : Sales

Department id : 4 Department Name : Marketing

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Posted 21st October 2014 by Unknown

0 Add a comment
OCT

21

Handling Exception

Error Handling in oracle

ERROR

Any departure from the expected behavior of the system or program,

which stops the working of the system is an error.

Types : compile time error

Run time error

EXCEPTION

Any error or problem which one can handle and continue to work normally.

Handling Exception

When exception is raised, control passes to the exception section of the block.

i.e. EXCEPTION

WHEN name_of_exception THEN

Types : Pre Defined Exceptions

User Defined Exceptions


Predefined Exception

*********************

Oracle has predefined several exceptions that correspond to the most common oracle errors.

------------------------------------------------------------------------

Exception Oracle Error SQL Code Value

------------------------------------------------------------------------

ZERO_DIVIDE ORA-01476 -1476

NO_DATA_FOUND ORA-01403 +100

DUP_VAL_ON_INDEX ORA-00001 -1

TOO_MANY_ROWS ORA-01422 -1422

VALUE_ERROR ORA-06502 -6502

CURSOR_ALREADY_OPEN ORA-06511 -6511

OTHERS

------------------------------------------------------------------------

-->-- ZERO_DIVIDE --<--

Your program attempts to divide a number by zero.

DECLARE

v_result NUMBER;
BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN ZERO_DIVIDE THEN

dbms_output.put_line('Divisor is equal to zero');

END;

-->-- NO_DATA_FOUND --<--

Single row SELECT returned no rows or your program referenced a deleted element in a nested
table

or an uninitialized element in an associative array (index-by table).

CREATE TABLE test_tb(id NUMBER PRIMARY KEY);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN NO_DATA_FOUND THEN

dbms_output.put_line('There is no data inside the table');

END;
-->-- DUP_VAL_ON_INDEX --<--

A program attempted to insert duplicate values in a column that is constrained by a unique


index.

INSERT INTO test_tb VALUES (1);

INSERT INTO test_tb VALUES (2);

commit;

BEGIN

INSERT INTO test_tb VALUES (2);

EXCEPTION

WHEN DUP_VAL_ON_INDEX THEN

dbms_output.put_line('Duplicate values are not allowed');

END;

-->-- TOO_MANY_ROWS --<--

Single row SELECT returned multiple rows.

DECLARE

v_id NUMBER;
BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN TOO_MANY_ROWS THEN

dbms_output.put_line('Query returning more than one row');

END;

DROP TABLE test_tb;

-->-- VALUE_ERROR --<--

An arithmetic, conversion, truncation, or size constraint error occurred.

DECLARE

num1 NUMBER(2);

BEGIN

num1 := 345;

EXCEPTION

WHEN VALUE_ERROR THEN

dbms_output.put_line('check the size of the variable');

END;

-->-- CURSOR_ALREADY_OPEN --<--


A program attempted to open an already opened cursor.

CREATE TABLE emp(id NUMBER, name VARCHAR2(30));

BEGIN

INSERT INTO emp VALUES(1,'Name1');

INSERT INTO emp VALUES(2,'Name2');

INSERT INTO emp VALUES(3,'Name3');

INSERT INTO emp VALUES(4,'Name4');

COMMIT;

END;

SELECT * FROM emp;

DECLARE

cursor emp_c IS

SELECT * FROM emp;

all_data emp%ROWTYPE;

BEGIN

OPEN emp_c;

OPEN emp_c;

NULL;
CLOSE emp_c;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

END;

DROP TABLE emp;

-->-- OTHERS --<--

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

WHEN OTHERS THEN

dbms_output.put_line('Some other error ' || SQLERRM);

END;

User Defined Exception

**********************
A user-defined exception is an error that is defined by the programmer.

User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,

exceptions have a type EXCEPTION and scope.

DECLARE

v_gender CHAR := '&gender';

gender_ex EXCEPTION;

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE gender_ex;

END IF;

dbms_output.put_line('Gender : '||v_gender);

EXCEPTION

WHEN gender_ex THEN

dbms_output.put_line('Please Enter valid gender');

END;

create table test_insert (id NUMBER, Name VARCHAR2(30));

DECLARE

abort_ex EXCEPTION;
BEGIN

FOR i IN 1..100

LOOP

BEGIN

IF mod(i,10)=0 THEN

RAISE abort_ex;

END IF;

INSERT INTO test_insert VALUES(i, 'Name'||i);

EXCEPTION

WHEN abort_ex THEN

NULL;

END;

END LOOP;

COMMIT;

END;

SELECT * FROM test_insert;

DROP TABLE test_insert;

SQLERRM and SQLCODE

********************

SQLCODE returns the current error code, and SQLERRM returns the current error message
text;
For user-defined exception SQLCODE returns 1 and SQLERRM returns “user-defined
exception”.

SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.

CREATE TABLE test_tb (id NUMBER);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

dbms_output.put_line(v_id);

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('SQLERRM : ' || SQLERRM);

dbms_output.put_line('SQLCODE : ' || SQLCODE);

END;

/*sample output*/

SQLERRM : ORA-01403: no data found

SQLCODE : 100

DROP TABLE test_tb;


PRAGMA EXCEPTION_INIT

*********************

Using this you can associate a named exception with a particular oracle error.

This gives you the ability to trap this error specifically, rather than via an OTHERS handler.

Syntax:

PRAGMA EXCEPTION_INIT(exception_name, oracle_error_number);

DECLARE

v_result NUMBER;

PRAGMA EXCEPTION_INIT(Invalid, -1476);

BEGIN

SELECT 453 / 0 INTO v_result FROM dual;

dbms_output.put_line('Result : ' || v_result);

EXCEPTION

WHEN INVALID THEN

dbms_output.put_line('Invalid Exception');

END;

RAISE_APPLICATION_ERROR
************************

You can use this built-in function to create your own error messages, which can be more
descriptive than named exceptions.

Error Number :

Oracle Error Range : From -00000 to -19999

User Error Range : From -20000 to -20999

DECLARE

v_gender CHAR := '&gender';

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE_APPLICATION_ERROR(-20003, 'Enter valid gender');

END IF;

dbms_output.put_line('Gender : ' || v_gender);

END;

Posted 21st October 2014 by Unknown

1 View comments
RajmohanMarch 13, 2018 at 6:49 AM

How to get the two table data without using Joins and sub query,union?

Reply

OCT

Package

1. You can groups logical related subprogram (procedures and functions)

2. It consist of two parts

I) specification

II) Body

3. It allows the oracle server to read multiple object in to a memory once

4. You can declare global variable,cursor, user define exeption

5. Overloading

6. we can't create anonyms block inside the package

create table err_log(sno NUMBER, u_name VARCHAR2(30), error_msg CLOB, hap_tm


TIMESTAMP);

select * from err_log;


--stand alone procedure

CREATE OR REPLACE PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id


%TYPE) IS

v_salary employees.salary%TYPE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT salary,

first_name

INTO v_salary,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line('Salary of ' || v_first_name || ' is ' || v_salary);

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);
commit;

END emp_sal_sp;

BEGIN

-- Call the procedure

emp_sal_sp(p_employee_id => :p_employee_id);

END;

CREATE OR REPLACE PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id


%TYPE) IS

v_hire_date DATE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT hire_date,

first_name

INTO v_hire_date,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line(v_first_name || ' hired on ' || to_char(v_hire_date,'month ddth,


yyyy'));

EXCEPTION

WHEN OTHERS THEN


v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_hdt_sp;

BEGIN

-- Call the procedure

emp_hdt_sp(p_employee_id => :p_employee_id);

END;

create or replace function sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER

IS

v_c NUMBER;

BEGIN

v_c := p_a + p_b;

RETURN v_c;
END;

--Specification Part

CREATE OR REPLACE PACKAGE emp_pkg

IS

PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id%TYPE);

PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id%TYPE);

FUNCTION sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER;

END emp_pkg ;

--Body Part

CREATE OR REPLACE PACKAGE BODY emp_pkg

IS

PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id%TYPE) IS

v_salary employees.salary%TYPE;
v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT salary,

first_name

INTO v_salary,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line('Salary of ' || v_first_name || ' is ' || v_salary);

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_sal_sp;

PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id%TYPE) IS

v_hire_date DATE;
v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT hire_date,

first_name

INTO v_hire_date,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line(v_first_name || ' hired on ' || to_char(v_hire_date,'month ddth,


yyyy'));

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_hdt_sp;

FUNCTION sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER

IS
v_c NUMBER;

BEGIN

v_c := p_a + p_b;

RETURN v_c;

END;

END emp_pkg;

A package specification can exist without a package body, but

a package body can't exist without a package specification.

--Executing procedure inside the package

BEGIN

emp_pkg.emp_sal_sp(120);

END;

--Executing function inside the package

SELECT emp_pkg.sum_fn(23,567) FROM dual;

-- You can declare global variable,cursor, user define exeption


create or replace package all_detail

as

PROCEDURE emp2sal (a IN NUMBER);

PROCEDURE emp2exep (a IN NUMBER);

FUNCTION add2num (a IN NUMBER, b IN NUMBER)

RETURN NUMBER;

c NUMBER(8); --global declaration

abort_ex EXCEPTION; --global exception declaration

CURSOR emp_rec --global cursor declaration

IS

SELECT first_name, salary, hire_date, department_id

FROM employees;

End all_detail;

create or replace package body all_detail

as

PROCEDURE emp2sal (a IN NUMBER)


AS

BEGIN

SELECT salary

INTO c

FROM Employees

WHERE Employee_id = a;

Dbms_output.put_line('Salary of Employee ' || a || ' is ' || c);

EXCEPTION

WHEN no_data_found THEN

Dbms_output.put_line('Please enter valid id');

END emp2sal;

PROCEDURE emp2exep (a IN NUMBER)

AS

BEGIN

SELECT Round(Months_between(sysdate,hire_date)/12)

INTO c

FROM Employees

WHERE Employee_id = a;

Dbms_output.put_line( c || ' Years');

EXCEPTION
WHEN no_data_found THEN

Dbms_output.put_line('Please enter valid id');

END emp2exep;

FUNCTION add2num (a IN NUMBER, b IN NUMBER)

RETURN NUMBER

AS

BEGIN

c := a+b;

RETURN C;

END;

End all_detail;

/*Declaring a Bodiless Package */

CREATE OR REPLACE PACKAGE global_constant

IS

mile_2_kilo CONSTANT NUMBER := 1.6093;

kilo_2_mile CONSTANT NUMBER := 0.6214;

yard_2_meter CONSTANT NUMBER := 0.9144;


meter_2_yard CONSTANT NUMBER := 1.0936;

END global_constant;

BEGIN

DBMS_OUTPUT.PUT_LINE('20 miles = ' || 20*global_constant.mile_2_kilo||' km');

END;

/*Forward Declaration in package */

DECLARE

PROCEDURE P2; -- forward declaration

PROCEDURE P3;

PROCEDURE P1 IS

BEGIN

dbms_output.put_line('From procedure p1');

p2;

END P1;

PROCEDURE P2 IS

BEGIN

dbms_output.put_line('From procedure p2');

p3;
END P2;

PROCEDURE P3 IS

BEGIN

dbms_output.put_line('From procedure p3');

END P3;

BEGIN

p1;

END;

sample output:

From procedure p1

From procedure p2

From procedure p3

Drop package package_name;

Drop package body package_name;

SELECT text FROM user_source u

WHERE u.name = 'EMP_PKG';


Interview Questions:

What is package?

Advantage of package

Is it possible to create package body with out package specification?

what is package overloading?

what is forward declaration in package?

which data dictionary table contain source code of package?

How to declare global variable, exception and cursor?

How to execute procedure and function inside the package?

Posted 4th October 2014 by Unknown

0 Add a comment

OCT

%TYPE and %ROWTYPE

--%type is used to fetch the data type of the particular column


create table product_details

p_id NUMBER(3),

p_nm VARCHAR2(30),

p_qty NUMBER(8),

order_dt DATE

);

BEGIN

INSERT INTO product_details VALUES(100,'Name0',400,'23-Mar-13');

INSERT INTO product_details VALUES(101,'Name1',600,'26-Apr-13');

INSERT INTO product_details VALUES(102,'Name2',800,'27-Jan-12');

INSERT INTO product_details VALUES(103,'Name3',300,'23-Jul-11');

INSERT INTO product_details VALUES(104,'Name4',200,'22-Aug-11');

INSERT INTO product_details VALUES(105,'Name5',500,'25-Oct-12');

commit;

END;

SELECT * FROM product_details;

------------------------------------

P_ID P_NM P_QTY ORDER_DT


------------------------------------

100 Name0 400 03/23/2013

101 Name1 600 04/26/2013

102 Name2 800 01/27/2012

103 Name3 300 07/23/2011

104 Name4 200 08/22/2011

105 Name5 500 10/25/2012

------------------------------------

DECLARE

v_name VARCHAR2(4);

BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 100;

dbms_output.put_line('Product Name : ' || v_name);

--error numeric or value error

END;

DECLARE

v_name VARCHAR2(5);
BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 100;

dbms_output.put_line('Product Name : ' || v_name);

END;

ALTER TABLE product_details

MODIFY p_nm VARCHAR2(15);

INSERT INTO product_details

VALUES

(106,

'name6',

700,

'26-Dec-12');

commit;

106 name6 700 12/26/2012


DECLARE

v_name VARCHAR2(5);

BEGIN

SELECT p_nm INTO v_name

FROM product_details

WHERE p_id = 106;

dbms_output.put_line('Product Name : ' || v_name);

--error

END;

DECLARE

v_name product_details.p_nm%TYPE;

BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 106;

dbms_output.put_line('Product Name : ' || v_name);

END;
/

DROP TABLE product_details;

DECLARE

dep_id departments.department_id%TYPE;

dep_name departments.department_name%TYPE;

dep_man_id departments.manager_id%TYPE;

dep_loc_id departments.location_id%TYPE;

BEGIN

SELECT department_id,

department_name,

manager_id,

location_id

INTO dep_id,

dep_name,

dep_man_id,

dep_loc_id

FROM departments

WHERE department_id = 10;


dbms_output.put_line('Department_id : ' || dep_id);

dbms_output.put_line('Department_name : ' || dep_name);

dbms_output.put_line('Manager_id : ' || dep_man_id);

dbms_output.put_line('Location_id : ' || dep_loc_id);

END;

--%rowtype is used to fetch the data type of all the column

--Insted of using %type if we use %rowtype means we can reduce the no of variables that we
declare

DECLARE

dep_detail departments%ROWTYPE;

BEGIN

SELECT *

INTO dep_detail

FROM departments

WHERE department_id = 10;

dbms_output.put_line('Department_id : ' || dep_detail.department_id);


dbms_output.put_line('Department_name : ' || dep_detail.department_name);

dbms_output.put_line('Manager_id : ' || dep_detail.manager_id);

dbms_output.put_line('Location_id : ' || dep_detail.location_id);

END;

DROP TABLE dept_details;

CREATE TABLE dept_details

dept_id number(3) ,

dept_name varchar2(30),

dept_manager_name varchar2(30)

);

insert into dept_details values(10,'dept1','manager_name1');

insert into dept_details values(20,'dept2','manager_name2');

SELECT * FROM dept_details;

-------------------------------------------------------

| DEPT_ID | DEPT_NAME | DEPT_MANAGER_NAME |


+------------+-----------------------+-----------------

| 10 | dept1 | manager_name1 |

| 20 | dept2 | manager_name2 |

------------+-----------------------+------------------

DECLARE

all_data dept_details%ROWTYPE;

BEGIN

all_data.dept_id := 100;

all_data.dept_name := 'Admin';

all_data.dept_manager_name := 'John';

UPDATE dept_details

SET ROW = all_data

WHERE dept_id = 10;

dbms_output.put_line(SQL%ROWCOUNT || ' Row(s) get updated');

END;

1 Row(s) get updated


select * from dept_details;

---------------------------------------------------

| DEPT_ID | DEPT_NAME | DEPT_MANAGER_NAME|

---------------------------------------------------

| 100 | Admin | John |

| 20 | dept2 | manager_name2 |

---------------------------------------------------

Interview Question :

1. What is the use of %TYPE?

2. What is the use of %ROWTYPE?

3. Difference between %TYPE and %ROWTYPE?

Posted 2nd October 2014 by Unknown

0 Add a comment
SEP

29

BULK Exceptions

/************************************************************************

* Handling Exceptions in Bulk Operations *

* Documented on 29-SEP-14 04.35.35.980894 PM +05:30 *

* Document By : Murugappan Annamalai *

* Reference : http://www.dba-oracle.com/plsql/t_plsql_exceptions.htm *

************************************************************************/

CREATE TABLE bulk_tb (ran_num NUMBER NOT NULL);

--inserting data using bulk collect

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP
v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

commit;

END;

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

200

TRUNCATE TABLE bulk_tb;

sample2.sql --without exception part

DECLARE
TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

commit;

END;

/*

Error Message :

ORA-01400: cannot insert NULL into ("HR"."bulk_tb"."ran_num")

ORA-06512: at line 15

*/
sample2.sql --with exception part

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

BEGIN

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

COMMIT;

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('Error while inserting bulk record '||SQLERRM);


END;

END;

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

99

SQL%BULK_EXCEPTIONS(i).ERROR_INDEX

Holds the iteration (not the subscript) of the original FORALL statement that raised the
exception.

In sparsely populated collections,

the exception row must be found by looping through the original collection the correct
number of times.

SQL%BULK_EXCEPTIONS(i).ERROR_CODE

Holds the exceptions error code.


The total number of exceptions can be returned using the collections COUNT method,

which returns zero if no exceptions were raised. The save_exceptions.sql script,

a modified version of the handled_exception.sql script, demonstrates this functionality.

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

v_ex_count NUMBER(4);

abort_ex EXCEPTION;

PRAGMA EXCEPTION_INIT(abort_ex, -24381);

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

v_dat(150) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

EXECUTE IMMEDIATE 'TRUNCATE TABLE bulk_tb';


BEGIN

FORALL i IN v_dat.FIRST..v_dat.LAST SAVE EXCEPTIONS

INSERT INTO bulk_tb VALUES(v_dat(i));

COMMIT;

EXCEPTION

WHEN abort_ex THEN

v_ex_count := SQL%BULK_EXCEPTIONS.COUNT;

FOR i IN 1..v_ex_count LOOP

dbms_output.put_line('Error: ' || i ||' Array Index: ' || SQL


%BULK_EXCEPTIONS(i).error_index ||

' Message: ' || SQLERRM(SQL%BULK_EXCEPTIONS(i).ERROR_CODE));

END LOOP;

END;

END;

/*

Sample output:

Error: 1 Array Index: 100 Message: -1400: non-ORACLE exception

Error: 2 Array Index: 150 Message: -1400: non-ORACLE exception

*/
SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

198

SAVE EXCEPTIONS clause being removed, in the above script now traps a different error number.

The output from this script is listed below.

/*

Sample output:

Error: 1 Array Index: 100 Message: -1400: non-ORACLE exception

*/

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

99
SELECT COUNT(*) FROM bulk_tb;

DROP TABLE bulk_tb;

Posted 29th September 2014 by Unknown

0 Add a comment

SEP

29

Cursor - FOR UPDATE

/************************************************************************

* FOR UPDATE clause in oracle *

* Document By : Murugappan Annamalai *

************************************************************************/

create table prod_details(p_id VARCHAR2(30), P_name VARCHAR2(30));


BEGIN

--Inserting data into prod_details table

FOR i IN 1..50 LOOP

INSERT INTO prod_details VALUES(i,'pname'||i);

END LOOP;

commit;

END;

SELECT * FROM prod_details;

DECLARE

CURSOR PROD_DTLS_C IS

SELECT * FROM PROD_DETAILS T1 FOR UPDATE OF P_ID;

V_PID PROD_DETAILS.P_ID%TYPE;

V_PRDNAME PROD_DETAILS.P_NAME%TYPE;

BEGIN

OPEN PROD_DTLS_C;

LOOP

FETCH PROD_DTLS_C INTO V_PID, V_PRDNAME;


IF PROD_DTLS_C%NOTFOUND THEN

EXIT;

ELSE

UPDATE PROD_DETAILS P

SET P.P_ID = LPAD(P_ID, 10, 0)

WHERE CURRENT OF PROD_DTLS_C;

END IF;

END LOOP;

CLOSE PROD_DTLS_C;

COMMIT;

END;

select * from PROD_DETAILS;

TRUNCATE TABLE prod_details;

BEGIN

--Inserting data into prod_details table

FOR i IN 1..50 LOOP

INSERT INTO prod_details VALUES(i,'pname'||i);


END LOOP;

commit;

END;

DECLARE

CURSOR PROD_DTLS_C IS

SELECT * FROM PROD_DETAILS T1 FOR UPDATE OF P_ID;

V_PID PROD_DETAILS.P_ID%TYPE;

V_PRDNAME PROD_DETAILS.P_NAME%TYPE;

BEGIN

OPEN PROD_DTLS_C;

LOOP

FETCH PROD_DTLS_C INTO V_PID, V_PRDNAME;

IF PROD_DTLS_C%NOTFOUND THEN

EXIT;

ELSE

UPDATE PROD_DETAILS P
SET P.P_ID = LPAD(P_ID, 10, 0)

WHERE CURRENT OF PROD_DTLS_C;

END IF;

COMMIT;

END LOOP;

CLOSE PROD_DTLS_C;

--COMMIT;

END;

select * from PROD_DETAILS;

Posted 29th September 2014 by Unknown

0 Add a comment

MAY

28

Escape Sequence in Oracle

Escape special characters when writing SQL queries

--to include single '


SELECT 'Steven's salary is more than 50k INR' AS "SAL_DETAILS"

FROM Dual;

ORA-01756 : quoted string not properly terminated

SELECT 'Steven''s salary is more than 50k INR' AS "SAL_DETAILS"

FROM Dual;

SAL_DETAILS

---------------------------------------

Steven's salary is more than 50k INR

--to include double '

SELECT 'You can print double quot ('''') in oracle' "Info"

FROM Dual;

Info

---------------------------------------

You can print double quot ('') in oracle


SELECT q'[some test ' some test ' some text ']' AS "In 10g"

FROM dual;

In 10g

------------------------------------

some test ' some test ' some text '

--Escape wild card characters ( _ and % )

The LIKE keyword allows for string searches.

The '_' wild card character is used to match exactly one character

While '%' is used to match zero or more occurrences of any characters.

These characters can be escaped in SQL as follows.

WITH mail_ids AS

SELECT 'an.murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an_murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an%murugappan@gmail.com' mail FROM Dual


)

SELECT * FROM mail_ids

WHERE mail LIKE '__$_%' ESCAPE '$';

mail

----------------------------------

an_murugappan@gmail.com

WITH mail_ids AS

SELECT 'an.murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an_murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an%murugappan@gmail.com' mail FROM Dual

SELECT * FROM mail_ids

WHERE mail LIKE '__/%%' ESCAPE '/';

mail

----------------------------------

an%murugappan@gmail.com
Escape ampersand (&) characters in SQL*Plus

SQL> select '&a' FROM dual;

'23'

----

23

SQL> SET ESCAPE '\'

SQL> select '\&a' FROM dual;

'&A'

----

&a

SQL> SET SCAN OFF;

SQL> select '&a' FROM dual;

'&A'

----

&a

SQL> SET SCAN ON;


SQL> select '&a' FROM dual;

'45'

----

45

Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Data Manipulation Language

Data Manipulation Language (DML) statements are used for managing data within schema
objects. Some examples:

INSERT - insert data into a table

UPDATE - updates existing data within a table

DELETE - deletes all records from a table, the space for the records remain

MERGE - UPSERT operation (insert or update)


CREATE TABLE prod_details

prod_id NUMBER(4) ,

prod_name VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

Deliver_dt DATE DEFAULT SYSDATE+3 ,

comments VARCHAR2(300)

);

SELECT * FROM prod_details;

no_data_found

INSERT

INSERT INTO prod_details(prod_id,prod_name,order_dt,deliver_dt,comments)

VALUES(100,'Apple iphone 5s','21-May-14','24-May-14','Color : Black');

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black


---------------------------------------------------------------------------

--Inserting records with out mentioning column name

INSERT INTO prod_details

VALUES(101,'Samsung Galaxy III','20-Aug-14','23-Aug-14','Color : White');

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

---------------------------------------------------------------------------

--Inserting selective number of values

INSERT INTO prod_details

VALUES(103,'Moto X','11-May-14','13-May-14');

ORA-00947 : not enough values

--While inserting selective number of values mentioning column name is compulsory.


INSERT INTO prod_details (prod_id,prod_name,order_dt,deliver_dt)

VALUES(103,'Moto X','11-May-14','13-May-14');

SELECT * FROM prod_details;

--------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

--------------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

--------------------------------------------------------------------------------

--Inserting NULL value.

--If you want to insert NULL value you can ignore that column at the time of inserting

--or we can use NULL keyword to insert NULL.

INSERT INTO prod_details

VALUES(104,'Moto G','19-May-14','22-May-14',NULL);

SELECT * FROM prod_details;

---------------------------------------------------------------------------
PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Noto G 5/19/2014 5/22/2014

---------------------------------------------------------------------------

--if you are not providing values for order_dt and deliver_dt column default value can be taken.

INSERT INTO prod_details(prod_id,prod_name,comments)

VALUES(105,'Nokia Lumis 720p','Color : Red');

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

----------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Moto G 5/19/2014 5/22/2014

105 Nokia Lumis 720p 5/26/2014 5/29/2014 Color : Red

---------------------------------------------------------------------------
--Inserting data by using sub query

CREATE TABLE test_tab (id NUMBER, Name VARCHAR2(30));

INSERT INTO test_tab VALUES(1,'Name1');

INSERT INTO test_tab VALUES(2,'Name2');

INSERT INTO test_tab VALUES(3,'Name3');

SELECT COUNT(*) FROM test_tab;

COUNT(*)

-------

--creating table by using sub query (with out data)

CREATE TABLE ins_chk

SELECT * FROM test_tab

WHERE id = 900;
SELECT COUNT(*) FROM ins_chk;

COUNT(*)

-------

--Inserting data by using sub query

--copying data from test_tab to ins_chk

INSERT INTO ins_chk (SELECT * FROM test_tab);

3 rows inserted in 0.047 seconds.

SELECT COUNT(*) FROM ins_chk;

COUNT(*)

-------

DROP TABLE test_tab;

DROP TABLE ins_chk;


UPDATE

Syntax :

UPDATE table_name

SET column1_name = column1_value,

column2_name = column2_value,

column2_name = column3_value,

columnn_name = columnn_value

WHERE condition(s);

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

----------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Moto G 5/19/2014 5/22/2014

105 Nokia Lumis 720p 5/26/2014 5/29/2014 Color : Red

---------------------------------------------------------------------------
UPDATE prod_details ps

SET ps.prod_name = 'iphone 5s'

WHERE ps.prod_id = 100;

1 row updated in 0.031 seconds

SELECT *

FROM prod_details ps

WHERE ps.prod_id = 100;

--------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

--------------------------------------------------------------------

100 iphone 5s 5/21/2014 5/24/2014 Color : Black

--------------------------------------------------------------------

--update statement with out condition

--If you try to execute update statement without condition it'll update all the records inside the
table.

UPDATE prod_details ps

SET ps.comments = 'None';

5 row updated in 0.031 seconds


SELECT *

FROM prod_details ps;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 None

101 Samsung Galaxy III 8/20/2014 8/23/2014 None

103 Moto X 5/11/2014 5/24/2014 None

104 Moto G 5/19/2014 5/22/2014 None

105 Nokia Lumis 720p 5/26/2014 5/29/2014 None

----------------------------------------------------------------------

--if your update text contain ' means you can use following metnod (use '')

UPDATE prod_details ps

SET ps.comments = 'Some product''s are not available'

WHERE ps.prod_id = 100;

1 row updated in 0.031 seconds

SELECT *

FROM prod_details ps
WHERE ps.prod_id = 100;

------------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

------------------------------------------------------------------------------------

100 iphone 5s 5/21/2014 5/24/2014 Some product's are not available

------------------------------------------------------------------------------------

DELETE

Syntax:

DELETE FROM table_name

WHERE condition(s);

DELETE FROM prod_details

WHERE prod_id IN (104, 105);

2 row(S) deleted in 0.032 seconds

SELECT *

FROM prod_details ps;


---------------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Some product's are not available

101 Samsung Galaxy III 8/20/2014 8/23/2014 None

103 Moto X 5/11/2014 5/24/2014 None

---------------------------------------------------------------------------------------

DELETE FROM prod_details;

3 row(s) deleted in 0.062 seconds.

SELECT * FROM prod_details;

no rows selected.

DROP TABLE prod_details;

MERGE = Insert + Update

-- will update soon.

Posted 28th May 2014 by Unknown


0 Add a comment

MAY

28

Data Define Language

Data Definition Language (DDL) statements are used to define the database structure or schema.

Some examples:

CREATE - to create objects in the database.

ALTER - alters the structure of the database.

ADD

RENAME

MODIFY

DROP

DROP - delete objects from the database

TRUNCATE - remove all records from a table,

including all spaces allocated for the records are removed.

COMMENT - add comments to the data dictionary.

RENAME - rename an object.


Creating Table

--------------------------------------------------------------------------

Data Types Size Default Size Explanation

--------------------------------------------------------------------------

NUMBER(P,S) P: 1 to 38 we can store number between 0-9

S: -84 to 127

VARCHAR2 4000 Bytes we can store 0-9, a-z, A-Z and special characters

CHAR 2000 Bytes 1

DATE 7 Used to store Date

TIMESTAMP Includes year, month, day, hour, minute, and seconds.

LONG 2 GB Only one long column is allowed in a table.

We can't use this column in ORDER BY clause.

CLOB 4 GB Character Large Object

BLOB Binary Larger Object

--------------------------------------------------------------------------

CREATE

ALTER : ADD RENAME MODIFY DROP RENAME

RENAME

DROP

TRUNCATE

--creating table
CREATE TABLE friends_details_tb

Name VARCHAR2(30) ,

Phone NUMBER(10) ,

Gender CHAR ,

dob DATE ,

other_details LONG ,

make_dtm TIMESTAMP

);

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

-----------------------------

--maximum you can keep 255 columns in a table


ALTER : Colum level operations

ADD RENAME MODIFY DROP

ADD : Used to add a column after the table hase been created

ALTER TABLE friends_details_tb

ADD email VARCHAR2(30);

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

EMAIL VARCHAR2(30)

-----------------------------
--adding multiple columns by using single ALTER statement

SYNTAX

ALTER TABLE friends_details_tb

ADD (

column_1 Data_type(size),

column_2 Data_type(size),

column_3 Data_type(size),

column_4 Data_type(size)

);

RENAME : Used to Rename a column

ALTER TABLE friends_details_tb

RENAME COLUMN email TO email_id;

DESC friends_details_tb;

-----------------------------

NAME TYPE
-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

MODIFY : Used to change the data type or size of the data type.

ALTER TABLE friends_details_tb

MODIFY other_details CLOB;

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)
DOB DATE

OTHER_DETAILS CLOB

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

--Modifying multiple columns at a time

ALTER TABLE friends_details_tb

MODIFY ( column_name_1 old_datatype(new_size),

column_name_2 new_datatype(old_size),

column_name_3 new_datatype(new_size)

);

DROP : Used to drop the column after the table has been created.

ALTER TABLE friends_details_tb

DROP COLUMN other_details;

DESC friends_details_tb;

-----------------------------

NAME TYPE
-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

RENAME : Used to Rename a particular table.

SYNTAX

RENAME old_table_name TO new_table_name;

RENAME friends_details_tb TO fnd_det;

DESCRIBE fnd_det;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)
GENDER CHAR(1)

DOB DATE

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

TRUNCATE : Used to remove the entire content of the table (not a structure)

SYNTAX

TRUNCATE TABLE table_name;

TRUNCATE TABLE fnd_det;

DROP : Used to drop the tabel (Data + stucture of the table get removed from the database )

DROP TABLE fnd_det;

*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

Posted 28th May 2014 by Unknown


0 Add a comment

MAY

28

Statements in Oracle

Data Definition Language (DDL)

DDL statements are used to define the database structure or schema. Some examples:

CREATE - to create objects in the database

ALTER - alters the structure of the database

ADD

RENAME

MODIFY

DROP

DROP - delete objects from the database

TRUNCATE - remove all records from a table,

including all spaces allocated for the records are removed

RENAME - rename an object

Data Manipulation Language (DML)

DML statements are used for managing data within schema objects. Some examples:
INSERT - insert data into a table

UPDATE - updates existing data within a table

DELETE - deletes all records from a table, the space for the records remain

MERGE - UPSERT operation (insert or update)

Data Control Language (DCL)

DCL statements. Some examples:

GRANT - gives users access privileges to database

REVOKE - withdraw access privileges given with the GRANT command

Transaction Control (TCL)

TCL statements are used to manage the changes made by DML statements. It allows
statements to be grouped together into logical transactions.

COMMIT - save work done

SAVEPOINT - identify a point in a transaction to which you can later roll back

ROLLBACK - restore database to original since the last COMMIT


Posted 28th May 2014 by Unknown

0 Add a comment

MAY

19

DECODE and CASE statement

CREATE TABLE students (

roll_no NUMBER(4) ,

Name VARCHAR2(30) ,

dept_cd VARCHAR2(20) ,

total_marks NUMBER(3)

);

BEGIN

INSERT INTO students VALUES (2000,'Rahul','CSE',480);

INSERT INTO students VALUES (2001,'Bala','IT', 390);

INSERT INTO students VALUES (2002,'Ramesh','CSE',250);

INSERT INTO students VALUES (2003,'Karthi','EEE',185);

INSERT INTO students VALUES (2004,'Ravi','IT',345);

END;

/
SELECT * FROM students;

DECODE

Decode is a function. Its a Oracle one.

Works like IF-THEN-ELSE.

You can use DECODE only in SELECT clause.

In DECODE you can include 255 things include Exep, search , result and default value.

Example

SELECT roll_no,

NAME,

dept_cd,

DECODE(dept_cd,

'CSE',

'Computer Science and Engineering',

'IT',

'Information Technology',

'Default Value') AS "DEPARTMENT NAME"

FROM students;

Sample Output

------------------------------------------------------------
ROLL_NO NAME DEPT_CD DEPARTMENT NAME

------------------------------------------------------------

2000 Rahul CSE Computer Science and Engineering

2001 Bala IT Information Technology

2002 Ramesh CSE Computer Science and Engineering

2003 Karthi EEE Default Value

2004 Ravi IT Information Technology

------------------------------------------------------------

CASE

CASE is an expression. Its a ANSI standard.

Compare to DECODE case will be more faster.

Example

SELECT roll_no,

NAME,

dept_cd,

total_marks,

CASE

WHEN total_marks > 500 THEN

'A Grade'

WHEN total_marks > 400 THEN

'B Grade'

WHEN total_marks > 300 THEN


'C Grade'

ELSE

'U Grade'

END AS "GRADE"

FROM students;

-----------------------------------------------

ROLL_NO NAME DEPT_CD TOTAL_MARKS GRADE

-----------------------------------------------

2000 Rahul CSE 480 B Grade

2001 Bala IT 390 C Grade

2002 Ramesh CSE 250 U Grade

2003 Karthi EEE 185 U Grade

2004 Ravi IT 345 C Grade

-----------------------------------------------

Interview Questions:

What is DECODE?

What is CASE?

Difference between CASE and DECODE? Which one is faster?

Posted 19th May 2014 by Unknown


0 Add a comment

MAY

19

Sub Query

Query with in another query

1. Single Row sub query

2. Multi row Sub query

select * from employees;

Want to fetch the person Who are all getting salary more than Neena's salary ?

Neena's Salary : 17000

Select First_name, salary

From Employees

Where salary > 17000;

--change in Neena's salary won't work for the above query.


Select salary From Employees

Where First_name = 'Neena';

Sub Query :

Select First_name, salary

From Employees

Where salary > (

Select salary From Employees

Where First_name = 'Neena'

);

Select * from employees;

Select salary From Employees

Where First_name = 'Alexander';

Sub Query Returns one value it is called as Single row sub query

Sub Query Returns more than one value it is called as Multi row sub query
Single row sub query operators :

> < >= <= = <>

Multiple Row Sub query operators :

IN ALL ANY

Who are all getting salary more than the average salary?

Select

First_name,

Salary

From

Employees

WHERE

Salary > (

SELECT Round(avg(salary),0)

FROM Employees

);

Multiple Row Sub query (In ANY ALL)


Select First_name,Department_id, salary

From Employees

Where salary in(

Select Salary From Employees

Where First_name = 'Alexander'

);

Any : Minimum Value will be taken (3100)

Select First_name,Department_id, salary

From Employees

Where salary > ANY(

Select Salary From Employees

Where First_name = 'Alexander'

);

All : Maximum Value will be taken (9000)

Select First_name,Department_id, salary

From Employees

Where salary > All(

Select Salary From Employees

Where First_name = 'Alexander'

);
We can use sub query in all the classes except Group by and order by class.

Select

From

Where

-----------Group by

having

-----------Order by

SELECT

( Select Count(*) from Employees Where Department_id = 90 )Executive,

( Select Count(*) from Employees Where Department_id = 60 ) IT,

( Select Count(*) from Employees Where Department_id = 10 ) Administration,

( Select Count(*) from Employees Where Department_id = 100) Finance

FROM

Dual;

Select Min(salary) From Employees;

Select Min(salary) from

Select * from Employees

Where Department_id = 60
);

What is INLINE VIEW?

If u use sub query in From it is call it is as INLINE VIEW.

Intermediate result set

Correlated sub query

SELECT employee_number, name

FROM employees Bob

WHERE salary > (

SELECT AVG(salary)

FROM employees

WHERE department = Bob.department

);

Posted 19th May 2014 by Unknown

0 Add a comment
Loading

Dynamic Views theme. Powered by Blogger.

Oracle sql & Pl/sql

search

Home Sql and pl/sql Sql Interview Questions

JUL

20

INLINE view in Oracle with 12c New Features

Named sub Query in FROM clause is call it as INLINE VIEW.

Oracle process a inline view faster than sub query

Inline View in Oracle

--Query to display all the employees who are all getting salary more than their department
average salary

SELECT First_name

, last_name

, salary

, department_id

FROM employees a , ( SELECT b.department_id

, AVG(b.salary) avg_sal

FROM employees b
GROUP BY b.department_id

)b

WHERE a.department_id = b.department_id

AND a.salary > b.avg_salary;

Display all the customer who have placed more number of orders by using INLINE view

CREATE TABLE customer_order_det_tb

( custm_id NUMBER ,

custm_nm VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

ttl_amt NUMBER(7,2)

);

BEGIN

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '11-Jul-15' , 45000.00);

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '14-Jul-15' , 27000.00);

INSERT INTO customer_order_det_tb VALUES(101, 'Raja' , '13-Jul-15' , 17000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 34000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 38000.00);

COMMIT;

END;
SELECT c.*

FROM customer_order_det_tb c;

--------------------------------------------

custm_id custm_nm order_dt ttl_amt

--------------------------------------------

100 Murugappan 7/11/2015 45000.00

100 Murugappan 7/14/2015 27000.00

101 Raja 7/13/2015 17000.00

102 Ramesh 7/15/2015 34000.00

102 Ramesh 7/15/2015 38000.00

--------------------------------------------

--Writing a Quer to display all the customer who have placed maximum number of order

--Query #1 for inline view

SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC;

--------------------------------

custm_id custm_nm total_odr

--------------------------------
100 Murugappan 2

102 Ramesh 2

101 Raja 1

--------------------------------

--Query #2 for inline view

SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm;

----------

total_odr

----------

----------

Inline view to find all the customers who have placed maximum number of orders

/****************************************

Syntax

SELECT * FROM <query1> x, <query2> y

WHERE contition;

****************************************/
SELECT query1.* FROM

( SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC

) query1,

( SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm

) query2

WHERE query1.total_odr = query2.total_odr;

-------------------------------

custm_id custm_nm total_odr

-------------------------------

100 Murugappan 2

102 Ramesh 2

-------------------------------

DROP TABLE customer_order_det_tb;

--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT
SELECT first_name, salary

FROM ( SELECT first_name, salary

FROM employees e

WHERE job_id NOT IN ('SALESMAN','PRESIDENT')

ORDER BY salary DESC

WHERE ROWNUM < 4;

New Oracle 12c Inline view Syntax

LATERAL clause for In-line views

Allows for columns in the inline view to be accessed!!

Example :

--in 11g

SELECT * FROM employees e, (

SELECT *

FROM departments d

WHERE e.department_id = d.department_id);

ORA-0090: "E"."DEPARTMENT_ID": Invalid Identifier


--in 12c

SELECT * FROM employees e, LATERAL(

SELECT *

FROM departments d

WHERE e.department_id = d.department_id

);

--in 11g

WITH t

AS

( SELECT LEVEL a

FROM dual

CONNECT BY LEVEL <= 30)

SELECT *

FROM t, (SELECT *

FROM employees

WHERE department_id = t.a

);

ORA-00904: "T"."A": invalid Identifier

--in 12c

WITH t
AS

(SELECT LEVEL a FROM dual CONNECT BY LEVEL <= 30)

SELECT * FROM t,

LATERAL(SELECT *

FROM employees

WHERE department_id = t.a);

Hope you have enjoyed this little article

Feed backs are always Welcome :) (:

Posted 20th July 2015 by Unknown

0 Add a comment

JAN

23

Salary Related Questions in Oracle

--creating table

CREATE TABLE employee_data

(
eid NUMBER(4),

ename VARCHAR2(30),

depno NUMBER(3),

salary NUMBER(8)

);

BEGIN

--Inserting records

INSERT INTO employee_data VALUES(1000,'Name01',90,30000);

INSERT INTO employee_data VALUES(1001,'Name02',90,6000);

INSERT INTO employee_data VALUES(1002,'Name03',90,23000);

INSERT INTO employee_data VALUES(1003,'Name04',60,35000);

INSERT INTO employee_data VALUES(1004,'Name05',60,60000);

INSERT INTO employee_data VALUES(1005,'Name06',60,30000);

INSERT INTO employee_data VALUES(1006,'Name07',80,36000);

INSERT INTO employee_data VALUES(1007,'Name08',80,29000);

INSERT INTO employee_data VALUES(1008,'Name09',80,37000);

INSERT INTO employee_data VALUES(1009,'Name10',80,41000);

COMMIT;

END;

/
SELECT * FROM employee_data

ORDER BY salary DESC;

--query to find maximum salary from employee_data table

SELECT MAX(salary) FROM employee_data;

--query to find minimum salary from employee_data table

SELECT MIN(salary) FROM employee_data;

--query to find second maximum salary from employee_data table

SELECT MAX(salary)

FROM employee_data

WHERE salary NOT IN (SELECT MAX(salary)

FROM employee_data);

--query to select 5th maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)


WHERE rownum <= 5);

--query to select nth maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= &n);

--query to select all the details of the employee whose getting nth maximum salary

SELECT *

FROM (SELECT emp.*,

rownum rn

FROM (SELECT *

FROM employee_data

ORDER BY salary DESC) emp)

WHERE rn = 9;

--same query using row_numbr( ) function


SELECT *

FROM (SELECT emp.*,

row_number() over(ORDER BY salary) rank

FROM employee_data emp)

WHERE rank = 9;

--same query using rank( ) function

SELECT *

FROM (SELECT emp.*,

rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--same query using dense_rank( ) function

SELECT *

FROM (SELECT emp.*,

dense_rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--query to display display maximum salary in all the department


SELECT e.depno "Department id",

MAX(salary) "Maximum Salary"

FROM employee_data e

GROUP BY e.depno;

--query to display all the employees who are all getting salary more than average salary of the
company

SELECT e.* FROM employee_data e

WHERE salary > (SELECT AVG(salary) FROM employee_data);

--query to display all the employees who are all getting salary more than their department
average salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE department_id = OUT.department_id);

--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE employee_id = OUT.manager_id);

Documented By : Murugappan Annamalai

Posted on : 23-Jan-15 16:34:00 IST.

Hope you have enjoyed this little article

Feed backs are always welcome :)

Posted 23rd January 2015 by Unknown

7 View comments

JAN

22

Why prefer COALESCE over NVL


Documented By : Nimish Garg

I prefer using "COALESCE" over "NVL" is some of the scenarios. Last week One of my friend
asked me what is the advantage of using "COALESCE" where we can simply use "NVL". I simply
gave him the reply from Oracle Docs i.e. NVL lets you replace null (returned as a blank) with a
string in the results of a query and COALESCE returns the first non-null expr in the expression list.
Oracle Database uses short-circuit evaluation with "COALESCE".

He replied that he knows the difference, he knows that "COALESCE" can take multiple arguments
and so on. He was more interested in understanding "short-circuit evaluation" of "COALESCE"
and the scenarios where I prefer using "COALESCE" over "NVL".

To make him understand I created following function which takes One second in every execution
and simply returns '--null--' and executed 2 very similar queries one with NVL and other with
COALESCE.

SQL> create or replace function f_null return varchar2

2 is

3 begin

4 dbms_lock.sleep(1);

5 return '--null--';

6 end;

7 /

Function created.

Following are the queries which I used to demonstrate that NVL evaluates both arguments even
if the second argument is not used and COALESCE uses short-circuit evaluation i.e. it only
evaluates the arguments only if they are needed.

SQL> select e.empno, e.ename ename, nvl(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.
Elapsed: 00:00:14.01

SQL> select e.empno, e.ename ename, coalesce(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.
Elapsed: 00:00:01.01

Here we can see easily that the first query with NVL took 14+ seconds, one second for each
record even if the "f_null" value was used only in one record. On the contrary as mentioned in
Oracle Documentation "COALESCE" uses its "short-circuit evaluation" and "f_null" was called
only once and so second query took only One Second. "COALESCE" is certainly use less resources
than NVL.

Posted 22nd January 2015 by Unknown

0 Add a comment

DEC

21

Constraints

It Enforce Rule On Table

We can create constraint at the time of Creating Table

1. Column Level Declaration

2. Table Level Declaration


1. We can provide own name.

Format : [part_of_project_name-table_name-column_name-constraint_type]

Example : gmind_emp_id_pk _uk _ck _f

2. system name name

Format : sys_cn

Example : SYS_C405323

We can create constraint after the table has been created

Types

Primary Key

Not allowed Null value

Not allowed you to enter duplicate value

Ex : Employee_id, Student_id

Unique Key
allowed Null value

Not allowed you to enter duplicate value

Ex : Contact_no, email

Foreign Key

It will allowed you to enter NULL and Duplicate value.

c1(pk) : 1 2 3

c2(f) : 1 1 2 3 4 Not allowed

Allowed you to enter duplicate value and null value

Not Null

It will not allowed you to enter null value

Check

You can check your own condition

Simple Table for understanding


------------------------------------

Duplicate NULL

------------------------------------

Primary Key X X

Unique Key X Allowed

Foreign Key Allowed Allowed

------------------------------------

creating table with all constraint type

Create table my_stu_details

S_id Number(2),

S_name Varchar2(30) Not Null, --SYS_Cn

s_mail Varchar2(30),

s_gender char(1),

s_did Number(3),

Constraint my_stu_sid_pk PRIMARY KEY (s_id),

constraint my_stu_mail_uk UNIQUE (s_mail) ,

Constraint my_stu_gen_ck CHECK (s_gender IN ('M', 'F', 'm', 'f')),

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

);
DESC my_stu_details;

------------------------------------

Name Type Nullable

------------------------------------

S_ID NUMBER(2)

S_NAME VARCHAR2(30)

S_MAIL VARCHAR2(30) Y

S_GENDER CHAR(1) Y

S_DID NUMBER(3) Y

------------------------------------

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name1' , 'name1@gmail.com' , 'm' , 60 );

Select * from my_stu_details;

Validating Primary Key


Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-00001: unique constraint (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (NULL, 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-01400: cannot insert NULL into (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (2 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

Validating NOT NULL Constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , NULL , 'name3@gmail.com' , 'F' , 80 );


ORA-01400: cannot insert NULL into ("HR"."MY_STU_DETAILS"."S_NAME")

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , 'Name3' , 'name3@gmail.com' , 'F' , 80 );

Select * from my_stu_details;

Validating Unique Key Constraint

--Duplicate Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , 'name3@gmail.com' , 'F' , 80 );

ORA-00001: unique constraint (HR.MY_STU_MAIL_UK) violated

--Null Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , null , 'M' , 70 );


Select * from my_stu_details;

Validating Check constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'j' , 70 );

ORA-02290: check constraint (HR.MY_STU_GEN_CK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'M' , 70 );

Select * from my_stu_details;

Validating Foreign Key

Select * from Departments;


Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 3 );

ORA-02291: integrity constraint (HR.MY_STU_DID_FK) violated - parent key not found

Departments table : parent table

my_stu_details : Child table

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

--------------------------------------------------------

s_id s_name s_mail s_gender s_did

--------------------------------------------------------

1 name1 name1@gmail.com m 60

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 M 70
5 Name5 name5@gmail.com M 70

6 Name6 name6@gmail.com F 90

--------------------------------------------------------

Deleting the Primary key value which is referred by Foreign Key

Select * from Departments;

DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID

------------------------------------------------------------

60 IT 103 1400 <---- Delete

-- don't execute this query

--Delete From Departments

--Where Department_id = 60;

1) ON DELETE SET NULL

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID


-------------------------------------------------

6 Name6 name6@gmail.com F 90

1 name1 name1@gmail.com m -

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

2) ON DELETE SET CASCADE

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

Syntax

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE CASCADE
Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE SET NULL

Constraint Related Data Dictionary Table information.

To view constraint Information

SELECT c.owner,

c.constraint_name,

c.constraint_type,

c.table_name,

c.r_constraint_name,

c.status

FROM user_constraints c

WHERE c.table_name = 'MY_STU_DETAILS';

------------------------------------------------------------------------------------

owner constraint_name constraint_type table_name r_constraint_name status

------------------------------------------------------------------------------------

HR SYS_C004023 C MY_STU_DETAILS ENABLED

HR MY_STU_GEN_CK C MY_STU_DETAILS ENABLED


HR MY_STU_SID_PK P MY_STU_DETAILS ENABLED

HR MY_STU_MAIL_UK U MY_STU_DETAILS ENABLED

HR MY_STU_DID_FK R MY_STU_DETAILS DEPT_ID_PK ENABLED

------------------------------------------------------------------------------------

To view constraint name with corresponding column name

SELECT * FROM user_cons_columns c

WHERE c.table_name = 'MY_STU_DETAILS';

-------------------------------------------------------------

owner constraint_name table_name column_name position

-------------------------------------------------------------

HR MY_STU_MAIL_UK MY_STU_DETAILS S_MAIL 1

HR MY_STU_SID_PK MY_STU_DETAILS S_ID 1

HR MY_STU_GEN_CK MY_STU_DETAILS S_GENDER

HR SYS_C004023 MY_STU_DETAILS S_NAME

HR MY_STU_DID_FK MY_STU_DETAILS S_DID 1

-------------------------------------------------------------

Creating Composite Primary Key


Creating Primary Key with more than one number of column

ALTER TABLE table_name

ADD CONSTRAINT constraint_name PRIMARY KEY(column1, column_2 , column3);

In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.

creating constraint after the table creation

ALTER TABLE table_name

ADD CONSTRAINT constraint_name CONSTRAINT_TYPE(column_name);

ALTER TABLE table_name

DROP CONSTRAINT constraint_name;

ALTER TABLE table_name

DROP PRIMARY KEY;

To drop related foreign key


ALTER TABLE table_name

DROP PRIMARY KEY CASCADE;

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name;

Disable constraint with related foreign key constraint

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name CASCADE;

ALTER TABLE table_name

ENABLE CONSTRAINT constraint_name;

Interview Questions

What are all the type of constraint available in oracle?

Difference between PRIMARY KEY and UNIQUE key.

Difference between PRIMARY KEY ans FOREIGN KEY.

Difference between UNIQUE key and FOREIGN KEY.


Is it possible to create tow primary key in single table.

Write a syntax to create FOREIGN constraint.

How to create constraint after the table has been created?

How to enable and disable a constraint.

Which data dictionary table contains information about constraints?

Which Data Dictionary table contains information about constraint with corresponding column
name?

What is composite primary key?

Explain ON DELETE CASCADE and ON DELETE SET NULL option.

~Thanks For Reading~

Post your valuable feedback below

Posted 21st December 2014 by Unknown

1 View comments

UnknownMay 22, 2017 at 12:39 AM

good

Reply
DEC

listagg in Oracle 11g

Oracle 11gR2 listagg built-in function allows for many table columns to be displayed within a
single row, a non-first-normal form display

Syntax :

listagg(column_value,'delimiter') WITHIN GROUP(ORDER BY column_name)

--Example 1:

CREATE TABLE test_ins(empid NUMBER,product VARCHAR2(30));

BEGIN

INSERT INTO test_ins VALUES( 101,'pendrive');

INSERT INTO test_ins VALUES( 102,'toy');

INSERT INTO test_ins VALUES( 101,'ipod');

INSERT INTO test_ins VALUES( 102,'hat');

INSERT INTO test_ins VALUES( 103,'cpu');

INSERT INTO test_ins VALUES( 104,'pen');

INSERT INTO test_ins VALUES( 104,'car');

INSERT INTO test_ins VALUES( 104,'mat');

INSERT INTO test_ins VALUES( 105,'tv');


INSERT INTO test_ins VALUES( 106,'laptop');

commit;

END;

SELECT * FROM test_ins;

SELECT empid "Employee",

listagg(product,

',') within

GROUP (ORDER BY empid) "Products"

FROM test_ins

GROUP BY empid;

-->-- Result set --<--


DROP TABLE test_ins;

-->-- Example 2

select department_id "Department id", listagg(first_name,', ') WITHIN GROUP(ORDER BY


employee_id) "Employees"

FROM employees

WHERE department_id IN (10,20,30,60)

GROUP BY department_id;

-->-- Result set --<--

Posted 4th December 2014 by Unknown

0 Add a comment

NOV

Condition and Looping Statement


IF

IF ELSE

Multiple IF ELSE

LOOP

FOR LOOP

WHILE LOOP

create table test_udt(id NUMBER, salary NUMBER);

BEGIN

INSERT INTO test_udt VALUES(001,23000);

INSERT INTO test_udt VALUES(002,43000);

INSERT INTO test_udt VALUES(003,78000);

INSERT INTO test_udt VALUES(004,25000);

INSERT INTO test_udt VALUES(005,26000);

INSERT INTO test_udt VALUES(006,90000);

Commit;

END;

select * from test_udt;


IF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 1;

IF v_salary > 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

END IF;

commit;

END;

IF ELSE
DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

ELSE

UPDATE test_udt t

SET t.salary = v_salary+20007

WHERE t.id = v_id ;

END IF;

commit;

END;

--same example with less number of lines


DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

v_salary := v_salary+10005;

ELSE

v_salary := v_salary+20007;

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;


Multiple IF ELSIF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 3;

IF v_id = 1 THEN

v_salary := 1000;

dbms_output.put_line('1 inside');

ELSIF v_id = 2 THEN

v_salary := 2000;

dbms_output.put_line('2 inside');

ELSIF v_id = 3 THEN

v_salary := 3000;

dbms_output.put_line('3 inside');

ELSIF v_id = 4 THEN

v_salary := 4000;

dbms_output.put_line('4 inside');

END IF;
UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

LOOP

--syntax

LOOP

--statements

--increment

--exit statement

END LOOP;

CREATE TABLE prod_details (pid VARCHAR2(3), pname VARCHAR2(30));

DECLARE

i NUMBER := 1;
x VARCHAR2(3);

BEGIN

LOOP

x := lpad(i,3,'0');

dbms_output.put_line('x value : '|| x);

INSERT INTO prod_details VALUES(i, 'Product '||i);

EXIT WHEN i >900;

i := i+1;

IF MOD(i,100) = 0 THEN

commit;

dbms_output.put_line('commit executed');

END IF;

END LOOP;

END;

SELECT * FROM prod_details ORDER BY 1;

DROP TABLE prod_details;

FOR LOOP

BEGIN

FOR I in 1..5
LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

FOR LOOP - Reverse

BEGIN

FOR I in REVERSE 14..50

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

WHILE LOOP

DECLARE

i_val NUMBER:=0;

BEGIN

WHILE (i_val < 11)

LOOP

dbms_output.put_line('The value of I is '||i_val);

i_val := i_val + 1;
END LOOP;

END;

sample output:

The value of I is 0

The value of I is 1

The value of I is 2

The value of I is 3

The value of I is 4

The value of I is 5

The value of I is 6

The value of I is 7

The value of I is 8

The value of I is 9

The value of I is 10

Posted 8th November 2014 by Unknown

0 Add a comment

OCT
21

Bulk Collect

This is used for array fetches

With this you can retrieve multiple rows of data with a single round trip.

This reduces the number of context switches between the pl/sql and sql engines.

You can use bulk collect in both dynamic and static sql.

You can use bulk collect in select, fetch into and returning into clauses.

SQL engine automatically initializes and extends the collections you reference in the bulk
collect clause.

You can fetch into multiple collections with one column each.

You can use the limit clause of bulk collect to restrict the no of rows retrieved.

SELECT * FROM product_details;

-->-- Bulk collect in FETCH INTO --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN
OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Bulk collect in SELECT clause --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

BEGIN

SELECT * BULK COLLECT INTO dta FROM product_details;

FOR i IN dta.FIRST .. dta.LAST LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;
-->-- LIMIT in Bulk collect --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta LIMIT 30;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Multiple fetches in INTO clause --<--

SELECT * FROM product_details;


DECLARE

TYPE alldata_typ1 IS TABLE OF product_details.p_id%TYPE;

TYPE alldata_typ2 IS TABLE OF product_details.p_name%TYPE;

dta1 alldata_typ1;

dta2 alldata_typ2;

CURSOR proddt_cur IS

SELECT p_id, p_name FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta1, dta2;

CLOSE proddt_cur;

FOR i IN dta1.FIRST .. dta1.COUNT LOOP

dbms_output.put_line('Department Id : ' || dta1(i));

END LOOP;

FOR i IN dta2.FIRST .. dta2.COUNT LOOP

dbms_output.put_line('Department Name : ' || dta2(i));

END LOOP;

END;

/
DROP TABLE dep_details;

DROP TABLE product_details;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Ref Cursor

This is unconstrained cursor which will return different types depends upon the user input.

Ref cursors cannot be closed implicitly.

Ref cursor with return type is called strong cursor.

Ref cursor without return type is called weak cursor.

You can declare ref cursor type in package spec as well as body.

You can declare ref cursor types in local subprograms or anonymous blocks.

CREATE OR REPLACE PROCEDURE ref_c_sp(dep_det_c IN OUT SYS_REFCURSOR)

AS

BEGIN

OPEN dep_det_c
FOR

SELECT * FROM dep_details d;

END;

DECLARE

dep_det_c SYS_REFCURSOR;

tab_data dep_details%ROWTYPE;

BEGIN

ref_c_sp(dep_det_c);

LOOP

FETCH dep_det_c INTO tab_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department Name : '|| tab_data.d_name);

END LOOP;

CLOSE dep_det_c;

END;

/*sample output*/

Department Name : Admin

Department Name : HR
Department Name : Sales

Department Name : Marketing

DROP PROCEDURE ref_c_sp;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Cursor

SQL Private work Area where the query get passed and executed.

Types

******

Implicit(SQL)

Explicit

-->-- advanced cursor types --<--

Parametrized Cursor

Ref Cursor
Implicit

********

ORACLE implicitly opens a cursor to process each SQL statement not associated with an
explicitly declared cursor.

PL/SQL lets you refer to the most recent implicit cursor as the SQL” cursor. So, although you
cannot use the OPEN,

FETCH, and CLOSE statements to control an implicit cursor, you can still use cursor attributes to
access information

about the most recently executed SQL statement.

Cursor Stages

**************

OPEN cursor_name

FETCH (with in loop)

CLOSE cursor_name

Explicit

The set of rows returned by a query can consist of zero, one, or multiple rows,

depending on how many rows meet your search criteria. When a query returns multiple rows,

you can explicitly define a cursor to process the rows. You use three commands to control the
cursor
Cursor Attributes

*****************

%FOUND

%NOTFOUND

%ISOPEN

%ROWCOUNT

%BULK_ROWCOUNT --<-- used to handle error while using bulk collection.

%BULK_EXCEPTIONS --<-- used to handle error while using bulk collection.

Cursor Declaration

DECLARE

CURSOR <cursor_name>

IS

<SELECT statement>

BEGIN

--> some stmt

END;

Cursor Loop

Loop

While Loop

For Loop
Cursor Clauses

Return

For update

Where current of

Bulk collect

-->-- creating table

create table product_details

p_id NUMBER,

p_name VARCHAR2(30),

p_order_dt DATE

);

-->-- Inserting data

BEGIN

FOR i IN 1 .. 75 LOOP

INSERT INTO product_details VALUES (i, 'prod_name_' || i, SYSDATE + i);

END LOOP;

commit;

END;
-->-- selecting data

SELECT * FROM product_details;

---------------------------------------------

p_id p_name p_order_dt

---------------------------------------------

1 prod_name_1 10/11/2014 3:48:32 PM

2 prod_name_2 10/12/2014 3:48:32 PM

3 prod_name_3 10/13/2014 3:48:32 PM

4 prod_name_4 10/14/2014 3:48:32 PM

5 prod_name_5 10/15/2014 3:48:32 PM

6 prod_name_6 10/16/2014 3:48:32 PM

7 prod_name_7 10/17/2014 3:48:32 PM

8 prod_name_8 10/18/2014 3:48:32 PM

9 prod_name_9 10/19/2014 3:48:32 PM

10 prod_name_10 10/20/2014 3:48:32 PM

11 prod_name_11 10/21/2014 3:48:32 PM

12 prod_name_12 10/22/2014 3:48:32 PM

13 prod_name_13 10/23/2014 3:48:32 PM

14 prod_name_14 10/24/2014 3:48:32 PM

15 prod_name_15 10/25/2014 3:48:32 PM

16 prod_name_16 10/26/2014 3:48:32 PM


17 prod_name_17 10/27/2014 3:48:32 PM

18 prod_name_18 10/28/2014 3:48:32 PM

19 prod_name_19 10/29/2014 3:48:32 PM

20 prod_name_20 10/30/2014 3:48:32 PM

---------------------------------------------

----------------------------------------------

Implicit Cursor

----------------------------------------------

--will update soon

----------------------------------------------

Explicit Cursor

----------------------------------------------

**********************************************

Processing cursor data by using LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS
SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND; --<-- if next record not found means control will
come out from the loop

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )


DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

EXIT WHEN prod_detail_cur%FOUND; --<-- if next record found means control will come
out from the loop

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )


DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;
END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor Already closed

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP
FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

-->-- CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )


Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor closed

**********************************************

Processing cursor data by using WHILE LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

OPEN prod_detail_cur;

FETCH prod_detail_cur

INTO all_data;

WHILE prod_detail_cur%FOUND LOOP

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');


FETCH prod_detail_cur

INTO all_data;

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

************************************************************

Processing cursor data by using FOR LOOP - CURSOR FOR LOOP

************************************************************

DECLARE

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

FOR i IN prod_detail_cur
LOOP

dbms_output.put_line('Product id : ' || i.p_id ||

' Product Name : ' || i.p_name ||

' ( Orderd on : ' || TRIM(i.p_order_dt) || ' )');

END LOOP;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

Parameterized Cursor

*********************

This was used when you are going to use the cursor in more than one place with different
values for the same where clause.

Cursor parameters must be in mode.

Cursor parameters may have default values.

The scope of cursor parameter is within the select statement.


CREATE TABLE dep_details(d_id NUMBER,d_name VARCHAR2(30), location_id NUMBER);

BEGIN

INSRT INTO dep_details VALUES(001,'Admin',1010);

INSRT INTO dep_details VALUES(002,'HR',1010);

INSRT INTO dep_details VALUES(003,'Sales',1020);

INSRT INTO dep_details VALUES(004,'Marketing',1020);

commit;

END;

SELECT * FROM dep_details;

----------------------------

d_id d_name location_id

----------------------------

1 Admin 1010

2 HR 1010

3 Sales 1020

4 Marketing 1020

----------------------------
DECLARE

-->--Declaring parameterized cursor

CURSOR dep_det_c(p_location_id NUMBER) IS

SELECT * FROM dep_details d WHERE d.location_id = p_location_id;

all_data dep_details%ROWTYPE;

BEGIN

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

OPEN dep_det_c(1010);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

-->-- opening same cursor with different input value

OPEN dep_det_c(1020);

LOOP

FETCH dep_det_c

INTO all_data;
EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

END;

/*sample output*/

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 1 Department Name : Admin

Department id : 2 Department Name : HR

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 3 Department Name : Sales

Department id : 4 Department Name : Marketing

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Posted 21st October 2014 by Unknown

0 Add a comment
OCT

21

Handling Exception

Error Handling in oracle

ERROR

Any departure from the expected behavior of the system or program,

which stops the working of the system is an error.

Types : compile time error

Run time error

EXCEPTION

Any error or problem which one can handle and continue to work normally.

Handling Exception

When exception is raised, control passes to the exception section of the block.

i.e. EXCEPTION

WHEN name_of_exception THEN

Types : Pre Defined Exceptions

User Defined Exceptions


Predefined Exception

*********************

Oracle has predefined several exceptions that correspond to the most common oracle errors.

------------------------------------------------------------------------

Exception Oracle Error SQL Code Value

------------------------------------------------------------------------

ZERO_DIVIDE ORA-01476 -1476

NO_DATA_FOUND ORA-01403 +100

DUP_VAL_ON_INDEX ORA-00001 -1

TOO_MANY_ROWS ORA-01422 -1422

VALUE_ERROR ORA-06502 -6502

CURSOR_ALREADY_OPEN ORA-06511 -6511

OTHERS

------------------------------------------------------------------------

-->-- ZERO_DIVIDE --<--

Your program attempts to divide a number by zero.

DECLARE

v_result NUMBER;
BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN ZERO_DIVIDE THEN

dbms_output.put_line('Divisor is equal to zero');

END;

-->-- NO_DATA_FOUND --<--

Single row SELECT returned no rows or your program referenced a deleted element in a nested
table

or an uninitialized element in an associative array (index-by table).

CREATE TABLE test_tb(id NUMBER PRIMARY KEY);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN NO_DATA_FOUND THEN

dbms_output.put_line('There is no data inside the table');

END;
-->-- DUP_VAL_ON_INDEX --<--

A program attempted to insert duplicate values in a column that is constrained by a unique


index.

INSERT INTO test_tb VALUES (1);

INSERT INTO test_tb VALUES (2);

commit;

BEGIN

INSERT INTO test_tb VALUES (2);

EXCEPTION

WHEN DUP_VAL_ON_INDEX THEN

dbms_output.put_line('Duplicate values are not allowed');

END;

-->-- TOO_MANY_ROWS --<--

Single row SELECT returned multiple rows.

DECLARE

v_id NUMBER;
BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN TOO_MANY_ROWS THEN

dbms_output.put_line('Query returning more than one row');

END;

DROP TABLE test_tb;

-->-- VALUE_ERROR --<--

An arithmetic, conversion, truncation, or size constraint error occurred.

DECLARE

num1 NUMBER(2);

BEGIN

num1 := 345;

EXCEPTION

WHEN VALUE_ERROR THEN

dbms_output.put_line('check the size of the variable');

END;

-->-- CURSOR_ALREADY_OPEN --<--


A program attempted to open an already opened cursor.

CREATE TABLE emp(id NUMBER, name VARCHAR2(30));

BEGIN

INSERT INTO emp VALUES(1,'Name1');

INSERT INTO emp VALUES(2,'Name2');

INSERT INTO emp VALUES(3,'Name3');

INSERT INTO emp VALUES(4,'Name4');

COMMIT;

END;

SELECT * FROM emp;

DECLARE

cursor emp_c IS

SELECT * FROM emp;

all_data emp%ROWTYPE;

BEGIN

OPEN emp_c;

OPEN emp_c;

NULL;
CLOSE emp_c;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

END;

DROP TABLE emp;

-->-- OTHERS --<--

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

WHEN OTHERS THEN

dbms_output.put_line('Some other error ' || SQLERRM);

END;

User Defined Exception

**********************
A user-defined exception is an error that is defined by the programmer.

User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,

exceptions have a type EXCEPTION and scope.

DECLARE

v_gender CHAR := '&gender';

gender_ex EXCEPTION;

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE gender_ex;

END IF;

dbms_output.put_line('Gender : '||v_gender);

EXCEPTION

WHEN gender_ex THEN

dbms_output.put_line('Please Enter valid gender');

END;

create table test_insert (id NUMBER, Name VARCHAR2(30));

DECLARE

abort_ex EXCEPTION;
BEGIN

FOR i IN 1..100

LOOP

BEGIN

IF mod(i,10)=0 THEN

RAISE abort_ex;

END IF;

INSERT INTO test_insert VALUES(i, 'Name'||i);

EXCEPTION

WHEN abort_ex THEN

NULL;

END;

END LOOP;

COMMIT;

END;

SELECT * FROM test_insert;

DROP TABLE test_insert;

SQLERRM and SQLCODE

********************

SQLCODE returns the current error code, and SQLERRM returns the current error message
text;
For user-defined exception SQLCODE returns 1 and SQLERRM returns “user-defined
exception”.

SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.

CREATE TABLE test_tb (id NUMBER);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

dbms_output.put_line(v_id);

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('SQLERRM : ' || SQLERRM);

dbms_output.put_line('SQLCODE : ' || SQLCODE);

END;

/*sample output*/

SQLERRM : ORA-01403: no data found

SQLCODE : 100

DROP TABLE test_tb;


PRAGMA EXCEPTION_INIT

*********************

Using this you can associate a named exception with a particular oracle error.

This gives you the ability to trap this error specifically, rather than via an OTHERS handler.

Syntax:

PRAGMA EXCEPTION_INIT(exception_name, oracle_error_number);

DECLARE

v_result NUMBER;

PRAGMA EXCEPTION_INIT(Invalid, -1476);

BEGIN

SELECT 453 / 0 INTO v_result FROM dual;

dbms_output.put_line('Result : ' || v_result);

EXCEPTION

WHEN INVALID THEN

dbms_output.put_line('Invalid Exception');

END;

RAISE_APPLICATION_ERROR
************************

You can use this built-in function to create your own error messages, which can be more
descriptive than named exceptions.

Error Number :

Oracle Error Range : From -00000 to -19999

User Error Range : From -20000 to -20999

DECLARE

v_gender CHAR := '&gender';

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE_APPLICATION_ERROR(-20003, 'Enter valid gender');

END IF;

dbms_output.put_line('Gender : ' || v_gender);

END;

Posted 21st October 2014 by Unknown

1 View comments
RajmohanMarch 13, 2018 at 6:49 AM

How to get the two table data without using Joins and sub query,union?

Reply

OCT

Package

1. You can groups logical related subprogram (procedures and functions)

2. It consist of two parts

I) specification

II) Body

3. It allows the oracle server to read multiple object in to a memory once

4. You can declare global variable,cursor, user define exeption

5. Overloading

6. we can't create anonyms block inside the package

create table err_log(sno NUMBER, u_name VARCHAR2(30), error_msg CLOB, hap_tm


TIMESTAMP);

select * from err_log;


--stand alone procedure

CREATE OR REPLACE PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id


%TYPE) IS

v_salary employees.salary%TYPE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT salary,

first_name

INTO v_salary,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line('Salary of ' || v_first_name || ' is ' || v_salary);

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);
commit;

END emp_sal_sp;

BEGIN

-- Call the procedure

emp_sal_sp(p_employee_id => :p_employee_id);

END;

CREATE OR REPLACE PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id


%TYPE) IS

v_hire_date DATE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT hire_date,

first_name

INTO v_hire_date,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line(v_first_name || ' hired on ' || to_char(v_hire_date,'month ddth,


yyyy'));

EXCEPTION

WHEN OTHERS THEN


v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_hdt_sp;

BEGIN

-- Call the procedure

emp_hdt_sp(p_employee_id => :p_employee_id);

END;

create or replace function sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER

IS

v_c NUMBER;

BEGIN

v_c := p_a + p_b;

RETURN v_c;
END;

--Specification Part

CREATE OR REPLACE PACKAGE emp_pkg

IS

PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id%TYPE);

PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id%TYPE);

FUNCTION sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER;

END emp_pkg ;

--Body Part

CREATE OR REPLACE PACKAGE BODY emp_pkg

IS

PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id%TYPE) IS

v_salary employees.salary%TYPE;
v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT salary,

first_name

INTO v_salary,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line('Salary of ' || v_first_name || ' is ' || v_salary);

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_sal_sp;

PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id%TYPE) IS

v_hire_date DATE;
v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT hire_date,

first_name

INTO v_hire_date,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line(v_first_name || ' hired on ' || to_char(v_hire_date,'month ddth,


yyyy'));

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_hdt_sp;

FUNCTION sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER

IS
v_c NUMBER;

BEGIN

v_c := p_a + p_b;

RETURN v_c;

END;

END emp_pkg;

A package specification can exist without a package body, but

a package body can't exist without a package specification.

--Executing procedure inside the package

BEGIN

emp_pkg.emp_sal_sp(120);

END;

--Executing function inside the package

SELECT emp_pkg.sum_fn(23,567) FROM dual;

-- You can declare global variable,cursor, user define exeption


create or replace package all_detail

as

PROCEDURE emp2sal (a IN NUMBER);

PROCEDURE emp2exep (a IN NUMBER);

FUNCTION add2num (a IN NUMBER, b IN NUMBER)

RETURN NUMBER;

c NUMBER(8); --global declaration

abort_ex EXCEPTION; --global exception declaration

CURSOR emp_rec --global cursor declaration

IS

SELECT first_name, salary, hire_date, department_id

FROM employees;

End all_detail;

create or replace package body all_detail

as

PROCEDURE emp2sal (a IN NUMBER)


AS

BEGIN

SELECT salary

INTO c

FROM Employees

WHERE Employee_id = a;

Dbms_output.put_line('Salary of Employee ' || a || ' is ' || c);

EXCEPTION

WHEN no_data_found THEN

Dbms_output.put_line('Please enter valid id');

END emp2sal;

PROCEDURE emp2exep (a IN NUMBER)

AS

BEGIN

SELECT Round(Months_between(sysdate,hire_date)/12)

INTO c

FROM Employees

WHERE Employee_id = a;

Dbms_output.put_line( c || ' Years');

EXCEPTION
WHEN no_data_found THEN

Dbms_output.put_line('Please enter valid id');

END emp2exep;

FUNCTION add2num (a IN NUMBER, b IN NUMBER)

RETURN NUMBER

AS

BEGIN

c := a+b;

RETURN C;

END;

End all_detail;

/*Declaring a Bodiless Package */

CREATE OR REPLACE PACKAGE global_constant

IS

mile_2_kilo CONSTANT NUMBER := 1.6093;

kilo_2_mile CONSTANT NUMBER := 0.6214;

yard_2_meter CONSTANT NUMBER := 0.9144;


meter_2_yard CONSTANT NUMBER := 1.0936;

END global_constant;

BEGIN

DBMS_OUTPUT.PUT_LINE('20 miles = ' || 20*global_constant.mile_2_kilo||' km');

END;

/*Forward Declaration in package */

DECLARE

PROCEDURE P2; -- forward declaration

PROCEDURE P3;

PROCEDURE P1 IS

BEGIN

dbms_output.put_line('From procedure p1');

p2;

END P1;

PROCEDURE P2 IS

BEGIN

dbms_output.put_line('From procedure p2');

p3;
END P2;

PROCEDURE P3 IS

BEGIN

dbms_output.put_line('From procedure p3');

END P3;

BEGIN

p1;

END;

sample output:

From procedure p1

From procedure p2

From procedure p3

Drop package package_name;

Drop package body package_name;

SELECT text FROM user_source u

WHERE u.name = 'EMP_PKG';


Interview Questions:

What is package?

Advantage of package

Is it possible to create package body with out package specification?

what is package overloading?

what is forward declaration in package?

which data dictionary table contain source code of package?

How to declare global variable, exception and cursor?

How to execute procedure and function inside the package?

Posted 4th October 2014 by Unknown

0 Add a comment

OCT

%TYPE and %ROWTYPE

--%type is used to fetch the data type of the particular column


create table product_details

p_id NUMBER(3),

p_nm VARCHAR2(30),

p_qty NUMBER(8),

order_dt DATE

);

BEGIN

INSERT INTO product_details VALUES(100,'Name0',400,'23-Mar-13');

INSERT INTO product_details VALUES(101,'Name1',600,'26-Apr-13');

INSERT INTO product_details VALUES(102,'Name2',800,'27-Jan-12');

INSERT INTO product_details VALUES(103,'Name3',300,'23-Jul-11');

INSERT INTO product_details VALUES(104,'Name4',200,'22-Aug-11');

INSERT INTO product_details VALUES(105,'Name5',500,'25-Oct-12');

commit;

END;

SELECT * FROM product_details;

------------------------------------

P_ID P_NM P_QTY ORDER_DT


------------------------------------

100 Name0 400 03/23/2013

101 Name1 600 04/26/2013

102 Name2 800 01/27/2012

103 Name3 300 07/23/2011

104 Name4 200 08/22/2011

105 Name5 500 10/25/2012

------------------------------------

DECLARE

v_name VARCHAR2(4);

BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 100;

dbms_output.put_line('Product Name : ' || v_name);

--error numeric or value error

END;

DECLARE

v_name VARCHAR2(5);
BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 100;

dbms_output.put_line('Product Name : ' || v_name);

END;

ALTER TABLE product_details

MODIFY p_nm VARCHAR2(15);

INSERT INTO product_details

VALUES

(106,

'name6',

700,

'26-Dec-12');

commit;

106 name6 700 12/26/2012


DECLARE

v_name VARCHAR2(5);

BEGIN

SELECT p_nm INTO v_name

FROM product_details

WHERE p_id = 106;

dbms_output.put_line('Product Name : ' || v_name);

--error

END;

DECLARE

v_name product_details.p_nm%TYPE;

BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 106;

dbms_output.put_line('Product Name : ' || v_name);

END;
/

DROP TABLE product_details;

DECLARE

dep_id departments.department_id%TYPE;

dep_name departments.department_name%TYPE;

dep_man_id departments.manager_id%TYPE;

dep_loc_id departments.location_id%TYPE;

BEGIN

SELECT department_id,

department_name,

manager_id,

location_id

INTO dep_id,

dep_name,

dep_man_id,

dep_loc_id

FROM departments

WHERE department_id = 10;


dbms_output.put_line('Department_id : ' || dep_id);

dbms_output.put_line('Department_name : ' || dep_name);

dbms_output.put_line('Manager_id : ' || dep_man_id);

dbms_output.put_line('Location_id : ' || dep_loc_id);

END;

--%rowtype is used to fetch the data type of all the column

--Insted of using %type if we use %rowtype means we can reduce the no of variables that we
declare

DECLARE

dep_detail departments%ROWTYPE;

BEGIN

SELECT *

INTO dep_detail

FROM departments

WHERE department_id = 10;

dbms_output.put_line('Department_id : ' || dep_detail.department_id);


dbms_output.put_line('Department_name : ' || dep_detail.department_name);

dbms_output.put_line('Manager_id : ' || dep_detail.manager_id);

dbms_output.put_line('Location_id : ' || dep_detail.location_id);

END;

DROP TABLE dept_details;

CREATE TABLE dept_details

dept_id number(3) ,

dept_name varchar2(30),

dept_manager_name varchar2(30)

);

insert into dept_details values(10,'dept1','manager_name1');

insert into dept_details values(20,'dept2','manager_name2');

SELECT * FROM dept_details;

-------------------------------------------------------

| DEPT_ID | DEPT_NAME | DEPT_MANAGER_NAME |


+------------+-----------------------+-----------------

| 10 | dept1 | manager_name1 |

| 20 | dept2 | manager_name2 |

------------+-----------------------+------------------

DECLARE

all_data dept_details%ROWTYPE;

BEGIN

all_data.dept_id := 100;

all_data.dept_name := 'Admin';

all_data.dept_manager_name := 'John';

UPDATE dept_details

SET ROW = all_data

WHERE dept_id = 10;

dbms_output.put_line(SQL%ROWCOUNT || ' Row(s) get updated');

END;

1 Row(s) get updated


select * from dept_details;

---------------------------------------------------

| DEPT_ID | DEPT_NAME | DEPT_MANAGER_NAME|

---------------------------------------------------

| 100 | Admin | John |

| 20 | dept2 | manager_name2 |

---------------------------------------------------

Interview Question :

1. What is the use of %TYPE?

2. What is the use of %ROWTYPE?

3. Difference between %TYPE and %ROWTYPE?

Posted 2nd October 2014 by Unknown

0 Add a comment
SEP

29

BULK Exceptions

/************************************************************************

* Handling Exceptions in Bulk Operations *

* Documented on 29-SEP-14 04.35.35.980894 PM +05:30 *

* Document By : Murugappan Annamalai *

* Reference : http://www.dba-oracle.com/plsql/t_plsql_exceptions.htm *

************************************************************************/

CREATE TABLE bulk_tb (ran_num NUMBER NOT NULL);

--inserting data using bulk collect

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP
v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

commit;

END;

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

200

TRUNCATE TABLE bulk_tb;

sample2.sql --without exception part

DECLARE
TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

commit;

END;

/*

Error Message :

ORA-01400: cannot insert NULL into ("HR"."bulk_tb"."ran_num")

ORA-06512: at line 15

*/
sample2.sql --with exception part

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

BEGIN

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

COMMIT;

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('Error while inserting bulk record '||SQLERRM);


END;

END;

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

99

SQL%BULK_EXCEPTIONS(i).ERROR_INDEX

Holds the iteration (not the subscript) of the original FORALL statement that raised the
exception.

In sparsely populated collections,

the exception row must be found by looping through the original collection the correct
number of times.

SQL%BULK_EXCEPTIONS(i).ERROR_CODE

Holds the exceptions error code.


The total number of exceptions can be returned using the collections COUNT method,

which returns zero if no exceptions were raised. The save_exceptions.sql script,

a modified version of the handled_exception.sql script, demonstrates this functionality.

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

v_ex_count NUMBER(4);

abort_ex EXCEPTION;

PRAGMA EXCEPTION_INIT(abort_ex, -24381);

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

v_dat(150) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

EXECUTE IMMEDIATE 'TRUNCATE TABLE bulk_tb';


BEGIN

FORALL i IN v_dat.FIRST..v_dat.LAST SAVE EXCEPTIONS

INSERT INTO bulk_tb VALUES(v_dat(i));

COMMIT;

EXCEPTION

WHEN abort_ex THEN

v_ex_count := SQL%BULK_EXCEPTIONS.COUNT;

FOR i IN 1..v_ex_count LOOP

dbms_output.put_line('Error: ' || i ||' Array Index: ' || SQL


%BULK_EXCEPTIONS(i).error_index ||

' Message: ' || SQLERRM(SQL%BULK_EXCEPTIONS(i).ERROR_CODE));

END LOOP;

END;

END;

/*

Sample output:

Error: 1 Array Index: 100 Message: -1400: non-ORACLE exception

Error: 2 Array Index: 150 Message: -1400: non-ORACLE exception

*/
SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

198

SAVE EXCEPTIONS clause being removed, in the above script now traps a different error number.

The output from this script is listed below.

/*

Sample output:

Error: 1 Array Index: 100 Message: -1400: non-ORACLE exception

*/

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

99
SELECT COUNT(*) FROM bulk_tb;

DROP TABLE bulk_tb;

Posted 29th September 2014 by Unknown

0 Add a comment

SEP

29

Cursor - FOR UPDATE

/************************************************************************

* FOR UPDATE clause in oracle *

* Document By : Murugappan Annamalai *

************************************************************************/

create table prod_details(p_id VARCHAR2(30), P_name VARCHAR2(30));


BEGIN

--Inserting data into prod_details table

FOR i IN 1..50 LOOP

INSERT INTO prod_details VALUES(i,'pname'||i);

END LOOP;

commit;

END;

SELECT * FROM prod_details;

DECLARE

CURSOR PROD_DTLS_C IS

SELECT * FROM PROD_DETAILS T1 FOR UPDATE OF P_ID;

V_PID PROD_DETAILS.P_ID%TYPE;

V_PRDNAME PROD_DETAILS.P_NAME%TYPE;

BEGIN

OPEN PROD_DTLS_C;

LOOP
FETCH PROD_DTLS_C INTO V_PID, V_PRDNAME;

IF PROD_DTLS_C%NOTFOUND THEN

EXIT;

ELSE

UPDATE PROD_DETAILS P

SET P.P_ID = LPAD(P_ID, 10, 0)

WHERE CURRENT OF PROD_DTLS_C;

END IF;

END LOOP;

CLOSE PROD_DTLS_C;

COMMIT;

END;

select * from PROD_DETAILS;

TRUNCATE TABLE prod_details;

BEGIN

--Inserting data into prod_details table

FOR i IN 1..50 LOOP


INSERT INTO prod_details VALUES(i,'pname'||i);

END LOOP;

commit;

END;

DECLARE

CURSOR PROD_DTLS_C IS

SELECT * FROM PROD_DETAILS T1 FOR UPDATE OF P_ID;

V_PID PROD_DETAILS.P_ID%TYPE;

V_PRDNAME PROD_DETAILS.P_NAME%TYPE;

BEGIN

OPEN PROD_DTLS_C;

LOOP

FETCH PROD_DTLS_C INTO V_PID, V_PRDNAME;

IF PROD_DTLS_C%NOTFOUND THEN

EXIT;

ELSE
UPDATE PROD_DETAILS P

SET P.P_ID = LPAD(P_ID, 10, 0)

WHERE CURRENT OF PROD_DTLS_C;

END IF;

COMMIT;

END LOOP;

CLOSE PROD_DTLS_C;

--COMMIT;

END;

select * from PROD_DETAILS;

Posted 29th September 2014 by Unknown

0 Add a comment

MAY

28

Escape Sequence in Oracle

Escape special characters when writing SQL queries


--to include single '

SELECT 'Steven's salary is more than 50k INR' AS "SAL_DETAILS"

FROM Dual;

ORA-01756 : quoted string not properly terminated

SELECT 'Steven''s salary is more than 50k INR' AS "SAL_DETAILS"

FROM Dual;

SAL_DETAILS

---------------------------------------

Steven's salary is more than 50k INR

--to include double '

SELECT 'You can print double quot ('''') in oracle' "Info"

FROM Dual;

Info

---------------------------------------
You can print double quot ('') in oracle

SELECT q'[some test ' some test ' some text ']' AS "In 10g"

FROM dual;

In 10g

------------------------------------

some test ' some test ' some text '

--Escape wild card characters ( _ and % )

The LIKE keyword allows for string searches.

The '_' wild card character is used to match exactly one character

While '%' is used to match zero or more occurrences of any characters.

These characters can be escaped in SQL as follows.

WITH mail_ids AS

SELECT 'an.murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an_murugappan@gmail.com' mail FROM Dual

UNION
SELECT 'an%murugappan@gmail.com' mail FROM Dual

SELECT * FROM mail_ids

WHERE mail LIKE '__$_%' ESCAPE '$';

mail

----------------------------------

an_murugappan@gmail.com

WITH mail_ids AS

SELECT 'an.murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an_murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an%murugappan@gmail.com' mail FROM Dual

SELECT * FROM mail_ids

WHERE mail LIKE '__/%%' ESCAPE '/';

mail

----------------------------------

an%murugappan@gmail.com
Escape ampersand (&) characters in SQL*Plus

SQL> select '&a' FROM dual;

'23'

----

23

SQL> SET ESCAPE '\'

SQL> select '\&a' FROM dual;

'&A'

----

&a

SQL> SET SCAN OFF;

SQL> select '&a' FROM dual;

'&A'

----

&a
SQL> SET SCAN ON;

SQL> select '&a' FROM dual;

'45'

----

45

Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Data Manipulation Language

Data Manipulation Language (DML) statements are used for managing data within schema
objects. Some examples:

INSERT - insert data into a table

UPDATE - updates existing data within a table

DELETE - deletes all records from a table, the space for the records remain

MERGE - UPSERT operation (insert or update)


CREATE TABLE prod_details

prod_id NUMBER(4) ,

prod_name VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

Deliver_dt DATE DEFAULT SYSDATE+3 ,

comments VARCHAR2(300)

);

SELECT * FROM prod_details;

no_data_found

INSERT

INSERT INTO prod_details(prod_id,prod_name,order_dt,deliver_dt,comments)

VALUES(100,'Apple iphone 5s','21-May-14','24-May-14','Color : Black');

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------
100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

---------------------------------------------------------------------------

--Inserting records with out mentioning column name

INSERT INTO prod_details

VALUES(101,'Samsung Galaxy III','20-Aug-14','23-Aug-14','Color : White');

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

---------------------------------------------------------------------------

--Inserting selective number of values

INSERT INTO prod_details

VALUES(103,'Moto X','11-May-14','13-May-14');

ORA-00947 : not enough values

--While inserting selective number of values mentioning column name is compulsory.


INSERT INTO prod_details (prod_id,prod_name,order_dt,deliver_dt)

VALUES(103,'Moto X','11-May-14','13-May-14');

SELECT * FROM prod_details;

--------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

--------------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

--------------------------------------------------------------------------------

--Inserting NULL value.

--If you want to insert NULL value you can ignore that column at the time of inserting

--or we can use NULL keyword to insert NULL.

INSERT INTO prod_details

VALUES(104,'Moto G','19-May-14','22-May-14',NULL);

SELECT * FROM prod_details;


---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Noto G 5/19/2014 5/22/2014

---------------------------------------------------------------------------

--if you are not providing values for order_dt and deliver_dt column default value can be taken.

INSERT INTO prod_details(prod_id,prod_name,comments)

VALUES(105,'Nokia Lumis 720p','Color : Red');

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

----------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Moto G 5/19/2014 5/22/2014

105 Nokia Lumis 720p 5/26/2014 5/29/2014 Color : Red


---------------------------------------------------------------------------

--Inserting data by using sub query

CREATE TABLE test_tab (id NUMBER, Name VARCHAR2(30));

INSERT INTO test_tab VALUES(1,'Name1');

INSERT INTO test_tab VALUES(2,'Name2');

INSERT INTO test_tab VALUES(3,'Name3');

SELECT COUNT(*) FROM test_tab;

COUNT(*)

-------

--creating table by using sub query (with out data)

CREATE TABLE ins_chk

SELECT * FROM test_tab

WHERE id = 900;
SELECT COUNT(*) FROM ins_chk;

COUNT(*)

-------

--Inserting data by using sub query

--copying data from test_tab to ins_chk

INSERT INTO ins_chk (SELECT * FROM test_tab);

3 rows inserted in 0.047 seconds.

SELECT COUNT(*) FROM ins_chk;

COUNT(*)

-------

DROP TABLE test_tab;


DROP TABLE ins_chk;

UPDATE

Syntax :

UPDATE table_name

SET column1_name = column1_value,

column2_name = column2_value,

column2_name = column3_value,

columnn_name = columnn_value

WHERE condition(s);

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

----------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Moto G 5/19/2014 5/22/2014

105 Nokia Lumis 720p 5/26/2014 5/29/2014 Color : Red


---------------------------------------------------------------------------

UPDATE prod_details ps

SET ps.prod_name = 'iphone 5s'

WHERE ps.prod_id = 100;

1 row updated in 0.031 seconds

SELECT *

FROM prod_details ps

WHERE ps.prod_id = 100;

--------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

--------------------------------------------------------------------

100 iphone 5s 5/21/2014 5/24/2014 Color : Black

--------------------------------------------------------------------

--update statement with out condition

--If you try to execute update statement without condition it'll update all the records inside the
table.

UPDATE prod_details ps

SET ps.comments = 'None';

5 row updated in 0.031 seconds


SELECT *

FROM prod_details ps;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 None

101 Samsung Galaxy III 8/20/2014 8/23/2014 None

103 Moto X 5/11/2014 5/24/2014 None

104 Moto G 5/19/2014 5/22/2014 None

105 Nokia Lumis 720p 5/26/2014 5/29/2014 None

----------------------------------------------------------------------

--if your update text contain ' means you can use following metnod (use '')

UPDATE prod_details ps

SET ps.comments = 'Some product''s are not available'

WHERE ps.prod_id = 100;

1 row updated in 0.031 seconds

SELECT *
FROM prod_details ps

WHERE ps.prod_id = 100;

------------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

------------------------------------------------------------------------------------

100 iphone 5s 5/21/2014 5/24/2014 Some product's are not available

------------------------------------------------------------------------------------

DELETE

Syntax:

DELETE FROM table_name

WHERE condition(s);

DELETE FROM prod_details

WHERE prod_id IN (104, 105);

2 row(S) deleted in 0.032 seconds

SELECT *

FROM prod_details ps;


---------------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Some product's are not available

101 Samsung Galaxy III 8/20/2014 8/23/2014 None

103 Moto X 5/11/2014 5/24/2014 None

---------------------------------------------------------------------------------------

DELETE FROM prod_details;

3 row(s) deleted in 0.062 seconds.

SELECT * FROM prod_details;

no rows selected.

DROP TABLE prod_details;

MERGE = Insert + Update

-- will update soon.


Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Data Define Language

Data Definition Language (DDL) statements are used to define the database structure or schema.

Some examples:

CREATE - to create objects in the database.

ALTER - alters the structure of the database.

ADD

RENAME

MODIFY

DROP

DROP - delete objects from the database

TRUNCATE - remove all records from a table,

including all spaces allocated for the records are removed.

COMMENT - add comments to the data dictionary.

RENAME - rename an object.


Creating Table

--------------------------------------------------------------------------

Data Types Size Default Size Explanation

--------------------------------------------------------------------------

NUMBER(P,S) P: 1 to 38 we can store number between 0-9

S: -84 to 127

VARCHAR2 4000 Bytes we can store 0-9, a-z, A-Z and special characters

CHAR 2000 Bytes 1

DATE 7 Used to store Date

TIMESTAMP Includes year, month, day, hour, minute, and seconds.

LONG 2 GB Only one long column is allowed in a table.

We can't use this column in ORDER BY clause.

CLOB 4 GB Character Large Object

BLOB Binary Larger Object

--------------------------------------------------------------------------

CREATE

ALTER : ADD RENAME MODIFY DROP RENAME

RENAME

DROP

TRUNCATE
--creating table

CREATE TABLE friends_details_tb

Name VARCHAR2(30) ,

Phone NUMBER(10) ,

Gender CHAR ,

dob DATE ,

other_details LONG ,

make_dtm TIMESTAMP

);

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

-----------------------------
--maximum you can keep 255 columns in a table

ALTER : Colum level operations

ADD RENAME MODIFY DROP

ADD : Used to add a column after the table hase been created

ALTER TABLE friends_details_tb

ADD email VARCHAR2(30);

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

EMAIL VARCHAR2(30)
-----------------------------

--adding multiple columns by using single ALTER statement

SYNTAX

ALTER TABLE friends_details_tb

ADD (

column_1 Data_type(size),

column_2 Data_type(size),

column_3 Data_type(size),

column_4 Data_type(size)

);

RENAME : Used to Rename a column

ALTER TABLE friends_details_tb

RENAME COLUMN email TO email_id;

DESC friends_details_tb;

-----------------------------
NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

MODIFY : Used to change the data type or size of the data type.

ALTER TABLE friends_details_tb

MODIFY other_details CLOB;

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)
GENDER CHAR(1)

DOB DATE

OTHER_DETAILS CLOB

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

--Modifying multiple columns at a time

ALTER TABLE friends_details_tb

MODIFY ( column_name_1 old_datatype(new_size),

column_name_2 new_datatype(old_size),

column_name_3 new_datatype(new_size)

);

DROP : Used to drop the column after the table has been created.

ALTER TABLE friends_details_tb

DROP COLUMN other_details;

DESC friends_details_tb;

-----------------------------
NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

RENAME : Used to Rename a particular table.

SYNTAX

RENAME old_table_name TO new_table_name;

RENAME friends_details_tb TO fnd_det;

DESCRIBE fnd_det;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)
PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

TRUNCATE : Used to remove the entire content of the table (not a structure)

SYNTAX

TRUNCATE TABLE table_name;

TRUNCATE TABLE fnd_det;

DROP : Used to drop the tabel (Data + stucture of the table get removed from the database )

DROP TABLE fnd_det;

*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Statements in Oracle

Data Definition Language (DDL)

DDL statements are used to define the database structure or schema. Some examples:

CREATE - to create objects in the database

ALTER - alters the structure of the database

ADD

RENAME

MODIFY

DROP

DROP - delete objects from the database

TRUNCATE - remove all records from a table,

including all spaces allocated for the records are removed

RENAME - rename an object

Data Manipulation Language (DML)


DML statements are used for managing data within schema objects. Some examples:

INSERT - insert data into a table

UPDATE - updates existing data within a table

DELETE - deletes all records from a table, the space for the records remain

MERGE - UPSERT operation (insert or update)

Data Control Language (DCL)

DCL statements. Some examples:

GRANT - gives users access privileges to database

REVOKE - withdraw access privileges given with the GRANT command

Transaction Control (TCL)

TCL statements are used to manage the changes made by DML statements. It allows
statements to be grouped together into logical transactions.

COMMIT - save work done

SAVEPOINT - identify a point in a transaction to which you can later roll back

ROLLBACK - restore database to original since the last COMMIT


Posted 28th May 2014 by Unknown

0 Add a comment

MAY

19

DECODE and CASE statement

CREATE TABLE students (

roll_no NUMBER(4) ,

Name VARCHAR2(30) ,

dept_cd VARCHAR2(20) ,

total_marks NUMBER(3)

);

BEGIN

INSERT INTO students VALUES (2000,'Rahul','CSE',480);

INSERT INTO students VALUES (2001,'Bala','IT', 390);

INSERT INTO students VALUES (2002,'Ramesh','CSE',250);

INSERT INTO students VALUES (2003,'Karthi','EEE',185);

INSERT INTO students VALUES (2004,'Ravi','IT',345);

END;
/

SELECT * FROM students;

DECODE

Decode is a function. Its a Oracle one.

Works like IF-THEN-ELSE.

You can use DECODE only in SELECT clause.

In DECODE you can include 255 things include Exep, search , result and default value.

Example

SELECT roll_no,

NAME,

dept_cd,

DECODE(dept_cd,

'CSE',

'Computer Science and Engineering',

'IT',

'Information Technology',

'Default Value') AS "DEPARTMENT NAME"

FROM students;

Sample Output
------------------------------------------------------------

ROLL_NO NAME DEPT_CD DEPARTMENT NAME

------------------------------------------------------------

2000 Rahul CSE Computer Science and Engineering

2001 Bala IT Information Technology

2002 Ramesh CSE Computer Science and Engineering

2003 Karthi EEE Default Value

2004 Ravi IT Information Technology

------------------------------------------------------------

CASE

CASE is an expression. Its a ANSI standard.

Compare to DECODE case will be more faster.

Example

SELECT roll_no,

NAME,

dept_cd,

total_marks,

CASE

WHEN total_marks > 500 THEN

'A Grade'

WHEN total_marks > 400 THEN

'B Grade'
WHEN total_marks > 300 THEN

'C Grade'

ELSE

'U Grade'

END AS "GRADE"

FROM students;

-----------------------------------------------

ROLL_NO NAME DEPT_CD TOTAL_MARKS GRADE

-----------------------------------------------

2000 Rahul CSE 480 B Grade

2001 Bala IT 390 C Grade

2002 Ramesh CSE 250 U Grade

2003 Karthi EEE 185 U Grade

2004 Ravi IT 345 C Grade

-----------------------------------------------

Interview Questions:

What is DECODE?

What is CASE?

Difference between CASE and DECODE? Which one is faster?

Posted 19th May 2014 by Unknown


0 Add a comment

MAY

19

Sub Query

Query with in another query

1. Single Row sub query

2. Multi row Sub query

select * from employees;

Want to fetch the person Who are all getting salary more than Neena's salary ?

Neena's Salary : 17000

Select First_name, salary

From Employees

Where salary > 17000;

--change in Neena's salary won't work for the above query.


Select salary From Employees

Where First_name = 'Neena';

Sub Query :

Select First_name, salary

From Employees

Where salary > (

Select salary From Employees

Where First_name = 'Neena'

);

Select * from employees;

Select salary From Employees

Where First_name = 'Alexander';

Sub Query Returns one value it is called as Single row sub query

Sub Query Returns more than one value it is called as Multi row sub query
Single row sub query operators :

> < >= <= = <>

Multiple Row Sub query operators :

IN ALL ANY

Who are all getting salary more than the average salary?

Select

First_name,

Salary

From

Employees

WHERE

Salary > (

SELECT Round(avg(salary),0)

FROM Employees

);

Multiple Row Sub query (In ANY ALL)


Select First_name,Department_id, salary

From Employees

Where salary in(

Select Salary From Employees

Where First_name = 'Alexander'

);

Any : Minimum Value will be taken (3100)

Select First_name,Department_id, salary

From Employees

Where salary > ANY(

Select Salary From Employees

Where First_name = 'Alexander'

);

All : Maximum Value will be taken (9000)

Select First_name,Department_id, salary

From Employees

Where salary > All(

Select Salary From Employees

Where First_name = 'Alexander'

);
We can use sub query in all the classes except Group by and order by class.

Select

From

Where

-----------Group by

having

-----------Order by

SELECT

( Select Count(*) from Employees Where Department_id = 90 )Executive,

( Select Count(*) from Employees Where Department_id = 60 ) IT,

( Select Count(*) from Employees Where Department_id = 10 ) Administration,

( Select Count(*) from Employees Where Department_id = 100) Finance

FROM

Dual;

Select Min(salary) From Employees;

Select Min(salary) from

Select * from Employees


Where Department_id = 60

);

What is INLINE VIEW?

If u use sub query in From it is call it is as INLINE VIEW.

Intermediate result set

Correlated sub query

SELECT employee_number, name

FROM employees Bob

WHERE salary > (

SELECT AVG(salary)

FROM employees

WHERE department = Bob.department

);

Posted 19th May 2014 by Unknown

0 Add a comment
Loading

Dynamic Views theme. Powered by Blogger.

Oracle sql & Pl/sql

search

Home Sql and pl/sql Sql Interview Questions

JUL

20

INLINE view in Oracle with 12c New Features

Named sub Query in FROM clause is call it as INLINE VIEW.

Oracle process a inline view faster than sub query

Inline View in Oracle

--Query to display all the employees who are all getting salary more than their department
average salary

SELECT First_name

, last_name

, salary

, department_id

FROM employees a , ( SELECT b.department_id

, AVG(b.salary) avg_sal
FROM employees b

GROUP BY b.department_id

)b

WHERE a.department_id = b.department_id

AND a.salary > b.avg_salary;

Display all the customer who have placed more number of orders by using INLINE view

CREATE TABLE customer_order_det_tb

( custm_id NUMBER ,

custm_nm VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

ttl_amt NUMBER(7,2)

);

BEGIN

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '11-Jul-15' , 45000.00);

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '14-Jul-15' , 27000.00);

INSERT INTO customer_order_det_tb VALUES(101, 'Raja' , '13-Jul-15' , 17000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 34000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 38000.00);

COMMIT;

END;
SELECT c.*

FROM customer_order_det_tb c;

--------------------------------------------

custm_id custm_nm order_dt ttl_amt

--------------------------------------------

100 Murugappan 7/11/2015 45000.00

100 Murugappan 7/14/2015 27000.00

101 Raja 7/13/2015 17000.00

102 Ramesh 7/15/2015 34000.00

102 Ramesh 7/15/2015 38000.00

--------------------------------------------

--Writing a Quer to display all the customer who have placed maximum number of order

--Query #1 for inline view

SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC;

--------------------------------

custm_id custm_nm total_odr


--------------------------------

100 Murugappan 2

102 Ramesh 2

101 Raja 1

--------------------------------

--Query #2 for inline view

SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm;

----------

total_odr

----------

----------

Inline view to find all the customers who have placed maximum number of orders

/****************************************

Syntax

SELECT * FROM <query1> x, <query2> y

WHERE contition;
****************************************/

SELECT query1.* FROM

( SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC

) query1,

( SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm

) query2

WHERE query1.total_odr = query2.total_odr;

-------------------------------

custm_id custm_nm total_odr

-------------------------------

100 Murugappan 2

102 Ramesh 2

-------------------------------

DROP TABLE customer_order_det_tb;

--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT
SELECT first_name, salary

FROM ( SELECT first_name, salary

FROM employees e

WHERE job_id NOT IN ('SALESMAN','PRESIDENT')

ORDER BY salary DESC

WHERE ROWNUM < 4;

New Oracle 12c Inline view Syntax

LATERAL clause for In-line views

Allows for columns in the inline view to be accessed!!

Example :

--in 11g

SELECT * FROM employees e, (

SELECT *

FROM departments d

WHERE e.department_id = d.department_id);

ORA-0090: "E"."DEPARTMENT_ID": Invalid Identifier


--in 12c

SELECT * FROM employees e, LATERAL(

SELECT *

FROM departments d

WHERE e.department_id = d.department_id

);

--in 11g

WITH t

AS

( SELECT LEVEL a

FROM dual

CONNECT BY LEVEL <= 30)

SELECT *

FROM t, (SELECT *

FROM employees

WHERE department_id = t.a

);

ORA-00904: "T"."A": invalid Identifier

--in 12c
WITH t

AS

(SELECT LEVEL a FROM dual CONNECT BY LEVEL <= 30)

SELECT * FROM t,

LATERAL(SELECT *

FROM employees

WHERE department_id = t.a);

Hope you have enjoyed this little article

Feed backs are always Welcome :) (:

Posted 20th July 2015 by Unknown

0 Add a comment

JAN

23

Salary Related Questions in Oracle

--creating table

CREATE TABLE employee_data


(

eid NUMBER(4),

ename VARCHAR2(30),

depno NUMBER(3),

salary NUMBER(8)

);

BEGIN

--Inserting records

INSERT INTO employee_data VALUES(1000,'Name01',90,30000);

INSERT INTO employee_data VALUES(1001,'Name02',90,6000);

INSERT INTO employee_data VALUES(1002,'Name03',90,23000);

INSERT INTO employee_data VALUES(1003,'Name04',60,35000);

INSERT INTO employee_data VALUES(1004,'Name05',60,60000);

INSERT INTO employee_data VALUES(1005,'Name06',60,30000);

INSERT INTO employee_data VALUES(1006,'Name07',80,36000);

INSERT INTO employee_data VALUES(1007,'Name08',80,29000);

INSERT INTO employee_data VALUES(1008,'Name09',80,37000);

INSERT INTO employee_data VALUES(1009,'Name10',80,41000);

COMMIT;

END;

/
SELECT * FROM employee_data

ORDER BY salary DESC;

--query to find maximum salary from employee_data table

SELECT MAX(salary) FROM employee_data;

--query to find minimum salary from employee_data table

SELECT MIN(salary) FROM employee_data;

--query to find second maximum salary from employee_data table

SELECT MAX(salary)

FROM employee_data

WHERE salary NOT IN (SELECT MAX(salary)

FROM employee_data);

--query to select 5th maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data
ORDER BY salary DESC)

WHERE rownum <= 5);

--query to select nth maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= &n);

--query to select all the details of the employee whose getting nth maximum salary

SELECT *

FROM (SELECT emp.*,

rownum rn

FROM (SELECT *

FROM employee_data

ORDER BY salary DESC) emp)

WHERE rn = 9;

--same query using row_numbr( ) function


SELECT *

FROM (SELECT emp.*,

row_number() over(ORDER BY salary) rank

FROM employee_data emp)

WHERE rank = 9;

--same query using rank( ) function

SELECT *

FROM (SELECT emp.*,

rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--same query using dense_rank( ) function

SELECT *

FROM (SELECT emp.*,

dense_rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--query to display display maximum salary in all the department


SELECT e.depno "Department id",

MAX(salary) "Maximum Salary"

FROM employee_data e

GROUP BY e.depno;

--query to display all the employees who are all getting salary more than average salary of the
company

SELECT e.* FROM employee_data e

WHERE salary > (SELECT AVG(salary) FROM employee_data);

--query to display all the employees who are all getting salary more than their department
average salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE department_id = OUT.department_id);

--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE employee_id = OUT.manager_id);

Documented By : Murugappan Annamalai

Posted on : 23-Jan-15 16:34:00 IST.

Hope you have enjoyed this little article

Feed backs are always welcome :)

Posted 23rd January 2015 by Unknown

7 View comments

JAN

22

Why prefer COALESCE over NVL


Documented By : Nimish Garg

I prefer using "COALESCE" over "NVL" is some of the scenarios. Last week One of my friend
asked me what is the advantage of using "COALESCE" where we can simply use "NVL". I simply
gave him the reply from Oracle Docs i.e. NVL lets you replace null (returned as a blank) with a
string in the results of a query and COALESCE returns the first non-null expr in the expression list.
Oracle Database uses short-circuit evaluation with "COALESCE".

He replied that he knows the difference, he knows that "COALESCE" can take multiple arguments
and so on. He was more interested in understanding "short-circuit evaluation" of "COALESCE"
and the scenarios where I prefer using "COALESCE" over "NVL".

To make him understand I created following function which takes One second in every execution
and simply returns '--null--' and executed 2 very similar queries one with NVL and other with
COALESCE.

SQL> create or replace function f_null return varchar2

2 is

3 begin

4 dbms_lock.sleep(1);

5 return '--null--';

6 end;

7 /

Function created.

Following are the queries which I used to demonstrate that NVL evaluates both arguments even
if the second argument is not used and COALESCE uses short-circuit evaluation i.e. it only
evaluates the arguments only if they are needed.

SQL> select e.empno, e.ename ename, nvl(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.
Elapsed: 00:00:14.01

SQL> select e.empno, e.ename ename, coalesce(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.
Elapsed: 00:00:01.01

Here we can see easily that the first query with NVL took 14+ seconds, one second for each
record even if the "f_null" value was used only in one record. On the contrary as mentioned in
Oracle Documentation "COALESCE" uses its "short-circuit evaluation" and "f_null" was called
only once and so second query took only One Second. "COALESCE" is certainly use less resources
than NVL.

Posted 22nd January 2015 by Unknown

0 Add a comment

DEC

21

Constraints

It Enforce Rule On Table

We can create constraint at the time of Creating Table

1. Column Level Declaration

2. Table Level Declaration


1. We can provide own name.

Format : [part_of_project_name-table_name-column_name-constraint_type]

Example : gmind_emp_id_pk _uk _ck _f

2. system name name

Format : sys_cn

Example : SYS_C405323

We can create constraint after the table has been created

Types

Primary Key

Not allowed Null value

Not allowed you to enter duplicate value

Ex : Employee_id, Student_id

Unique Key
allowed Null value

Not allowed you to enter duplicate value

Ex : Contact_no, email

Foreign Key

It will allowed you to enter NULL and Duplicate value.

c1(pk) : 1 2 3

c2(f) : 1 1 2 3 4 Not allowed

Allowed you to enter duplicate value and null value

Not Null

It will not allowed you to enter null value

Check

You can check your own condition

Simple Table for understanding


------------------------------------

Duplicate NULL

------------------------------------

Primary Key X X

Unique Key X Allowed

Foreign Key Allowed Allowed

------------------------------------

creating table with all constraint type

Create table my_stu_details

S_id Number(2),

S_name Varchar2(30) Not Null, --SYS_Cn

s_mail Varchar2(30),

s_gender char(1),

s_did Number(3),

Constraint my_stu_sid_pk PRIMARY KEY (s_id),

constraint my_stu_mail_uk UNIQUE (s_mail) ,

Constraint my_stu_gen_ck CHECK (s_gender IN ('M', 'F', 'm', 'f')),

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

);
DESC my_stu_details;

------------------------------------

Name Type Nullable

------------------------------------

S_ID NUMBER(2)

S_NAME VARCHAR2(30)

S_MAIL VARCHAR2(30) Y

S_GENDER CHAR(1) Y

S_DID NUMBER(3) Y

------------------------------------

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name1' , 'name1@gmail.com' , 'm' , 60 );

Select * from my_stu_details;

Validating Primary Key


Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-00001: unique constraint (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (NULL, 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-01400: cannot insert NULL into (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (2 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

Validating NOT NULL Constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , NULL , 'name3@gmail.com' , 'F' , 80 );


ORA-01400: cannot insert NULL into ("HR"."MY_STU_DETAILS"."S_NAME")

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , 'Name3' , 'name3@gmail.com' , 'F' , 80 );

Select * from my_stu_details;

Validating Unique Key Constraint

--Duplicate Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , 'name3@gmail.com' , 'F' , 80 );

ORA-00001: unique constraint (HR.MY_STU_MAIL_UK) violated

--Null Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , null , 'M' , 70 );


Select * from my_stu_details;

Validating Check constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'j' , 70 );

ORA-02290: check constraint (HR.MY_STU_GEN_CK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'M' , 70 );

Select * from my_stu_details;

Validating Foreign Key

Select * from Departments;


Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 3 );

ORA-02291: integrity constraint (HR.MY_STU_DID_FK) violated - parent key not found

Departments table : parent table

my_stu_details : Child table

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

--------------------------------------------------------

s_id s_name s_mail s_gender s_did

--------------------------------------------------------

1 name1 name1@gmail.com m 60

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 M 70
5 Name5 name5@gmail.com M 70

6 Name6 name6@gmail.com F 90

--------------------------------------------------------

Deleting the Primary key value which is referred by Foreign Key

Select * from Departments;

DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID

------------------------------------------------------------

60 IT 103 1400 <---- Delete

-- don't execute this query

--Delete From Departments

--Where Department_id = 60;

1) ON DELETE SET NULL

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID


-------------------------------------------------

6 Name6 name6@gmail.com F 90

1 name1 name1@gmail.com m -

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

2) ON DELETE SET CASCADE

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

Syntax

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE CASCADE
Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE SET NULL

Constraint Related Data Dictionary Table information.

To view constraint Information

SELECT c.owner,

c.constraint_name,

c.constraint_type,

c.table_name,

c.r_constraint_name,

c.status

FROM user_constraints c

WHERE c.table_name = 'MY_STU_DETAILS';

------------------------------------------------------------------------------------

owner constraint_name constraint_type table_name r_constraint_name status

------------------------------------------------------------------------------------

HR SYS_C004023 C MY_STU_DETAILS ENABLED

HR MY_STU_GEN_CK C MY_STU_DETAILS ENABLED


HR MY_STU_SID_PK P MY_STU_DETAILS ENABLED

HR MY_STU_MAIL_UK U MY_STU_DETAILS ENABLED

HR MY_STU_DID_FK R MY_STU_DETAILS DEPT_ID_PK ENABLED

------------------------------------------------------------------------------------

To view constraint name with corresponding column name

SELECT * FROM user_cons_columns c

WHERE c.table_name = 'MY_STU_DETAILS';

-------------------------------------------------------------

owner constraint_name table_name column_name position

-------------------------------------------------------------

HR MY_STU_MAIL_UK MY_STU_DETAILS S_MAIL 1

HR MY_STU_SID_PK MY_STU_DETAILS S_ID 1

HR MY_STU_GEN_CK MY_STU_DETAILS S_GENDER

HR SYS_C004023 MY_STU_DETAILS S_NAME

HR MY_STU_DID_FK MY_STU_DETAILS S_DID 1

-------------------------------------------------------------

Creating Composite Primary Key


Creating Primary Key with more than one number of column

ALTER TABLE table_name

ADD CONSTRAINT constraint_name PRIMARY KEY(column1, column_2 , column3);

In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.

creating constraint after the table creation

ALTER TABLE table_name

ADD CONSTRAINT constraint_name CONSTRAINT_TYPE(column_name);

ALTER TABLE table_name

DROP CONSTRAINT constraint_name;

ALTER TABLE table_name

DROP PRIMARY KEY;

To drop related foreign key


ALTER TABLE table_name

DROP PRIMARY KEY CASCADE;

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name;

Disable constraint with related foreign key constraint

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name CASCADE;

ALTER TABLE table_name

ENABLE CONSTRAINT constraint_name;

Interview Questions

What are all the type of constraint available in oracle?

Difference between PRIMARY KEY and UNIQUE key.

Difference between PRIMARY KEY ans FOREIGN KEY.

Difference between UNIQUE key and FOREIGN KEY.


Is it possible to create tow primary key in single table.

Write a syntax to create FOREIGN constraint.

How to create constraint after the table has been created?

How to enable and disable a constraint.

Which data dictionary table contains information about constraints?

Which Data Dictionary table contains information about constraint with corresponding column
name?

What is composite primary key?

Explain ON DELETE CASCADE and ON DELETE SET NULL option.

~Thanks For Reading~

Post your valuable feedback below

Posted 21st December 2014 by Unknown

1 View comments

UnknownMay 22, 2017 at 12:39 AM

good

Reply
DEC

listagg in Oracle 11g

Oracle 11gR2 listagg built-in function allows for many table columns to be displayed within a
single row, a non-first-normal form display

Syntax :

listagg(column_value,'delimiter') WITHIN GROUP(ORDER BY column_name)

--Example 1:

CREATE TABLE test_ins(empid NUMBER,product VARCHAR2(30));

BEGIN

INSERT INTO test_ins VALUES( 101,'pendrive');

INSERT INTO test_ins VALUES( 102,'toy');

INSERT INTO test_ins VALUES( 101,'ipod');

INSERT INTO test_ins VALUES( 102,'hat');

INSERT INTO test_ins VALUES( 103,'cpu');

INSERT INTO test_ins VALUES( 104,'pen');

INSERT INTO test_ins VALUES( 104,'car');

INSERT INTO test_ins VALUES( 104,'mat');

INSERT INTO test_ins VALUES( 105,'tv');


INSERT INTO test_ins VALUES( 106,'laptop');

commit;

END;

SELECT * FROM test_ins;

SELECT empid "Employee",

listagg(product,

',') within

GROUP (ORDER BY empid) "Products"

FROM test_ins

GROUP BY empid;

-->-- Result set --<--


DROP TABLE test_ins;

-->-- Example 2

select department_id "Department id", listagg(first_name,', ') WITHIN GROUP(ORDER BY


employee_id) "Employees"

FROM employees

WHERE department_id IN (10,20,30,60)

GROUP BY department_id;

-->-- Result set --<--

Posted 4th December 2014 by Unknown

0 Add a comment

NOV

Condition and Looping Statement


IF

IF ELSE

Multiple IF ELSE

LOOP

FOR LOOP

WHILE LOOP

create table test_udt(id NUMBER, salary NUMBER);

BEGIN

INSERT INTO test_udt VALUES(001,23000);

INSERT INTO test_udt VALUES(002,43000);

INSERT INTO test_udt VALUES(003,78000);

INSERT INTO test_udt VALUES(004,25000);

INSERT INTO test_udt VALUES(005,26000);

INSERT INTO test_udt VALUES(006,90000);

Commit;

END;

select * from test_udt;


IF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 1;

IF v_salary > 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

END IF;

commit;

END;

IF ELSE
DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

ELSE

UPDATE test_udt t

SET t.salary = v_salary+20007

WHERE t.id = v_id ;

END IF;

commit;

END;

--same example with less number of lines


DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

v_salary := v_salary+10005;

ELSE

v_salary := v_salary+20007;

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;


Multiple IF ELSIF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 3;

IF v_id = 1 THEN

v_salary := 1000;

dbms_output.put_line('1 inside');

ELSIF v_id = 2 THEN

v_salary := 2000;

dbms_output.put_line('2 inside');

ELSIF v_id = 3 THEN

v_salary := 3000;

dbms_output.put_line('3 inside');

ELSIF v_id = 4 THEN

v_salary := 4000;

dbms_output.put_line('4 inside');

END IF;
UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

LOOP

--syntax

LOOP

--statements

--increment

--exit statement

END LOOP;

CREATE TABLE prod_details (pid VARCHAR2(3), pname VARCHAR2(30));

DECLARE

i NUMBER := 1;
x VARCHAR2(3);

BEGIN

LOOP

x := lpad(i,3,'0');

dbms_output.put_line('x value : '|| x);

INSERT INTO prod_details VALUES(i, 'Product '||i);

EXIT WHEN i >900;

i := i+1;

IF MOD(i,100) = 0 THEN

commit;

dbms_output.put_line('commit executed');

END IF;

END LOOP;

END;

SELECT * FROM prod_details ORDER BY 1;

DROP TABLE prod_details;

FOR LOOP

BEGIN

FOR I in 1..5
LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

FOR LOOP - Reverse

BEGIN

FOR I in REVERSE 14..50

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

WHILE LOOP

DECLARE

i_val NUMBER:=0;

BEGIN

WHILE (i_val < 11)

LOOP

dbms_output.put_line('The value of I is '||i_val);

i_val := i_val + 1;
END LOOP;

END;

sample output:

The value of I is 0

The value of I is 1

The value of I is 2

The value of I is 3

The value of I is 4

The value of I is 5

The value of I is 6

The value of I is 7

The value of I is 8

The value of I is 9

The value of I is 10

Posted 8th November 2014 by Unknown

0 Add a comment

OCT
21

Bulk Collect

This is used for array fetches

With this you can retrieve multiple rows of data with a single round trip.

This reduces the number of context switches between the pl/sql and sql engines.

You can use bulk collect in both dynamic and static sql.

You can use bulk collect in select, fetch into and returning into clauses.

SQL engine automatically initializes and extends the collections you reference in the bulk
collect clause.

You can fetch into multiple collections with one column each.

You can use the limit clause of bulk collect to restrict the no of rows retrieved.

SELECT * FROM product_details;

-->-- Bulk collect in FETCH INTO --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN
OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Bulk collect in SELECT clause --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

BEGIN

SELECT * BULK COLLECT INTO dta FROM product_details;

FOR i IN dta.FIRST .. dta.LAST LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;
-->-- LIMIT in Bulk collect --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta LIMIT 30;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Multiple fetches in INTO clause --<--

SELECT * FROM product_details;


DECLARE

TYPE alldata_typ1 IS TABLE OF product_details.p_id%TYPE;

TYPE alldata_typ2 IS TABLE OF product_details.p_name%TYPE;

dta1 alldata_typ1;

dta2 alldata_typ2;

CURSOR proddt_cur IS

SELECT p_id, p_name FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta1, dta2;

CLOSE proddt_cur;

FOR i IN dta1.FIRST .. dta1.COUNT LOOP

dbms_output.put_line('Department Id : ' || dta1(i));

END LOOP;

FOR i IN dta2.FIRST .. dta2.COUNT LOOP

dbms_output.put_line('Department Name : ' || dta2(i));

END LOOP;

END;

/
DROP TABLE dep_details;

DROP TABLE product_details;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Ref Cursor

This is unconstrained cursor which will return different types depends upon the user input.

Ref cursors cannot be closed implicitly.

Ref cursor with return type is called strong cursor.

Ref cursor without return type is called weak cursor.

You can declare ref cursor type in package spec as well as body.

You can declare ref cursor types in local subprograms or anonymous blocks.

CREATE OR REPLACE PROCEDURE ref_c_sp(dep_det_c IN OUT SYS_REFCURSOR)

AS

BEGIN

OPEN dep_det_c
FOR

SELECT * FROM dep_details d;

END;

DECLARE

dep_det_c SYS_REFCURSOR;

tab_data dep_details%ROWTYPE;

BEGIN

ref_c_sp(dep_det_c);

LOOP

FETCH dep_det_c INTO tab_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department Name : '|| tab_data.d_name);

END LOOP;

CLOSE dep_det_c;

END;

/*sample output*/

Department Name : Admin

Department Name : HR
Department Name : Sales

Department Name : Marketing

DROP PROCEDURE ref_c_sp;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Cursor

SQL Private work Area where the query get passed and executed.

Types

******

Implicit(SQL)

Explicit

-->-- advanced cursor types --<--

Parametrized Cursor

Ref Cursor
Implicit

********

ORACLE implicitly opens a cursor to process each SQL statement not associated with an
explicitly declared cursor.

PL/SQL lets you refer to the most recent implicit cursor as the SQL” cursor. So, although you
cannot use the OPEN,

FETCH, and CLOSE statements to control an implicit cursor, you can still use cursor attributes to
access information

about the most recently executed SQL statement.

Cursor Stages

**************

OPEN cursor_name

FETCH (with in loop)

CLOSE cursor_name

Explicit

The set of rows returned by a query can consist of zero, one, or multiple rows,

depending on how many rows meet your search criteria. When a query returns multiple rows,

you can explicitly define a cursor to process the rows. You use three commands to control the
cursor
Cursor Attributes

*****************

%FOUND

%NOTFOUND

%ISOPEN

%ROWCOUNT

%BULK_ROWCOUNT --<-- used to handle error while using bulk collection.

%BULK_EXCEPTIONS --<-- used to handle error while using bulk collection.

Cursor Declaration

DECLARE

CURSOR <cursor_name>

IS

<SELECT statement>

BEGIN

--> some stmt

END;

Cursor Loop

Loop

While Loop

For Loop
Cursor Clauses

Return

For update

Where current of

Bulk collect

-->-- creating table

create table product_details

p_id NUMBER,

p_name VARCHAR2(30),

p_order_dt DATE

);

-->-- Inserting data

BEGIN

FOR i IN 1 .. 75 LOOP

INSERT INTO product_details VALUES (i, 'prod_name_' || i, SYSDATE + i);

END LOOP;

commit;

END;
-->-- selecting data

SELECT * FROM product_details;

---------------------------------------------

p_id p_name p_order_dt

---------------------------------------------

1 prod_name_1 10/11/2014 3:48:32 PM

2 prod_name_2 10/12/2014 3:48:32 PM

3 prod_name_3 10/13/2014 3:48:32 PM

4 prod_name_4 10/14/2014 3:48:32 PM

5 prod_name_5 10/15/2014 3:48:32 PM

6 prod_name_6 10/16/2014 3:48:32 PM

7 prod_name_7 10/17/2014 3:48:32 PM

8 prod_name_8 10/18/2014 3:48:32 PM

9 prod_name_9 10/19/2014 3:48:32 PM

10 prod_name_10 10/20/2014 3:48:32 PM

11 prod_name_11 10/21/2014 3:48:32 PM

12 prod_name_12 10/22/2014 3:48:32 PM

13 prod_name_13 10/23/2014 3:48:32 PM

14 prod_name_14 10/24/2014 3:48:32 PM

15 prod_name_15 10/25/2014 3:48:32 PM

16 prod_name_16 10/26/2014 3:48:32 PM


17 prod_name_17 10/27/2014 3:48:32 PM

18 prod_name_18 10/28/2014 3:48:32 PM

19 prod_name_19 10/29/2014 3:48:32 PM

20 prod_name_20 10/30/2014 3:48:32 PM

---------------------------------------------

----------------------------------------------

Implicit Cursor

----------------------------------------------

--will update soon

----------------------------------------------

Explicit Cursor

----------------------------------------------

**********************************************

Processing cursor data by using LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS
SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND; --<-- if next record not found means control will
come out from the loop

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )


DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

EXIT WHEN prod_detail_cur%FOUND; --<-- if next record found means control will come
out from the loop

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )


DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;
END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor Already closed

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP
FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

-->-- CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )


Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor closed

**********************************************

Processing cursor data by using WHILE LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

OPEN prod_detail_cur;

FETCH prod_detail_cur

INTO all_data;

WHILE prod_detail_cur%FOUND LOOP

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');


FETCH prod_detail_cur

INTO all_data;

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

************************************************************

Processing cursor data by using FOR LOOP - CURSOR FOR LOOP

************************************************************

DECLARE

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

FOR i IN prod_detail_cur
LOOP

dbms_output.put_line('Product id : ' || i.p_id ||

' Product Name : ' || i.p_name ||

' ( Orderd on : ' || TRIM(i.p_order_dt) || ' )');

END LOOP;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

Parameterized Cursor

*********************

This was used when you are going to use the cursor in more than one place with different
values for the same where clause.

Cursor parameters must be in mode.

Cursor parameters may have default values.

The scope of cursor parameter is within the select statement.


CREATE TABLE dep_details(d_id NUMBER,d_name VARCHAR2(30), location_id NUMBER);

BEGIN

INSRT INTO dep_details VALUES(001,'Admin',1010);

INSRT INTO dep_details VALUES(002,'HR',1010);

INSRT INTO dep_details VALUES(003,'Sales',1020);

INSRT INTO dep_details VALUES(004,'Marketing',1020);

commit;

END;

SELECT * FROM dep_details;

----------------------------

d_id d_name location_id

----------------------------

1 Admin 1010

2 HR 1010

3 Sales 1020

4 Marketing 1020

----------------------------
DECLARE

-->--Declaring parameterized cursor

CURSOR dep_det_c(p_location_id NUMBER) IS

SELECT * FROM dep_details d WHERE d.location_id = p_location_id;

all_data dep_details%ROWTYPE;

BEGIN

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

OPEN dep_det_c(1010);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

-->-- opening same cursor with different input value

OPEN dep_det_c(1020);

LOOP

FETCH dep_det_c

INTO all_data;
EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

END;

/*sample output*/

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 1 Department Name : Admin

Department id : 2 Department Name : HR

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 3 Department Name : Sales

Department id : 4 Department Name : Marketing

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Posted 21st October 2014 by Unknown

0 Add a comment
OCT

21

Handling Exception

Error Handling in oracle

ERROR

Any departure from the expected behavior of the system or program,

which stops the working of the system is an error.

Types : compile time error

Run time error

EXCEPTION

Any error or problem which one can handle and continue to work normally.

Handling Exception

When exception is raised, control passes to the exception section of the block.

i.e. EXCEPTION

WHEN name_of_exception THEN

Types : Pre Defined Exceptions

User Defined Exceptions


Predefined Exception

*********************

Oracle has predefined several exceptions that correspond to the most common oracle errors.

------------------------------------------------------------------------

Exception Oracle Error SQL Code Value

------------------------------------------------------------------------

ZERO_DIVIDE ORA-01476 -1476

NO_DATA_FOUND ORA-01403 +100

DUP_VAL_ON_INDEX ORA-00001 -1

TOO_MANY_ROWS ORA-01422 -1422

VALUE_ERROR ORA-06502 -6502

CURSOR_ALREADY_OPEN ORA-06511 -6511

OTHERS

------------------------------------------------------------------------

-->-- ZERO_DIVIDE --<--

Your program attempts to divide a number by zero.

DECLARE

v_result NUMBER;
BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN ZERO_DIVIDE THEN

dbms_output.put_line('Divisor is equal to zero');

END;

-->-- NO_DATA_FOUND --<--

Single row SELECT returned no rows or your program referenced a deleted element in a nested
table

or an uninitialized element in an associative array (index-by table).

CREATE TABLE test_tb(id NUMBER PRIMARY KEY);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN NO_DATA_FOUND THEN

dbms_output.put_line('There is no data inside the table');

END;
-->-- DUP_VAL_ON_INDEX --<--

A program attempted to insert duplicate values in a column that is constrained by a unique


index.

INSERT INTO test_tb VALUES (1);

INSERT INTO test_tb VALUES (2);

commit;

BEGIN

INSERT INTO test_tb VALUES (2);

EXCEPTION

WHEN DUP_VAL_ON_INDEX THEN

dbms_output.put_line('Duplicate values are not allowed');

END;

-->-- TOO_MANY_ROWS --<--

Single row SELECT returned multiple rows.

DECLARE

v_id NUMBER;
BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN TOO_MANY_ROWS THEN

dbms_output.put_line('Query returning more than one row');

END;

DROP TABLE test_tb;

-->-- VALUE_ERROR --<--

An arithmetic, conversion, truncation, or size constraint error occurred.

DECLARE

num1 NUMBER(2);

BEGIN

num1 := 345;

EXCEPTION

WHEN VALUE_ERROR THEN

dbms_output.put_line('check the size of the variable');

END;

-->-- CURSOR_ALREADY_OPEN --<--


A program attempted to open an already opened cursor.

CREATE TABLE emp(id NUMBER, name VARCHAR2(30));

BEGIN

INSERT INTO emp VALUES(1,'Name1');

INSERT INTO emp VALUES(2,'Name2');

INSERT INTO emp VALUES(3,'Name3');

INSERT INTO emp VALUES(4,'Name4');

COMMIT;

END;

SELECT * FROM emp;

DECLARE

cursor emp_c IS

SELECT * FROM emp;

all_data emp%ROWTYPE;

BEGIN

OPEN emp_c;

OPEN emp_c;

NULL;
CLOSE emp_c;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

END;

DROP TABLE emp;

-->-- OTHERS --<--

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

WHEN OTHERS THEN

dbms_output.put_line('Some other error ' || SQLERRM);

END;

User Defined Exception

**********************
A user-defined exception is an error that is defined by the programmer.

User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,

exceptions have a type EXCEPTION and scope.

DECLARE

v_gender CHAR := '&gender';

gender_ex EXCEPTION;

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE gender_ex;

END IF;

dbms_output.put_line('Gender : '||v_gender);

EXCEPTION

WHEN gender_ex THEN

dbms_output.put_line('Please Enter valid gender');

END;

create table test_insert (id NUMBER, Name VARCHAR2(30));

DECLARE

abort_ex EXCEPTION;
BEGIN

FOR i IN 1..100

LOOP

BEGIN

IF mod(i,10)=0 THEN

RAISE abort_ex;

END IF;

INSERT INTO test_insert VALUES(i, 'Name'||i);

EXCEPTION

WHEN abort_ex THEN

NULL;

END;

END LOOP;

COMMIT;

END;

SELECT * FROM test_insert;

DROP TABLE test_insert;

SQLERRM and SQLCODE

********************

SQLCODE returns the current error code, and SQLERRM returns the current error message
text;
For user-defined exception SQLCODE returns 1 and SQLERRM returns “user-defined
exception”.

SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.

CREATE TABLE test_tb (id NUMBER);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

dbms_output.put_line(v_id);

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('SQLERRM : ' || SQLERRM);

dbms_output.put_line('SQLCODE : ' || SQLCODE);

END;

/*sample output*/

SQLERRM : ORA-01403: no data found

SQLCODE : 100

DROP TABLE test_tb;


PRAGMA EXCEPTION_INIT

*********************

Using this you can associate a named exception with a particular oracle error.

This gives you the ability to trap this error specifically, rather than via an OTHERS handler.

Syntax:

PRAGMA EXCEPTION_INIT(exception_name, oracle_error_number);

DECLARE

v_result NUMBER;

PRAGMA EXCEPTION_INIT(Invalid, -1476);

BEGIN

SELECT 453 / 0 INTO v_result FROM dual;

dbms_output.put_line('Result : ' || v_result);

EXCEPTION

WHEN INVALID THEN

dbms_output.put_line('Invalid Exception');

END;

RAISE_APPLICATION_ERROR
************************

You can use this built-in function to create your own error messages, which can be more
descriptive than named exceptions.

Error Number :

Oracle Error Range : From -00000 to -19999

User Error Range : From -20000 to -20999

DECLARE

v_gender CHAR := '&gender';

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE_APPLICATION_ERROR(-20003, 'Enter valid gender');

END IF;

dbms_output.put_line('Gender : ' || v_gender);

END;

Posted 21st October 2014 by Unknown

1 View comments
RajmohanMarch 13, 2018 at 6:49 AM

How to get the two table data without using Joins and sub query,union?

Reply

OCT

Package

1. You can groups logical related subprogram (procedures and functions)

2. It consist of two parts

I) specification

II) Body

3. It allows the oracle server to read multiple object in to a memory once

4. You can declare global variable,cursor, user define exeption

5. Overloading

6. we can't create anonyms block inside the package

create table err_log(sno NUMBER, u_name VARCHAR2(30), error_msg CLOB, hap_tm


TIMESTAMP);

select * from err_log;


--stand alone procedure

CREATE OR REPLACE PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id


%TYPE) IS

v_salary employees.salary%TYPE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT salary,

first_name

INTO v_salary,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line('Salary of ' || v_first_name || ' is ' || v_salary);

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);
commit;

END emp_sal_sp;

BEGIN

-- Call the procedure

emp_sal_sp(p_employee_id => :p_employee_id);

END;

CREATE OR REPLACE PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id


%TYPE) IS

v_hire_date DATE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT hire_date,

first_name

INTO v_hire_date,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line(v_first_name || ' hired on ' || to_char(v_hire_date,'month ddth,


yyyy'));

EXCEPTION

WHEN OTHERS THEN


v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_hdt_sp;

BEGIN

-- Call the procedure

emp_hdt_sp(p_employee_id => :p_employee_id);

END;

create or replace function sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER

IS

v_c NUMBER;

BEGIN

v_c := p_a + p_b;

RETURN v_c;
END;

--Specification Part

CREATE OR REPLACE PACKAGE emp_pkg

IS

PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id%TYPE);

PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id%TYPE);

FUNCTION sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER;

END emp_pkg ;

--Body Part

CREATE OR REPLACE PACKAGE BODY emp_pkg

IS

PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id%TYPE) IS

v_salary employees.salary%TYPE;
v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT salary,

first_name

INTO v_salary,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line('Salary of ' || v_first_name || ' is ' || v_salary);

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_sal_sp;

PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id%TYPE) IS

v_hire_date DATE;
v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT hire_date,

first_name

INTO v_hire_date,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line(v_first_name || ' hired on ' || to_char(v_hire_date,'month ddth,


yyyy'));

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_hdt_sp;

FUNCTION sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER

IS
v_c NUMBER;

BEGIN

v_c := p_a + p_b;

RETURN v_c;

END;

END emp_pkg;

A package specification can exist without a package body, but

a package body can't exist without a package specification.

--Executing procedure inside the package

BEGIN

emp_pkg.emp_sal_sp(120);

END;

--Executing function inside the package

SELECT emp_pkg.sum_fn(23,567) FROM dual;

-- You can declare global variable,cursor, user define exeption


create or replace package all_detail

as

PROCEDURE emp2sal (a IN NUMBER);

PROCEDURE emp2exep (a IN NUMBER);

FUNCTION add2num (a IN NUMBER, b IN NUMBER)

RETURN NUMBER;

c NUMBER(8); --global declaration

abort_ex EXCEPTION; --global exception declaration

CURSOR emp_rec --global cursor declaration

IS

SELECT first_name, salary, hire_date, department_id

FROM employees;

End all_detail;

create or replace package body all_detail

as

PROCEDURE emp2sal (a IN NUMBER)


AS

BEGIN

SELECT salary

INTO c

FROM Employees

WHERE Employee_id = a;

Dbms_output.put_line('Salary of Employee ' || a || ' is ' || c);

EXCEPTION

WHEN no_data_found THEN

Dbms_output.put_line('Please enter valid id');

END emp2sal;

PROCEDURE emp2exep (a IN NUMBER)

AS

BEGIN

SELECT Round(Months_between(sysdate,hire_date)/12)

INTO c

FROM Employees

WHERE Employee_id = a;

Dbms_output.put_line( c || ' Years');

EXCEPTION
WHEN no_data_found THEN

Dbms_output.put_line('Please enter valid id');

END emp2exep;

FUNCTION add2num (a IN NUMBER, b IN NUMBER)

RETURN NUMBER

AS

BEGIN

c := a+b;

RETURN C;

END;

End all_detail;

/*Declaring a Bodiless Package */

CREATE OR REPLACE PACKAGE global_constant

IS

mile_2_kilo CONSTANT NUMBER := 1.6093;

kilo_2_mile CONSTANT NUMBER := 0.6214;

yard_2_meter CONSTANT NUMBER := 0.9144;


meter_2_yard CONSTANT NUMBER := 1.0936;

END global_constant;

BEGIN

DBMS_OUTPUT.PUT_LINE('20 miles = ' || 20*global_constant.mile_2_kilo||' km');

END;

/*Forward Declaration in package */

DECLARE

PROCEDURE P2; -- forward declaration

PROCEDURE P3;

PROCEDURE P1 IS

BEGIN

dbms_output.put_line('From procedure p1');

p2;

END P1;

PROCEDURE P2 IS

BEGIN

dbms_output.put_line('From procedure p2');

p3;
END P2;

PROCEDURE P3 IS

BEGIN

dbms_output.put_line('From procedure p3');

END P3;

BEGIN

p1;

END;

sample output:

From procedure p1

From procedure p2

From procedure p3

Drop package package_name;

Drop package body package_name;

SELECT text FROM user_source u

WHERE u.name = 'EMP_PKG';


Interview Questions:

What is package?

Advantage of package

Is it possible to create package body with out package specification?

what is package overloading?

what is forward declaration in package?

which data dictionary table contain source code of package?

How to declare global variable, exception and cursor?

How to execute procedure and function inside the package?

Posted 4th October 2014 by Unknown

0 Add a comment

OCT

%TYPE and %ROWTYPE

--%type is used to fetch the data type of the particular column


create table product_details

p_id NUMBER(3),

p_nm VARCHAR2(30),

p_qty NUMBER(8),

order_dt DATE

);

BEGIN

INSERT INTO product_details VALUES(100,'Name0',400,'23-Mar-13');

INSERT INTO product_details VALUES(101,'Name1',600,'26-Apr-13');

INSERT INTO product_details VALUES(102,'Name2',800,'27-Jan-12');

INSERT INTO product_details VALUES(103,'Name3',300,'23-Jul-11');

INSERT INTO product_details VALUES(104,'Name4',200,'22-Aug-11');

INSERT INTO product_details VALUES(105,'Name5',500,'25-Oct-12');

commit;

END;

SELECT * FROM product_details;

------------------------------------

P_ID P_NM P_QTY ORDER_DT


------------------------------------

100 Name0 400 03/23/2013

101 Name1 600 04/26/2013

102 Name2 800 01/27/2012

103 Name3 300 07/23/2011

104 Name4 200 08/22/2011

105 Name5 500 10/25/2012

------------------------------------

DECLARE

v_name VARCHAR2(4);

BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 100;

dbms_output.put_line('Product Name : ' || v_name);

--error numeric or value error

END;

DECLARE

v_name VARCHAR2(5);
BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 100;

dbms_output.put_line('Product Name : ' || v_name);

END;

ALTER TABLE product_details

MODIFY p_nm VARCHAR2(15);

INSERT INTO product_details

VALUES

(106,

'name6',

700,

'26-Dec-12');

commit;

106 name6 700 12/26/2012


DECLARE

v_name VARCHAR2(5);

BEGIN

SELECT p_nm INTO v_name

FROM product_details

WHERE p_id = 106;

dbms_output.put_line('Product Name : ' || v_name);

--error

END;

DECLARE

v_name product_details.p_nm%TYPE;

BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 106;

dbms_output.put_line('Product Name : ' || v_name);

END;
/

DROP TABLE product_details;

DECLARE

dep_id departments.department_id%TYPE;

dep_name departments.department_name%TYPE;

dep_man_id departments.manager_id%TYPE;

dep_loc_id departments.location_id%TYPE;

BEGIN

SELECT department_id,

department_name,

manager_id,

location_id

INTO dep_id,

dep_name,

dep_man_id,

dep_loc_id

FROM departments

WHERE department_id = 10;


dbms_output.put_line('Department_id : ' || dep_id);

dbms_output.put_line('Department_name : ' || dep_name);

dbms_output.put_line('Manager_id : ' || dep_man_id);

dbms_output.put_line('Location_id : ' || dep_loc_id);

END;

--%rowtype is used to fetch the data type of all the column

--Insted of using %type if we use %rowtype means we can reduce the no of variables that we
declare

DECLARE

dep_detail departments%ROWTYPE;

BEGIN

SELECT *

INTO dep_detail

FROM departments

WHERE department_id = 10;

dbms_output.put_line('Department_id : ' || dep_detail.department_id);


dbms_output.put_line('Department_name : ' || dep_detail.department_name);

dbms_output.put_line('Manager_id : ' || dep_detail.manager_id);

dbms_output.put_line('Location_id : ' || dep_detail.location_id);

END;

DROP TABLE dept_details;

CREATE TABLE dept_details

dept_id number(3) ,

dept_name varchar2(30),

dept_manager_name varchar2(30)

);

insert into dept_details values(10,'dept1','manager_name1');

insert into dept_details values(20,'dept2','manager_name2');

SELECT * FROM dept_details;

-------------------------------------------------------

| DEPT_ID | DEPT_NAME | DEPT_MANAGER_NAME |


+------------+-----------------------+-----------------

| 10 | dept1 | manager_name1 |

| 20 | dept2 | manager_name2 |

------------+-----------------------+------------------

DECLARE

all_data dept_details%ROWTYPE;

BEGIN

all_data.dept_id := 100;

all_data.dept_name := 'Admin';

all_data.dept_manager_name := 'John';

UPDATE dept_details

SET ROW = all_data

WHERE dept_id = 10;

dbms_output.put_line(SQL%ROWCOUNT || ' Row(s) get updated');

END;

1 Row(s) get updated


select * from dept_details;

---------------------------------------------------

| DEPT_ID | DEPT_NAME | DEPT_MANAGER_NAME|

---------------------------------------------------

| 100 | Admin | John |

| 20 | dept2 | manager_name2 |

---------------------------------------------------

Interview Question :

1. What is the use of %TYPE?

2. What is the use of %ROWTYPE?

3. Difference between %TYPE and %ROWTYPE?

Posted 2nd October 2014 by Unknown

0 Add a comment
SEP

29

BULK Exceptions

/************************************************************************

* Handling Exceptions in Bulk Operations *

* Documented on 29-SEP-14 04.35.35.980894 PM +05:30 *

* Document By : Murugappan Annamalai *

* Reference : http://www.dba-oracle.com/plsql/t_plsql_exceptions.htm *

************************************************************************/

CREATE TABLE bulk_tb (ran_num NUMBER NOT NULL);

--inserting data using bulk collect

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP
v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

commit;

END;

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

200

TRUNCATE TABLE bulk_tb;

sample2.sql --without exception part

DECLARE
TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

commit;

END;

/*

Error Message :

ORA-01400: cannot insert NULL into ("HR"."bulk_tb"."ran_num")

ORA-06512: at line 15

*/
sample2.sql --with exception part

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

BEGIN

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

COMMIT;

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('Error while inserting bulk record '||SQLERRM);


END;

END;

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

99

SQL%BULK_EXCEPTIONS(i).ERROR_INDEX

Holds the iteration (not the subscript) of the original FORALL statement that raised the
exception.

In sparsely populated collections,

the exception row must be found by looping through the original collection the correct
number of times.

SQL%BULK_EXCEPTIONS(i).ERROR_CODE

Holds the exceptions error code.


The total number of exceptions can be returned using the collections COUNT method,

which returns zero if no exceptions were raised. The save_exceptions.sql script,

a modified version of the handled_exception.sql script, demonstrates this functionality.

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

v_ex_count NUMBER(4);

abort_ex EXCEPTION;

PRAGMA EXCEPTION_INIT(abort_ex, -24381);

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

v_dat(150) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

EXECUTE IMMEDIATE 'TRUNCATE TABLE bulk_tb';


BEGIN

FORALL i IN v_dat.FIRST..v_dat.LAST SAVE EXCEPTIONS

INSERT INTO bulk_tb VALUES(v_dat(i));

COMMIT;

EXCEPTION

WHEN abort_ex THEN

v_ex_count := SQL%BULK_EXCEPTIONS.COUNT;

FOR i IN 1..v_ex_count LOOP

dbms_output.put_line('Error: ' || i ||' Array Index: ' || SQL


%BULK_EXCEPTIONS(i).error_index ||

' Message: ' || SQLERRM(SQL%BULK_EXCEPTIONS(i).ERROR_CODE));

END LOOP;

END;

END;

/*

Sample output:

Error: 1 Array Index: 100 Message: -1400: non-ORACLE exception

Error: 2 Array Index: 150 Message: -1400: non-ORACLE exception

*/
SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

198

SAVE EXCEPTIONS clause being removed, in the above script now traps a different error number.

The output from this script is listed below.

/*

Sample output:

Error: 1 Array Index: 100 Message: -1400: non-ORACLE exception

*/

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

99
SELECT COUNT(*) FROM bulk_tb;

DROP TABLE bulk_tb;

Posted 29th September 2014 by Unknown

0 Add a comment

SEP

29

Cursor - FOR UPDATE

/************************************************************************

* FOR UPDATE clause in oracle *

* Document By : Murugappan Annamalai *

************************************************************************/

create table prod_details(p_id VARCHAR2(30), P_name VARCHAR2(30));


BEGIN

--Inserting data into prod_details table

FOR i IN 1..50 LOOP

INSERT INTO prod_details VALUES(i,'pname'||i);

END LOOP;

commit;

END;

SELECT * FROM prod_details;

DECLARE

CURSOR PROD_DTLS_C IS

SELECT * FROM PROD_DETAILS T1 FOR UPDATE OF P_ID;

V_PID PROD_DETAILS.P_ID%TYPE;

V_PRDNAME PROD_DETAILS.P_NAME%TYPE;

BEGIN

OPEN PROD_DTLS_C;

LOOP
FETCH PROD_DTLS_C INTO V_PID, V_PRDNAME;

IF PROD_DTLS_C%NOTFOUND THEN

EXIT;

ELSE

UPDATE PROD_DETAILS P

SET P.P_ID = LPAD(P_ID, 10, 0)

WHERE CURRENT OF PROD_DTLS_C;

END IF;

END LOOP;

CLOSE PROD_DTLS_C;

COMMIT;

END;

select * from PROD_DETAILS;

TRUNCATE TABLE prod_details;

BEGIN

--Inserting data into prod_details table

FOR i IN 1..50 LOOP


INSERT INTO prod_details VALUES(i,'pname'||i);

END LOOP;

commit;

END;

DECLARE

CURSOR PROD_DTLS_C IS

SELECT * FROM PROD_DETAILS T1 FOR UPDATE OF P_ID;

V_PID PROD_DETAILS.P_ID%TYPE;

V_PRDNAME PROD_DETAILS.P_NAME%TYPE;

BEGIN

OPEN PROD_DTLS_C;

LOOP

FETCH PROD_DTLS_C INTO V_PID, V_PRDNAME;

IF PROD_DTLS_C%NOTFOUND THEN

EXIT;

ELSE
UPDATE PROD_DETAILS P

SET P.P_ID = LPAD(P_ID, 10, 0)

WHERE CURRENT OF PROD_DTLS_C;

END IF;

COMMIT;

END LOOP;

CLOSE PROD_DTLS_C;

--COMMIT;

END;

select * from PROD_DETAILS;

Posted 29th September 2014 by Unknown

0 Add a comment

MAY

28

Escape Sequence in Oracle

Escape special characters when writing SQL queries


--to include single '

SELECT 'Steven's salary is more than 50k INR' AS "SAL_DETAILS"

FROM Dual;

ORA-01756 : quoted string not properly terminated

SELECT 'Steven''s salary is more than 50k INR' AS "SAL_DETAILS"

FROM Dual;

SAL_DETAILS

---------------------------------------

Steven's salary is more than 50k INR

--to include double '

SELECT 'You can print double quot ('''') in oracle' "Info"

FROM Dual;

Info
---------------------------------------

You can print double quot ('') in oracle

SELECT q'[some test ' some test ' some text ']' AS "In 10g"

FROM dual;

In 10g

------------------------------------

some test ' some test ' some text '

--Escape wild card characters ( _ and % )

The LIKE keyword allows for string searches.

The '_' wild card character is used to match exactly one character

While '%' is used to match zero or more occurrences of any characters.

These characters can be escaped in SQL as follows.

WITH mail_ids AS

SELECT 'an.murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an_murugappan@gmail.com' mail FROM Dual


UNION

SELECT 'an%murugappan@gmail.com' mail FROM Dual

SELECT * FROM mail_ids

WHERE mail LIKE '__$_%' ESCAPE '$';

mail

----------------------------------

an_murugappan@gmail.com

WITH mail_ids AS

SELECT 'an.murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an_murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an%murugappan@gmail.com' mail FROM Dual

SELECT * FROM mail_ids

WHERE mail LIKE '__/%%' ESCAPE '/';

mail

----------------------------------
an%murugappan@gmail.com

Escape ampersand (&) characters in SQL*Plus

SQL> select '&a' FROM dual;

'23'

----

23

SQL> SET ESCAPE '\'

SQL> select '\&a' FROM dual;

'&A'

----

&a

SQL> SET SCAN OFF;

SQL> select '&a' FROM dual;

'&A'

----

&a
SQL> SET SCAN ON;

SQL> select '&a' FROM dual;

'45'

----

45

Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Data Manipulation Language

Data Manipulation Language (DML) statements are used for managing data within schema
objects. Some examples:

INSERT - insert data into a table

UPDATE - updates existing data within a table

DELETE - deletes all records from a table, the space for the records remain

MERGE - UPSERT operation (insert or update)


CREATE TABLE prod_details

prod_id NUMBER(4) ,

prod_name VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

Deliver_dt DATE DEFAULT SYSDATE+3 ,

comments VARCHAR2(300)

);

SELECT * FROM prod_details;

no_data_found

INSERT

INSERT INTO prod_details(prod_id,prod_name,order_dt,deliver_dt,comments)

VALUES(100,'Apple iphone 5s','21-May-14','24-May-14','Color : Black');

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS


---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

---------------------------------------------------------------------------

--Inserting records with out mentioning column name

INSERT INTO prod_details

VALUES(101,'Samsung Galaxy III','20-Aug-14','23-Aug-14','Color : White');

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

---------------------------------------------------------------------------

--Inserting selective number of values

INSERT INTO prod_details

VALUES(103,'Moto X','11-May-14','13-May-14');

ORA-00947 : not enough values


--While inserting selective number of values mentioning column name is compulsory.

INSERT INTO prod_details (prod_id,prod_name,order_dt,deliver_dt)

VALUES(103,'Moto X','11-May-14','13-May-14');

SELECT * FROM prod_details;

--------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

--------------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

--------------------------------------------------------------------------------

--Inserting NULL value.

--If you want to insert NULL value you can ignore that column at the time of inserting

--or we can use NULL keyword to insert NULL.

INSERT INTO prod_details

VALUES(104,'Moto G','19-May-14','22-May-14',NULL);

SELECT * FROM prod_details;


---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Noto G 5/19/2014 5/22/2014

---------------------------------------------------------------------------

--if you are not providing values for order_dt and deliver_dt column default value can be taken.

INSERT INTO prod_details(prod_id,prod_name,comments)

VALUES(105,'Nokia Lumis 720p','Color : Red');

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

----------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Moto G 5/19/2014 5/22/2014


105 Nokia Lumis 720p 5/26/2014 5/29/2014 Color : Red

---------------------------------------------------------------------------

--Inserting data by using sub query

CREATE TABLE test_tab (id NUMBER, Name VARCHAR2(30));

INSERT INTO test_tab VALUES(1,'Name1');

INSERT INTO test_tab VALUES(2,'Name2');

INSERT INTO test_tab VALUES(3,'Name3');

SELECT COUNT(*) FROM test_tab;

COUNT(*)

-------

--creating table by using sub query (with out data)

CREATE TABLE ins_chk

SELECT * FROM test_tab


WHERE id = 900;

SELECT COUNT(*) FROM ins_chk;

COUNT(*)

-------

--Inserting data by using sub query

--copying data from test_tab to ins_chk

INSERT INTO ins_chk (SELECT * FROM test_tab);

3 rows inserted in 0.047 seconds.

SELECT COUNT(*) FROM ins_chk;

COUNT(*)

-------

DROP TABLE test_tab;


DROP TABLE ins_chk;

UPDATE

Syntax :

UPDATE table_name

SET column1_name = column1_value,

column2_name = column2_value,

column2_name = column3_value,

columnn_name = columnn_value

WHERE condition(s);

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

----------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Moto G 5/19/2014 5/22/2014


105 Nokia Lumis 720p 5/26/2014 5/29/2014 Color : Red

---------------------------------------------------------------------------

UPDATE prod_details ps

SET ps.prod_name = 'iphone 5s'

WHERE ps.prod_id = 100;

1 row updated in 0.031 seconds

SELECT *

FROM prod_details ps

WHERE ps.prod_id = 100;

--------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

--------------------------------------------------------------------

100 iphone 5s 5/21/2014 5/24/2014 Color : Black

--------------------------------------------------------------------

--update statement with out condition

--If you try to execute update statement without condition it'll update all the records inside the
table.

UPDATE prod_details ps

SET ps.comments = 'None';


5 row updated in 0.031 seconds

SELECT *

FROM prod_details ps;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 None

101 Samsung Galaxy III 8/20/2014 8/23/2014 None

103 Moto X 5/11/2014 5/24/2014 None

104 Moto G 5/19/2014 5/22/2014 None

105 Nokia Lumis 720p 5/26/2014 5/29/2014 None

----------------------------------------------------------------------

--if your update text contain ' means you can use following metnod (use '')

UPDATE prod_details ps

SET ps.comments = 'Some product''s are not available'

WHERE ps.prod_id = 100;

1 row updated in 0.031 seconds


SELECT *

FROM prod_details ps

WHERE ps.prod_id = 100;

------------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

------------------------------------------------------------------------------------

100 iphone 5s 5/21/2014 5/24/2014 Some product's are not available

------------------------------------------------------------------------------------

DELETE

Syntax:

DELETE FROM table_name

WHERE condition(s);

DELETE FROM prod_details

WHERE prod_id IN (104, 105);

2 row(S) deleted in 0.032 seconds

SELECT *
FROM prod_details ps;

---------------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Some product's are not available

101 Samsung Galaxy III 8/20/2014 8/23/2014 None

103 Moto X 5/11/2014 5/24/2014 None

---------------------------------------------------------------------------------------

DELETE FROM prod_details;

3 row(s) deleted in 0.062 seconds.

SELECT * FROM prod_details;

no rows selected.

DROP TABLE prod_details;

MERGE = Insert + Update

-- will update soon.


Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Data Define Language

Data Definition Language (DDL) statements are used to define the database structure or schema.

Some examples:

CREATE - to create objects in the database.

ALTER - alters the structure of the database.

ADD

RENAME

MODIFY

DROP

DROP - delete objects from the database

TRUNCATE - remove all records from a table,

including all spaces allocated for the records are removed.

COMMENT - add comments to the data dictionary.

RENAME - rename an object.


Creating Table

--------------------------------------------------------------------------

Data Types Size Default Size Explanation

--------------------------------------------------------------------------

NUMBER(P,S) P: 1 to 38 we can store number between 0-9

S: -84 to 127

VARCHAR2 4000 Bytes we can store 0-9, a-z, A-Z and special characters

CHAR 2000 Bytes 1

DATE 7 Used to store Date

TIMESTAMP Includes year, month, day, hour, minute, and seconds.

LONG 2 GB Only one long column is allowed in a table.

We can't use this column in ORDER BY clause.

CLOB 4 GB Character Large Object

BLOB Binary Larger Object

--------------------------------------------------------------------------

CREATE

ALTER : ADD RENAME MODIFY DROP RENAME

RENAME

DROP

TRUNCATE
--creating table

CREATE TABLE friends_details_tb

Name VARCHAR2(30) ,

Phone NUMBER(10) ,

Gender CHAR ,

dob DATE ,

other_details LONG ,

make_dtm TIMESTAMP

);

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

-----------------------------
--maximum you can keep 255 columns in a table

ALTER : Colum level operations

ADD RENAME MODIFY DROP

ADD : Used to add a column after the table hase been created

ALTER TABLE friends_details_tb

ADD email VARCHAR2(30);

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)
EMAIL VARCHAR2(30)

-----------------------------

--adding multiple columns by using single ALTER statement

SYNTAX

ALTER TABLE friends_details_tb

ADD (

column_1 Data_type(size),

column_2 Data_type(size),

column_3 Data_type(size),

column_4 Data_type(size)

);

RENAME : Used to Rename a column

ALTER TABLE friends_details_tb

RENAME COLUMN email TO email_id;

DESC friends_details_tb;
-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

MODIFY : Used to change the data type or size of the data type.

ALTER TABLE friends_details_tb

MODIFY other_details CLOB;

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)
PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS CLOB

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

--Modifying multiple columns at a time

ALTER TABLE friends_details_tb

MODIFY ( column_name_1 old_datatype(new_size),

column_name_2 new_datatype(old_size),

column_name_3 new_datatype(new_size)

);

DROP : Used to drop the column after the table has been created.

ALTER TABLE friends_details_tb

DROP COLUMN other_details;

DESC friends_details_tb;
-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

RENAME : Used to Rename a particular table.

SYNTAX

RENAME old_table_name TO new_table_name;

RENAME friends_details_tb TO fnd_det;

DESCRIBE fnd_det;

-----------------------------

NAME TYPE

-----------------------------
NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

TRUNCATE : Used to remove the entire content of the table (not a structure)

SYNTAX

TRUNCATE TABLE table_name;

TRUNCATE TABLE fnd_det;

DROP : Used to drop the tabel (Data + stucture of the table get removed from the database )

DROP TABLE fnd_det;

*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Statements in Oracle

Data Definition Language (DDL)

DDL statements are used to define the database structure or schema. Some examples:

CREATE - to create objects in the database

ALTER - alters the structure of the database

ADD

RENAME

MODIFY

DROP

DROP - delete objects from the database

TRUNCATE - remove all records from a table,

including all spaces allocated for the records are removed

RENAME - rename an object

Data Manipulation Language (DML)


DML statements are used for managing data within schema objects. Some examples:

INSERT - insert data into a table

UPDATE - updates existing data within a table

DELETE - deletes all records from a table, the space for the records remain

MERGE - UPSERT operation (insert or update)

Data Control Language (DCL)

DCL statements. Some examples:

GRANT - gives users access privileges to database

REVOKE - withdraw access privileges given with the GRANT command

Transaction Control (TCL)

TCL statements are used to manage the changes made by DML statements. It allows
statements to be grouped together into logical transactions.

COMMIT - save work done

SAVEPOINT - identify a point in a transaction to which you can later roll back

ROLLBACK - restore database to original since the last COMMIT


Posted 28th May 2014 by Unknown

0 Add a comment

MAY

19

DECODE and CASE statement

CREATE TABLE students (

roll_no NUMBER(4) ,

Name VARCHAR2(30) ,

dept_cd VARCHAR2(20) ,

total_marks NUMBER(3)

);

BEGIN

INSERT INTO students VALUES (2000,'Rahul','CSE',480);

INSERT INTO students VALUES (2001,'Bala','IT', 390);

INSERT INTO students VALUES (2002,'Ramesh','CSE',250);

INSERT INTO students VALUES (2003,'Karthi','EEE',185);

INSERT INTO students VALUES (2004,'Ravi','IT',345);


END;

SELECT * FROM students;

DECODE

Decode is a function. Its a Oracle one.

Works like IF-THEN-ELSE.

You can use DECODE only in SELECT clause.

In DECODE you can include 255 things include Exep, search , result and default value.

Example

SELECT roll_no,

NAME,

dept_cd,

DECODE(dept_cd,

'CSE',

'Computer Science and Engineering',

'IT',

'Information Technology',

'Default Value') AS "DEPARTMENT NAME"

FROM students;

Sample Output
------------------------------------------------------------

ROLL_NO NAME DEPT_CD DEPARTMENT NAME

------------------------------------------------------------

2000 Rahul CSE Computer Science and Engineering

2001 Bala IT Information Technology

2002 Ramesh CSE Computer Science and Engineering

2003 Karthi EEE Default Value

2004 Ravi IT Information Technology

------------------------------------------------------------

CASE

CASE is an expression. Its a ANSI standard.

Compare to DECODE case will be more faster.

Example

SELECT roll_no,

NAME,

dept_cd,

total_marks,

CASE

WHEN total_marks > 500 THEN

'A Grade'

WHEN total_marks > 400 THEN


'B Grade'

WHEN total_marks > 300 THEN

'C Grade'

ELSE

'U Grade'

END AS "GRADE"

FROM students;

-----------------------------------------------

ROLL_NO NAME DEPT_CD TOTAL_MARKS GRADE

-----------------------------------------------

2000 Rahul CSE 480 B Grade

2001 Bala IT 390 C Grade

2002 Ramesh CSE 250 U Grade

2003 Karthi EEE 185 U Grade

2004 Ravi IT 345 C Grade

-----------------------------------------------

Interview Questions:

What is DECODE?

What is CASE?

Difference between CASE and DECODE? Which one is faster?


Posted 19th May 2014 by Unknown

0 Add a comment

MAY

19

Sub Query

Query with in another query

1. Single Row sub query

2. Multi row Sub query

select * from employees;

Want to fetch the person Who are all getting salary more than Neena's salary ?

Neena's Salary : 17000

Select First_name, salary

From Employees

Where salary > 17000;


--change in Neena's salary won't work for the above query.

Select salary From Employees

Where First_name = 'Neena';

Sub Query :

Select First_name, salary

From Employees

Where salary > (

Select salary From Employees

Where First_name = 'Neena'

);

Select * from employees;

Select salary From Employees

Where First_name = 'Alexander';

Sub Query Returns one value it is called as Single row sub query
Sub Query Returns more than one value it is called as Multi row sub query

Single row sub query operators :

> < >= <= = <>

Multiple Row Sub query operators :

IN ALL ANY

Who are all getting salary more than the average salary?

Select

First_name,

Salary

From

Employees

WHERE

Salary > (

SELECT Round(avg(salary),0)

FROM Employees

);
Multiple Row Sub query (In ANY ALL)

Select First_name,Department_id, salary

From Employees

Where salary in(

Select Salary From Employees

Where First_name = 'Alexander'

);

Any : Minimum Value will be taken (3100)

Select First_name,Department_id, salary

From Employees

Where salary > ANY(

Select Salary From Employees

Where First_name = 'Alexander'

);

All : Maximum Value will be taken (9000)

Select First_name,Department_id, salary

From Employees

Where salary > All(

Select Salary From Employees

Where First_name = 'Alexander'


);

We can use sub query in all the classes except Group by and order by class.

Select

From

Where

-----------Group by

having

-----------Order by

SELECT

( Select Count(*) from Employees Where Department_id = 90 )Executive,

( Select Count(*) from Employees Where Department_id = 60 ) IT,

( Select Count(*) from Employees Where Department_id = 10 ) Administration,

( Select Count(*) from Employees Where Department_id = 100) Finance

FROM

Dual;

Select Min(salary) From Employees;

Select Min(salary) from

(
Select * from Employees

Where Department_id = 60

);

What is INLINE VIEW?

If u use sub query in From it is call it is as INLINE VIEW.

Intermediate result set

Correlated sub query

SELECT employee_number, name

FROM employees Bob

WHERE salary > (

SELECT AVG(salary)

FROM employees

WHERE department = Bob.department

);

Posted 19th May 2014 by Unknown

0 Add a comment
Loading

Dynamic Views theme. POracle sql & Pl/sql

search

Home Sql and pl/sql Sql Interview Questions

JUL

20

INLINE view in Oracle with 12c New Features

Named sub Query in FROM clause is call it as INLINE VIEW.

Oracle process a inline view faster than sub query

Inline View in Oracle

--Query to display all the employees who are all getting salary more than their department
average salary

SELECT First_name

, last_name

, salary

, department_id

FROM employees a , ( SELECT b.department_id

, AVG(b.salary) avg_sal
FROM employees b

GROUP BY b.department_id

)b

WHERE a.department_id = b.department_id

AND a.salary > b.avg_salary;

Display all the customer who have placed more number of orders by using INLINE view

CREATE TABLE customer_order_det_tb

( custm_id NUMBER ,

custm_nm VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

ttl_amt NUMBER(7,2)

);

BEGIN

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '11-Jul-15' , 45000.00);

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '14-Jul-15' , 27000.00);

INSERT INTO customer_order_det_tb VALUES(101, 'Raja' , '13-Jul-15' , 17000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 34000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 38000.00);

COMMIT;

END;
SELECT c.*

FROM customer_order_det_tb c;

--------------------------------------------

custm_id custm_nm order_dt ttl_amt

--------------------------------------------

100 Murugappan 7/11/2015 45000.00

100 Murugappan 7/14/2015 27000.00

101 Raja 7/13/2015 17000.00

102 Ramesh 7/15/2015 34000.00

102 Ramesh 7/15/2015 38000.00

--------------------------------------------

--Writing a Quer to display all the customer who have placed maximum number of order

--Query #1 for inline view

SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC;

--------------------------------

custm_id custm_nm total_odr


--------------------------------

100 Murugappan 2

102 Ramesh 2

101 Raja 1

--------------------------------

--Query #2 for inline view

SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm;

----------

total_odr

----------

----------

Inline view to find all the customers who have placed maximum number of orders

/****************************************

Syntax

SELECT * FROM <query1> x, <query2> y

WHERE contition;
****************************************/

SELECT query1.* FROM

( SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC

) query1,

( SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm

) query2

WHERE query1.total_odr = query2.total_odr;

-------------------------------

custm_id custm_nm total_odr

-------------------------------

100 Murugappan 2

102 Ramesh 2

-------------------------------

DROP TABLE customer_order_det_tb;

--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT
SELECT first_name, salary

FROM ( SELECT first_name, salary

FROM employees e

WHERE job_id NOT IN ('SALESMAN','PRESIDENT')

ORDER BY salary DESC

WHERE ROWNUM < 4;

New Oracle 12c Inline view Syntax

LATERAL clause for In-line views

Allows for columns in the inline view to be accessed!!

Example :

--in 11g

SELECT * FROM employees e, (

SELECT *

FROM departments d

WHERE e.department_id = d.department_id);

ORA-0090: "E"."DEPARTMENT_ID": Invalid Identifier


--in 12c

SELECT * FROM employees e, LATERAL(

SELECT *

FROM departments d

WHERE e.department_id = d.department_id

);

--in 11g

WITH t

AS

( SELECT LEVEL a

FROM dual

CONNECT BY LEVEL <= 30)

SELECT *

FROM t, (SELECT *

FROM employees

WHERE department_id = t.a

);

ORA-00904: "T"."A": invalid Identifier

--in 12c
WITH t

AS

(SELECT LEVEL a FROM dual CONNECT BY LEVEL <= 30)

SELECT * FROM t,

LATERAL(SELECT *

FROM employees

WHERE department_id = t.a);

Hope you have enjoyed this little article

Feed backs are always Welcome :) (:

Posted 20th July 2015 by Unknown

0 Add a comment

JAN

23

Salary Related Questions in Oracle

--creating table

CREATE TABLE employee_data


(

eid NUMBER(4),

ename VARCHAR2(30),

depno NUMBER(3),

salary NUMBER(8)

);

BEGIN

--Inserting records

INSERT INTO employee_data VALUES(1000,'Name01',90,30000);

INSERT INTO employee_data VALUES(1001,'Name02',90,6000);

INSERT INTO employee_data VALUES(1002,'Name03',90,23000);

INSERT INTO employee_data VALUES(1003,'Name04',60,35000);

INSERT INTO employee_data VALUES(1004,'Name05',60,60000);

INSERT INTO employee_data VALUES(1005,'Name06',60,30000);

INSERT INTO employee_data VALUES(1006,'Name07',80,36000);

INSERT INTO employee_data VALUES(1007,'Name08',80,29000);

INSERT INTO employee_data VALUES(1008,'Name09',80,37000);

INSERT INTO employee_data VALUES(1009,'Name10',80,41000);

COMMIT;

END;

/
SELECT * FROM employee_data

ORDER BY salary DESC;

--query to find maximum salary from employee_data table

SELECT MAX(salary) FROM employee_data;

--query to find minimum salary from employee_data table

SELECT MIN(salary) FROM employee_data;

--query to find second maximum salary from employee_data table

SELECT MAX(salary)

FROM employee_data

WHERE salary NOT IN (SELECT MAX(salary)

FROM employee_data);

--query to select 5th maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data
ORDER BY salary DESC)

WHERE rownum <= 5);

--query to select nth maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= &n);

--query to select all the details of the employee whose getting nth maximum salary

SELECT *

FROM (SELECT emp.*,

rownum rn

FROM (SELECT *

FROM employee_data

ORDER BY salary DESC) emp)

WHERE rn = 9;

--same query using row_numbr( ) function


SELECT *

FROM (SELECT emp.*,

row_number() over(ORDER BY salary) rank

FROM employee_data emp)

WHERE rank = 9;

--same query using rank( ) function

SELECT *

FROM (SELECT emp.*,

rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--same query using dense_rank( ) function

SELECT *

FROM (SELECT emp.*,

dense_rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--query to display display maximum salary in all the department


SELECT e.depno "Department id",

MAX(salary) "Maximum Salary"

FROM employee_data e

GROUP BY e.depno;

--query to display all the employees who are all getting salary more than average salary of the
company

SELECT e.* FROM employee_data e

WHERE salary > (SELECT AVG(salary) FROM employee_data);

--query to display all the employees who are all getting salary more than their department
average salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE department_id = OUT.department_id);

--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE employee_id = OUT.manager_id);

Documented By : Murugappan Annamalai

Posted on : 23-Jan-15 16:34:00 IST.

Hope you have enjoyed this little article

Feed backs are always welcome :)

Posted 23rd January 2015 by Unknown

7 View comments

JAN

22

Why prefer COALESCE over NVL


Documented By : Nimish Garg

I prefer using "COALESCE" over "NVL" is some of the scenarios. Last week One of my friend
asked me what is the advantage of using "COALESCE" where we can simply use "NVL". I simply
gave him the reply from Oracle Docs i.e. NVL lets you replace null (returned as a blank) with a
string in the results of a query and COALESCE returns the first non-null expr in the expression list.
Oracle Database uses short-circuit evaluation with "COALESCE".

He replied that he knows the difference, he knows that "COALESCE" can take multiple arguments
and so on. He was more interested in understanding "short-circuit evaluation" of "COALESCE"
and the scenarios where I prefer using "COALESCE" over "NVL".

To make him understand I created following function which takes One second in every execution
and simply returns '--null--' and executed 2 very similar queries one with NVL and other with
COALESCE.

SQL> create or replace function f_null return varchar2

2 is

3 begin

4 dbms_lock.sleep(1);

5 return '--null--';

6 end;

7 /

Function created.

Following are the queries which I used to demonstrate that NVL evaluates both arguments even
if the second argument is not used and COALESCE uses short-circuit evaluation i.e. it only
evaluates the arguments only if they are needed.

SQL> select e.empno, e.ename ename, nvl(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.
Elapsed: 00:00:14.01

SQL> select e.empno, e.ename ename, coalesce(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.
Elapsed: 00:00:01.01

Here we can see easily that the first query with NVL took 14+ seconds, one second for each
record even if the "f_null" value was used only in one record. On the contrary as mentioned in
Oracle Documentation "COALESCE" uses its "short-circuit evaluation" and "f_null" was called
only once and so second query took only One Second. "COALESCE" is certainly use less resources
than NVL.

Posted 22nd January 2015 by Unknown

0 Add a comment

DEC

21

Constraints

It Enforce Rule On Table

We can create constraint at the time of Creating Table

1. Column Level Declaration

2. Table Level Declaration


1. We can provide own name.

Format : [part_of_project_name-table_name-column_name-constraint_type]

Example : gmind_emp_id_pk _uk _ck _f

2. system name name

Format : sys_cn

Example : SYS_C405323

We can create constraint after the table has been created

Types

Primary Key

Not allowed Null value

Not allowed you to enter duplicate value

Ex : Employee_id, Student_id

Unique Key
allowed Null value

Not allowed you to enter duplicate value

Ex : Contact_no, email

Foreign Key

It will allowed you to enter NULL and Duplicate value.

c1(pk) : 1 2 3

c2(f) : 1 1 2 3 4 Not allowed

Allowed you to enter duplicate value and null value

Not Null

It will not allowed you to enter null value

Check

You can check your own condition

Simple Table for understanding


------------------------------------

Duplicate NULL

------------------------------------

Primary Key X X

Unique Key X Allowed

Foreign Key Allowed Allowed

------------------------------------

creating table with all constraint type

Create table my_stu_details

S_id Number(2),

S_name Varchar2(30) Not Null, --SYS_Cn

s_mail Varchar2(30),

s_gender char(1),

s_did Number(3),

Constraint my_stu_sid_pk PRIMARY KEY (s_id),

constraint my_stu_mail_uk UNIQUE (s_mail) ,

Constraint my_stu_gen_ck CHECK (s_gender IN ('M', 'F', 'm', 'f')),

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

);
DESC my_stu_details;

------------------------------------

Name Type Nullable

------------------------------------

S_ID NUMBER(2)

S_NAME VARCHAR2(30)

S_MAIL VARCHAR2(30) Y

S_GENDER CHAR(1) Y

S_DID NUMBER(3) Y

------------------------------------

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name1' , 'name1@gmail.com' , 'm' , 60 );

Select * from my_stu_details;

Validating Primary Key


Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-00001: unique constraint (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (NULL, 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-01400: cannot insert NULL into (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (2 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

Validating NOT NULL Constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , NULL , 'name3@gmail.com' , 'F' , 80 );


ORA-01400: cannot insert NULL into ("HR"."MY_STU_DETAILS"."S_NAME")

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , 'Name3' , 'name3@gmail.com' , 'F' , 80 );

Select * from my_stu_details;

Validating Unique Key Constraint

--Duplicate Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , 'name3@gmail.com' , 'F' , 80 );

ORA-00001: unique constraint (HR.MY_STU_MAIL_UK) violated

--Null Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , null , 'M' , 70 );


Select * from my_stu_details;

Validating Check constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'j' , 70 );

ORA-02290: check constraint (HR.MY_STU_GEN_CK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'M' , 70 );

Select * from my_stu_details;

Validating Foreign Key

Select * from Departments;


Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 3 );

ORA-02291: integrity constraint (HR.MY_STU_DID_FK) violated - parent key not found

Departments table : parent table

my_stu_details : Child table

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

--------------------------------------------------------

s_id s_name s_mail s_gender s_did

--------------------------------------------------------

1 name1 name1@gmail.com m 60

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 M 70
5 Name5 name5@gmail.com M 70

6 Name6 name6@gmail.com F 90

--------------------------------------------------------

Deleting the Primary key value which is referred by Foreign Key

Select * from Departments;

DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID

------------------------------------------------------------

60 IT 103 1400 <---- Delete

-- don't execute this query

--Delete From Departments

--Where Department_id = 60;

1) ON DELETE SET NULL

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID


-------------------------------------------------

6 Name6 name6@gmail.com F 90

1 name1 name1@gmail.com m -

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

2) ON DELETE SET CASCADE

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

Syntax

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE CASCADE
Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE SET NULL

Constraint Related Data Dictionary Table information.

To view constraint Information

SELECT c.owner,

c.constraint_name,

c.constraint_type,

c.table_name,

c.r_constraint_name,

c.status

FROM user_constraints c

WHERE c.table_name = 'MY_STU_DETAILS';

------------------------------------------------------------------------------------

owner constraint_name constraint_type table_name r_constraint_name status

------------------------------------------------------------------------------------

HR SYS_C004023 C MY_STU_DETAILS ENABLED

HR MY_STU_GEN_CK C MY_STU_DETAILS ENABLED


HR MY_STU_SID_PK P MY_STU_DETAILS ENABLED

HR MY_STU_MAIL_UK U MY_STU_DETAILS ENABLED

HR MY_STU_DID_FK R MY_STU_DETAILS DEPT_ID_PK ENABLED

------------------------------------------------------------------------------------

To view constraint name with corresponding column name

SELECT * FROM user_cons_columns c

WHERE c.table_name = 'MY_STU_DETAILS';

-------------------------------------------------------------

owner constraint_name table_name column_name position

-------------------------------------------------------------

HR MY_STU_MAIL_UK MY_STU_DETAILS S_MAIL 1

HR MY_STU_SID_PK MY_STU_DETAILS S_ID 1

HR MY_STU_GEN_CK MY_STU_DETAILS S_GENDER

HR SYS_C004023 MY_STU_DETAILS S_NAME

HR MY_STU_DID_FK MY_STU_DETAILS S_DID 1

-------------------------------------------------------------

Creating Composite Primary Key


Creating Primary Key with more than one number of column

ALTER TABLE table_name

ADD CONSTRAINT constraint_name PRIMARY KEY(column1, column_2 , column3);

In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.

creating constraint after the table creation

ALTER TABLE table_name

ADD CONSTRAINT constraint_name CONSTRAINT_TYPE(column_name);

ALTER TABLE table_name

DROP CONSTRAINT constraint_name;

ALTER TABLE table_name

DROP PRIMARY KEY;

To drop related foreign key


ALTER TABLE table_name

DROP PRIMARY KEY CASCADE;

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name;

Disable constraint with related foreign key constraint

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name CASCADE;

ALTER TABLE table_name

ENABLE CONSTRAINT constraint_name;

Interview Questions

What are all the type of constraint available in oracle?

Difference between PRIMARY KEY and UNIQUE key.

Difference between PRIMARY KEY ans FOREIGN KEY.

Difference between UNIQUE key and FOREIGN KEY.


Is it possible to create tow primary key in single table.

Write a syntax to create FOREIGN constraint.

How to create constraint after the table has been created?

How to enable and disable a constraint.

Which data dictionary table contains information about constraints?

Which Data Dictionary table contains information about constraint with corresponding column
name?

What is composite primary key?

Explain ON DELETE CASCADE and ON DELETE SET NULL option.

~Thanks For Reading~

Post your valuable feedback below

Posted 21st December 2014 by Unknown

1 View comments

UnknownMay 22, 2017 at 12:39 AM

good

Reply
DEC

listagg in Oracle 11g

Oracle 11gR2 listagg built-in function allows for many table columns to be displayed within a
single row, a non-first-normal form display

Syntax :

listagg(column_value,'delimiter') WITHIN GROUP(ORDER BY column_name)

--Example 1:

CREATE TABLE test_ins(empid NUMBER,product VARCHAR2(30));

BEGIN

INSERT INTO test_ins VALUES( 101,'pendrive');

INSERT INTO test_ins VALUES( 102,'toy');

INSERT INTO test_ins VALUES( 101,'ipod');

INSERT INTO test_ins VALUES( 102,'hat');

INSERT INTO test_ins VALUES( 103,'cpu');

INSERT INTO test_ins VALUES( 104,'pen');

INSERT INTO test_ins VALUES( 104,'car');

INSERT INTO test_ins VALUES( 104,'mat');

INSERT INTO test_ins VALUES( 105,'tv');


INSERT INTO test_ins VALUES( 106,'laptop');

commit;

END;

SELECT * FROM test_ins;

SELECT empid "Employee",

listagg(product,

',') within

GROUP (ORDER BY empid) "Products"

FROM test_ins

GROUP BY empid;

-->-- Result set --<--


DROP TABLE test_ins;

-->-- Example 2

select department_id "Department id", listagg(first_name,', ') WITHIN GROUP(ORDER BY


employee_id) "Employees"

FROM employees

WHERE department_id IN (10,20,30,60)

GROUP BY department_id;

-->-- Result set --<--

Posted 4th December 2014 by Unknown

0 Add a comment

NOV

Condition and Looping Statement


IF

IF ELSE

Multiple IF ELSE

LOOP

FOR LOOP

WHILE LOOP

create table test_udt(id NUMBER, salary NUMBER);

BEGIN

INSERT INTO test_udt VALUES(001,23000);

INSERT INTO test_udt VALUES(002,43000);

INSERT INTO test_udt VALUES(003,78000);

INSERT INTO test_udt VALUES(004,25000);

INSERT INTO test_udt VALUES(005,26000);

INSERT INTO test_udt VALUES(006,90000);

Commit;

END;

select * from test_udt;


IF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 1;

IF v_salary > 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

END IF;

commit;

END;

IF ELSE
DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

ELSE

UPDATE test_udt t

SET t.salary = v_salary+20007

WHERE t.id = v_id ;

END IF;

commit;

END;

--same example with less number of lines


DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

v_salary := v_salary+10005;

ELSE

v_salary := v_salary+20007;

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;


Multiple IF ELSIF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 3;

IF v_id = 1 THEN

v_salary := 1000;

dbms_output.put_line('1 inside');

ELSIF v_id = 2 THEN

v_salary := 2000;

dbms_output.put_line('2 inside');

ELSIF v_id = 3 THEN

v_salary := 3000;

dbms_output.put_line('3 inside');

ELSIF v_id = 4 THEN

v_salary := 4000;

dbms_output.put_line('4 inside');

END IF;
UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

LOOP

--syntax

LOOP

--statements

--increment

--exit statement

END LOOP;

CREATE TABLE prod_details (pid VARCHAR2(3), pname VARCHAR2(30));

DECLARE

i NUMBER := 1;
x VARCHAR2(3);

BEGIN

LOOP

x := lpad(i,3,'0');

dbms_output.put_line('x value : '|| x);

INSERT INTO prod_details VALUES(i, 'Product '||i);

EXIT WHEN i >900;

i := i+1;

IF MOD(i,100) = 0 THEN

commit;

dbms_output.put_line('commit executed');

END IF;

END LOOP;

END;

SELECT * FROM prod_details ORDER BY 1;

DROP TABLE prod_details;

FOR LOOP

BEGIN

FOR I in 1..5
LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

FOR LOOP - Reverse

BEGIN

FOR I in REVERSE 14..50

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

WHILE LOOP

DECLARE

i_val NUMBER:=0;

BEGIN

WHILE (i_val < 11)

LOOP

dbms_output.put_line('The value of I is '||i_val);

i_val := i_val + 1;
END LOOP;

END;

sample output:

The value of I is 0

The value of I is 1

The value of I is 2

The value of I is 3

The value of I is 4

The value of I is 5

The value of I is 6

The value of I is 7

The value of I is 8

The value of I is 9

The value of I is 10

Posted 8th November 2014 by Unknown

0 Add a comment

OCT
21

Bulk Collect

This is used for array fetches

With this you can retrieve multiple rows of data with a single round trip.

This reduces the number of context switches between the pl/sql and sql engines.

You can use bulk collect in both dynamic and static sql.

You can use bulk collect in select, fetch into and returning into clauses.

SQL engine automatically initializes and extends the collections you reference in the bulk
collect clause.

You can fetch into multiple collections with one column each.

You can use the limit clause of bulk collect to restrict the no of rows retrieved.

SELECT * FROM product_details;

-->-- Bulk collect in FETCH INTO --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN
OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Bulk collect in SELECT clause --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

BEGIN

SELECT * BULK COLLECT INTO dta FROM product_details;

FOR i IN dta.FIRST .. dta.LAST LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;
-->-- LIMIT in Bulk collect --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta LIMIT 30;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Multiple fetches in INTO clause --<--

SELECT * FROM product_details;


DECLARE

TYPE alldata_typ1 IS TABLE OF product_details.p_id%TYPE;

TYPE alldata_typ2 IS TABLE OF product_details.p_name%TYPE;

dta1 alldata_typ1;

dta2 alldata_typ2;

CURSOR proddt_cur IS

SELECT p_id, p_name FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta1, dta2;

CLOSE proddt_cur;

FOR i IN dta1.FIRST .. dta1.COUNT LOOP

dbms_output.put_line('Department Id : ' || dta1(i));

END LOOP;

FOR i IN dta2.FIRST .. dta2.COUNT LOOP

dbms_output.put_line('Department Name : ' || dta2(i));

END LOOP;

END;

/
DROP TABLE dep_details;

DROP TABLE product_details;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Ref Cursor

This is unconstrained cursor which will return different types depends upon the user input.

Ref cursors cannot be closed implicitly.

Ref cursor with return type is called strong cursor.

Ref cursor without return type is called weak cursor.

You can declare ref cursor type in package spec as well as body.

You can declare ref cursor types in local subprograms or anonymous blocks.

CREATE OR REPLACE PROCEDURE ref_c_sp(dep_det_c IN OUT SYS_REFCURSOR)

AS

BEGIN

OPEN dep_det_c
FOR

SELECT * FROM dep_details d;

END;

DECLARE

dep_det_c SYS_REFCURSOR;

tab_data dep_details%ROWTYPE;

BEGIN

ref_c_sp(dep_det_c);

LOOP

FETCH dep_det_c INTO tab_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department Name : '|| tab_data.d_name);

END LOOP;

CLOSE dep_det_c;

END;

/*sample output*/

Department Name : Admin

Department Name : HR
Department Name : Sales

Department Name : Marketing

DROP PROCEDURE ref_c_sp;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Cursor

SQL Private work Area where the query get passed and executed.

Types

******

Implicit(SQL)

Explicit

-->-- advanced cursor types --<--

Parametrized Cursor

Ref Cursor
Implicit

********

ORACLE implicitly opens a cursor to process each SQL statement not associated with an
explicitly declared cursor.

PL/SQL lets you refer to the most recent implicit cursor as the SQL” cursor. So, although you
cannot use the OPEN,

FETCH, and CLOSE statements to control an implicit cursor, you can still use cursor attributes to
access information

about the most recently executed SQL statement.

Cursor Stages

**************

OPEN cursor_name

FETCH (with in loop)

CLOSE cursor_name

Explicit

The set of rows returned by a query can consist of zero, one, or multiple rows,

depending on how many rows meet your search criteria. When a query returns multiple rows,

you can explicitly define a cursor to process the rows. You use three commands to control the
cursor
Cursor Attributes

*****************

%FOUND

%NOTFOUND

%ISOPEN

%ROWCOUNT

%BULK_ROWCOUNT --<-- used to handle error while using bulk collection.

%BULK_EXCEPTIONS --<-- used to handle error while using bulk collection.

Cursor Declaration

DECLARE

CURSOR <cursor_name>

IS

<SELECT statement>

BEGIN

--> some stmt

END;

Cursor Loop

Loop

While Loop

For Loop
Cursor Clauses

Return

For update

Where current of

Bulk collect

-->-- creating table

create table product_details

p_id NUMBER,

p_name VARCHAR2(30),

p_order_dt DATE

);

-->-- Inserting data

BEGIN

FOR i IN 1 .. 75 LOOP

INSERT INTO product_details VALUES (i, 'prod_name_' || i, SYSDATE + i);

END LOOP;

commit;

END;
-->-- selecting data

SELECT * FROM product_details;

---------------------------------------------

p_id p_name p_order_dt

---------------------------------------------

1 prod_name_1 10/11/2014 3:48:32 PM

2 prod_name_2 10/12/2014 3:48:32 PM

3 prod_name_3 10/13/2014 3:48:32 PM

4 prod_name_4 10/14/2014 3:48:32 PM

5 prod_name_5 10/15/2014 3:48:32 PM

6 prod_name_6 10/16/2014 3:48:32 PM

7 prod_name_7 10/17/2014 3:48:32 PM

8 prod_name_8 10/18/2014 3:48:32 PM

9 prod_name_9 10/19/2014 3:48:32 PM

10 prod_name_10 10/20/2014 3:48:32 PM

11 prod_name_11 10/21/2014 3:48:32 PM

12 prod_name_12 10/22/2014 3:48:32 PM

13 prod_name_13 10/23/2014 3:48:32 PM

14 prod_name_14 10/24/2014 3:48:32 PM

15 prod_name_15 10/25/2014 3:48:32 PM

16 prod_name_16 10/26/2014 3:48:32 PM


17 prod_name_17 10/27/2014 3:48:32 PM

18 prod_name_18 10/28/2014 3:48:32 PM

19 prod_name_19 10/29/2014 3:48:32 PM

20 prod_name_20 10/30/2014 3:48:32 PM

---------------------------------------------

----------------------------------------------

Implicit Cursor

----------------------------------------------

--will update soon

----------------------------------------------

Explicit Cursor

----------------------------------------------

**********************************************

Processing cursor data by using LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS
SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND; --<-- if next record not found means control will
come out from the loop

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )


DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

EXIT WHEN prod_detail_cur%FOUND; --<-- if next record found means control will come
out from the loop

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )


DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;
END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor Already closed

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP
FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

-->-- CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )


Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor closed

**********************************************

Processing cursor data by using WHILE LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

OPEN prod_detail_cur;

FETCH prod_detail_cur

INTO all_data;

WHILE prod_detail_cur%FOUND LOOP

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');


FETCH prod_detail_cur

INTO all_data;

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

************************************************************

Processing cursor data by using FOR LOOP - CURSOR FOR LOOP

************************************************************

DECLARE

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

FOR i IN prod_detail_cur
LOOP

dbms_output.put_line('Product id : ' || i.p_id ||

' Product Name : ' || i.p_name ||

' ( Orderd on : ' || TRIM(i.p_order_dt) || ' )');

END LOOP;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

Parameterized Cursor

*********************

This was used when you are going to use the cursor in more than one place with different
values for the same where clause.

Cursor parameters must be in mode.

Cursor parameters may have default values.

The scope of cursor parameter is within the select statement.


CREATE TABLE dep_details(d_id NUMBER,d_name VARCHAR2(30), location_id NUMBER);

BEGIN

INSRT INTO dep_details VALUES(001,'Admin',1010);

INSRT INTO dep_details VALUES(002,'HR',1010);

INSRT INTO dep_details VALUES(003,'Sales',1020);

INSRT INTO dep_details VALUES(004,'Marketing',1020);

commit;

END;

SELECT * FROM dep_details;

----------------------------

d_id d_name location_id

----------------------------

1 Admin 1010

2 HR 1010

3 Sales 1020

4 Marketing 1020

----------------------------
DECLARE

-->--Declaring parameterized cursor

CURSOR dep_det_c(p_location_id NUMBER) IS

SELECT * FROM dep_details d WHERE d.location_id = p_location_id;

all_data dep_details%ROWTYPE;

BEGIN

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

OPEN dep_det_c(1010);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

-->-- opening same cursor with different input value

OPEN dep_det_c(1020);

LOOP

FETCH dep_det_c

INTO all_data;
EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

END;

/*sample output*/

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 1 Department Name : Admin

Department id : 2 Department Name : HR

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 3 Department Name : Sales

Department id : 4 Department Name : Marketing

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Posted 21st October 2014 by Unknown

0 Add a comment
OCT

21

Handling Exception

Error Handling in oracle

ERROR

Any departure from the expected behavior of the system or program,

which stops the working of the system is an error.

Types : compile time error

Run time error

EXCEPTION

Any error or problem which one can handle and continue to work normally.

Handling Exception

When exception is raised, control passes to the exception section of the block.

i.e. EXCEPTION

WHEN name_of_exception THEN

Types : Pre Defined Exceptions

User Defined Exceptions


Predefined Exception

*********************

Oracle has predefined several exceptions that correspond to the most common oracle errors.

------------------------------------------------------------------------

Exception Oracle Error SQL Code Value

------------------------------------------------------------------------

ZERO_DIVIDE ORA-01476 -1476

NO_DATA_FOUND ORA-01403 +100

DUP_VAL_ON_INDEX ORA-00001 -1

TOO_MANY_ROWS ORA-01422 -1422

VALUE_ERROR ORA-06502 -6502

CURSOR_ALREADY_OPEN ORA-06511 -6511

OTHERS

------------------------------------------------------------------------

-->-- ZERO_DIVIDE --<--

Your program attempts to divide a number by zero.

DECLARE

v_result NUMBER;
BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN ZERO_DIVIDE THEN

dbms_output.put_line('Divisor is equal to zero');

END;

-->-- NO_DATA_FOUND --<--

Single row SELECT returned no rows or your program referenced a deleted element in a nested
table

or an uninitialized element in an associative array (index-by table).

CREATE TABLE test_tb(id NUMBER PRIMARY KEY);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN NO_DATA_FOUND THEN

dbms_output.put_line('There is no data inside the table');

END;
-->-- DUP_VAL_ON_INDEX --<--

A program attempted to insert duplicate values in a column that is constrained by a unique


index.

INSERT INTO test_tb VALUES (1);

INSERT INTO test_tb VALUES (2);

commit;

BEGIN

INSERT INTO test_tb VALUES (2);

EXCEPTION

WHEN DUP_VAL_ON_INDEX THEN

dbms_output.put_line('Duplicate values are not allowed');

END;

-->-- TOO_MANY_ROWS --<--

Single row SELECT returned multiple rows.

DECLARE

v_id NUMBER;
BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN TOO_MANY_ROWS THEN

dbms_output.put_line('Query returning more than one row');

END;

DROP TABLE test_tb;

-->-- VALUE_ERROR --<--

An arithmetic, conversion, truncation, or size constraint error occurred.

DECLARE

num1 NUMBER(2);

BEGIN

num1 := 345;

EXCEPTION

WHEN VALUE_ERROR THEN

dbms_output.put_line('check the size of the variable');

END;

-->-- CURSOR_ALREADY_OPEN --<--


A program attempted to open an already opened cursor.

CREATE TABLE emp(id NUMBER, name VARCHAR2(30));

BEGIN

INSERT INTO emp VALUES(1,'Name1');

INSERT INTO emp VALUES(2,'Name2');

INSERT INTO emp VALUES(3,'Name3');

INSERT INTO emp VALUES(4,'Name4');

COMMIT;

END;

SELECT * FROM emp;

DECLARE

cursor emp_c IS

SELECT * FROM emp;

all_data emp%ROWTYPE;

BEGIN

OPEN emp_c;

OPEN emp_c;

NULL;
CLOSE emp_c;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

END;

DROP TABLE emp;

-->-- OTHERS --<--

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

WHEN OTHERS THEN

dbms_output.put_line('Some other error ' || SQLERRM);

END;

User Defined Exception

**********************
A user-defined exception is an error that is defined by the programmer.

User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,

exceptions have a type EXCEPTION and scope.

DECLARE

v_gender CHAR := '&gender';

gender_ex EXCEPTION;

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE gender_ex;

END IF;

dbms_output.put_line('Gender : '||v_gender);

EXCEPTION

WHEN gender_ex THEN

dbms_output.put_line('Please Enter valid gender');

END;

create table test_insert (id NUMBER, Name VARCHAR2(30));

DECLARE

abort_ex EXCEPTION;
BEGIN

FOR i IN 1..100

LOOP

BEGIN

IF mod(i,10)=0 THEN

RAISE abort_ex;

END IF;

INSERT INTO test_insert VALUES(i, 'Name'||i);

EXCEPTION

WHEN abort_ex THEN

NULL;

END;

END LOOP;

COMMIT;

END;

SELECT * FROM test_insert;

DROP TABLE test_insert;

SQLERRM and SQLCODE

********************

SQLCODE returns the current error code, and SQLERRM returns the current error message
text;
For user-defined exception SQLCODE returns 1 and SQLERRM returns “user-defined
exception”.

SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.

CREATE TABLE test_tb (id NUMBER);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

dbms_output.put_line(v_id);

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('SQLERRM : ' || SQLERRM);

dbms_output.put_line('SQLCODE : ' || SQLCODE);

END;

/*sample output*/

SQLERRM : ORA-01403: no data found

SQLCODE : 100

DROP TABLE test_tb;


PRAGMA EXCEPTION_INIT

*********************

Using this you can associate a named exception with a particular oracle error.

This gives you the ability to trap this error specifically, rather than via an OTHERS handler.

Syntax:

PRAGMA EXCEPTION_INIT(exception_name, oracle_error_number);

DECLARE

v_result NUMBER;

PRAGMA EXCEPTION_INIT(Invalid, -1476);

BEGIN

SELECT 453 / 0 INTO v_result FROM dual;

dbms_output.put_line('Result : ' || v_result);

EXCEPTION

WHEN INVALID THEN

dbms_output.put_line('Invalid Exception');

END;

RAISE_APPLICATION_ERROR
************************

You can use this built-in function to create your own error messages, which can be more
descriptive than named exceptions.

Error Number :

Oracle Error Range : From -00000 to -19999

User Error Range : From -20000 to -20999

DECLARE

v_gender CHAR := '&gender';

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE_APPLICATION_ERROR(-20003, 'Enter valid gender');

END IF;

dbms_output.put_line('Gender : ' || v_gender);

END;

Posted 21st October 2014 by Unknown

1 View comments
RajmohanMarch 13, 2018 at 6:49 AM

How to get the two table data without using Joins and sub query,union?

Reply

OCT

Package

1. You can groups logical related subprogram (procedures and functions)

2. It consist of two parts

I) specification

II) Body

3. It allows the oracle server to read multiple object in to a memory once

4. You can declare global variable,cursor, user define exeption

5. Overloading

6. we can't create anonyms block inside the package

create table err_log(sno NUMBER, u_name VARCHAR2(30), error_msg CLOB, hap_tm


TIMESTAMP);

select * from err_log;


--stand alone procedure

CREATE OR REPLACE PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id


%TYPE) IS

v_salary employees.salary%TYPE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT salary,

first_name

INTO v_salary,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line('Salary of ' || v_first_name || ' is ' || v_salary);

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);
commit;

END emp_sal_sp;

BEGIN

-- Call the procedure

emp_sal_sp(p_employee_id => :p_employee_id);

END;

CREATE OR REPLACE PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id


%TYPE) IS

v_hire_date DATE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT hire_date,

first_name

INTO v_hire_date,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line(v_first_name || ' hired on ' || to_char(v_hire_date,'month ddth,


yyyy'));

EXCEPTION

WHEN OTHERS THEN


v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_hdt_sp;

BEGIN

-- Call the procedure

emp_hdt_sp(p_employee_id => :p_employee_id);

END;

create or replace function sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER

IS

v_c NUMBER;

BEGIN

v_c := p_a + p_b;

RETURN v_c;
END;

--Specification Part

CREATE OR REPLACE PACKAGE emp_pkg

IS

PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id%TYPE);

PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id%TYPE);

FUNCTION sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER;

END emp_pkg ;

--Body Part

CREATE OR REPLACE PACKAGE BODY emp_pkg

IS

PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id%TYPE) IS

v_salary employees.salary%TYPE;
v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT salary,

first_name

INTO v_salary,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line('Salary of ' || v_first_name || ' is ' || v_salary);

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_sal_sp;

PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id%TYPE) IS

v_hire_date DATE;
v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT hire_date,

first_name

INTO v_hire_date,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line(v_first_name || ' hired on ' || to_char(v_hire_date,'month ddth,


yyyy'));

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_hdt_sp;

FUNCTION sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER

IS
v_c NUMBER;

BEGIN

v_c := p_a + p_b;

RETURN v_c;

END;

END emp_pkg;

A package specification can exist without a package body, but

a package body can't exist without a package specification.

--Executing procedure inside the package

BEGIN

emp_pkg.emp_sal_sp(120);

END;

--Executing function inside the package

SELECT emp_pkg.sum_fn(23,567) FROM dual;

-- You can declare global variable,cursor, user define exeption


create or replace package all_detail

as

PROCEDURE emp2sal (a IN NUMBER);

PROCEDURE emp2exep (a IN NUMBER);

FUNCTION add2num (a IN NUMBER, b IN NUMBER)

RETURN NUMBER;

c NUMBER(8); --global declaration

abort_ex EXCEPTION; --global exception declaration

CURSOR emp_rec --global cursor declaration

IS

SELECT first_name, salary, hire_date, department_id

FROM employees;

End all_detail;

create or replace package body all_detail

as

PROCEDURE emp2sal (a IN NUMBER)


AS

BEGIN

SELECT salary

INTO c

FROM Employees

WHERE Employee_id = a;

Dbms_output.put_line('Salary of Employee ' || a || ' is ' || c);

EXCEPTION

WHEN no_data_found THEN

Dbms_output.put_line('Please enter valid id');

END emp2sal;

PROCEDURE emp2exep (a IN NUMBER)

AS

BEGIN

SELECT Round(Months_between(sysdate,hire_date)/12)

INTO c

FROM Employees

WHERE Employee_id = a;

Dbms_output.put_line( c || ' Years');

EXCEPTION
WHEN no_data_found THEN

Dbms_output.put_line('Please enter valid id');

END emp2exep;

FUNCTION add2num (a IN NUMBER, b IN NUMBER)

RETURN NUMBER

AS

BEGIN

c := a+b;

RETURN C;

END;

End all_detail;

/*Declaring a Bodiless Package */

CREATE OR REPLACE PACKAGE global_constant

IS

mile_2_kilo CONSTANT NUMBER := 1.6093;

kilo_2_mile CONSTANT NUMBER := 0.6214;

yard_2_meter CONSTANT NUMBER := 0.9144;


meter_2_yard CONSTANT NUMBER := 1.0936;

END global_constant;

BEGIN

DBMS_OUTPUT.PUT_LINE('20 miles = ' || 20*global_constant.mile_2_kilo||' km');

END;

/*Forward Declaration in package */

DECLARE

PROCEDURE P2; -- forward declaration

PROCEDURE P3;

PROCEDURE P1 IS

BEGIN

dbms_output.put_line('From procedure p1');

p2;

END P1;

PROCEDURE P2 IS

BEGIN

dbms_output.put_line('From procedure p2');

p3;
END P2;

PROCEDURE P3 IS

BEGIN

dbms_output.put_line('From procedure p3');

END P3;

BEGIN

p1;

END;

sample output:

From procedure p1

From procedure p2

From procedure p3

Drop package package_name;

Drop package body package_name;

SELECT text FROM user_source u

WHERE u.name = 'EMP_PKG';


Interview Questions:

What is package?

Advantage of package

Is it possible to create package body with out package specification?

what is package overloading?

what is forward declaration in package?

which data dictionary table contain source code of package?

How to declare global variable, exception and cursor?

How to execute procedure and function inside the package?

Posted 4th October 2014 by Unknown

0 Add a comment

OCT

%TYPE and %ROWTYPE

--%type is used to fetch the data type of the particular column


create table product_details

p_id NUMBER(3),

p_nm VARCHAR2(30),

p_qty NUMBER(8),

order_dt DATE

);

BEGIN

INSERT INTO product_details VALUES(100,'Name0',400,'23-Mar-13');

INSERT INTO product_details VALUES(101,'Name1',600,'26-Apr-13');

INSERT INTO product_details VALUES(102,'Name2',800,'27-Jan-12');

INSERT INTO product_details VALUES(103,'Name3',300,'23-Jul-11');

INSERT INTO product_details VALUES(104,'Name4',200,'22-Aug-11');

INSERT INTO product_details VALUES(105,'Name5',500,'25-Oct-12');

commit;

END;

SELECT * FROM product_details;

------------------------------------

P_ID P_NM P_QTY ORDER_DT


------------------------------------

100 Name0 400 03/23/2013

101 Name1 600 04/26/2013

102 Name2 800 01/27/2012

103 Name3 300 07/23/2011

104 Name4 200 08/22/2011

105 Name5 500 10/25/2012

------------------------------------

DECLARE

v_name VARCHAR2(4);

BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 100;

dbms_output.put_line('Product Name : ' || v_name);

--error numeric or value error

END;

DECLARE

v_name VARCHAR2(5);
BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 100;

dbms_output.put_line('Product Name : ' || v_name);

END;

ALTER TABLE product_details

MODIFY p_nm VARCHAR2(15);

INSERT INTO product_details

VALUES

(106,

'name6',

700,

'26-Dec-12');

commit;

106 name6 700 12/26/2012


DECLARE

v_name VARCHAR2(5);

BEGIN

SELECT p_nm INTO v_name

FROM product_details

WHERE p_id = 106;

dbms_output.put_line('Product Name : ' || v_name);

--error

END;

DECLARE

v_name product_details.p_nm%TYPE;

BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 106;

dbms_output.put_line('Product Name : ' || v_name);

END;
/

DROP TABLE product_details;

DECLARE

dep_id departments.department_id%TYPE;

dep_name departments.department_name%TYPE;

dep_man_id departments.manager_id%TYPE;

dep_loc_id departments.location_id%TYPE;

BEGIN

SELECT department_id,

department_name,

manager_id,

location_id

INTO dep_id,

dep_name,

dep_man_id,

dep_loc_id

FROM departments

WHERE department_id = 10;


dbms_output.put_line('Department_id : ' || dep_id);

dbms_output.put_line('Department_name : ' || dep_name);

dbms_output.put_line('Manager_id : ' || dep_man_id);

dbms_output.put_line('Location_id : ' || dep_loc_id);

END;

--%rowtype is used to fetch the data type of all the column

--Insted of using %type if we use %rowtype means we can reduce the no of variables that we
declare

DECLARE

dep_detail departments%ROWTYPE;

BEGIN

SELECT *

INTO dep_detail

FROM departments

WHERE department_id = 10;

dbms_output.put_line('Department_id : ' || dep_detail.department_id);


dbms_output.put_line('Department_name : ' || dep_detail.department_name);

dbms_output.put_line('Manager_id : ' || dep_detail.manager_id);

dbms_output.put_line('Location_id : ' || dep_detail.location_id);

END;

DROP TABLE dept_details;

CREATE TABLE dept_details

dept_id number(3) ,

dept_name varchar2(30),

dept_manager_name varchar2(30)

);

insert into dept_details values(10,'dept1','manager_name1');

insert into dept_details values(20,'dept2','manager_name2');

SELECT * FROM dept_details;

-------------------------------------------------------

| DEPT_ID | DEPT_NAME | DEPT_MANAGER_NAME |


+------------+-----------------------+-----------------

| 10 | dept1 | manager_name1 |

| 20 | dept2 | manager_name2 |

------------+-----------------------+------------------

DECLARE

all_data dept_details%ROWTYPE;

BEGIN

all_data.dept_id := 100;

all_data.dept_name := 'Admin';

all_data.dept_manager_name := 'John';

UPDATE dept_details

SET ROW = all_data

WHERE dept_id = 10;

dbms_output.put_line(SQL%ROWCOUNT || ' Row(s) get updated');

END;

1 Row(s) get updated


select * from dept_details;

---------------------------------------------------

| DEPT_ID | DEPT_NAME | DEPT_MANAGER_NAME|

---------------------------------------------------

| 100 | Admin | John |

| 20 | dept2 | manager_name2 |

---------------------------------------------------

Interview Question :

1. What is the use of %TYPE?

2. What is the use of %ROWTYPE?

3. Difference between %TYPE and %ROWTYPE?

Posted 2nd October 2014 by Unknown

0 Add a comment
SEP

29

BULK Exceptions

/************************************************************************

* Handling Exceptions in Bulk Operations *

* Documented on 29-SEP-14 04.35.35.980894 PM +05:30 *

* Document By : Murugappan Annamalai *

* Reference : http://www.dba-oracle.com/plsql/t_plsql_exceptions.htm *

************************************************************************/

CREATE TABLE bulk_tb (ran_num NUMBER NOT NULL);

--inserting data using bulk collect

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP
v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

commit;

END;

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

200

TRUNCATE TABLE bulk_tb;

sample2.sql --without exception part

DECLARE
TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

commit;

END;

/*

Error Message :

ORA-01400: cannot insert NULL into ("HR"."bulk_tb"."ran_num")

ORA-06512: at line 15

*/
sample2.sql --with exception part

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

BEGIN

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

COMMIT;

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('Error while inserting bulk record '||SQLERRM);


END;

END;

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

99

SQL%BULK_EXCEPTIONS(i).ERROR_INDEX

Holds the iteration (not the subscript) of the original FORALL statement that raised the
exception.

In sparsely populated collections,

the exception row must be found by looping through the original collection the correct
number of times.

SQL%BULK_EXCEPTIONS(i).ERROR_CODE

Holds the exceptions error code.


The total number of exceptions can be returned using the collections COUNT method,

which returns zero if no exceptions were raised. The save_exceptions.sql script,

a modified version of the handled_exception.sql script, demonstrates this functionality.

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

v_ex_count NUMBER(4);

abort_ex EXCEPTION;

PRAGMA EXCEPTION_INIT(abort_ex, -24381);

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

v_dat(150) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

EXECUTE IMMEDIATE 'TRUNCATE TABLE bulk_tb';


BEGIN

FORALL i IN v_dat.FIRST..v_dat.LAST SAVE EXCEPTIONS

INSERT INTO bulk_tb VALUES(v_dat(i));

COMMIT;

EXCEPTION

WHEN abort_ex THEN

v_ex_count := SQL%BULK_EXCEPTIONS.COUNT;

FOR i IN 1..v_ex_count LOOP

dbms_output.put_line('Error: ' || i ||' Array Index: ' || SQL


%BULK_EXCEPTIONS(i).error_index ||

' Message: ' || SQLERRM(SQL%BULK_EXCEPTIONS(i).ERROR_CODE));

END LOOP;

END;

END;

/*

Sample output:

Error: 1 Array Index: 100 Message: -1400: non-ORACLE exception

Error: 2 Array Index: 150 Message: -1400: non-ORACLE exception

*/
SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

198

SAVE EXCEPTIONS clause being removed, in the above script now traps a different error number.

The output from this script is listed below.

/*

Sample output:

Error: 1 Array Index: 100 Message: -1400: non-ORACLE exception

*/

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

99
SELECT COUNT(*) FROM bulk_tb;

DROP TABLE bulk_tb;

Posted 29th September 2014 by Unknown

0 Add a comment

SEP

29

Cursor - FOR UPDATE

/************************************************************************

* FOR UPDATE clause in oracle *

* Document By : Murugappan Annamalai *

************************************************************************/

create table prod_details(p_id VARCHAR2(30), P_name VARCHAR2(30));


BEGIN

--Inserting data into prod_details table

FOR i IN 1..50 LOOP

INSERT INTO prod_details VALUES(i,'pname'||i);

END LOOP;

commit;

END;

SELECT * FROM prod_details;

DECLARE

CURSOR PROD_DTLS_C IS

SELECT * FROM PROD_DETAILS T1 FOR UPDATE OF P_ID;

V_PID PROD_DETAILS.P_ID%TYPE;

V_PRDNAME PROD_DETAILS.P_NAME%TYPE;

BEGIN

OPEN PROD_DTLS_C;

LOOP
FETCH PROD_DTLS_C INTO V_PID, V_PRDNAME;

IF PROD_DTLS_C%NOTFOUND THEN

EXIT;

ELSE

UPDATE PROD_DETAILS P

SET P.P_ID = LPAD(P_ID, 10, 0)

WHERE CURRENT OF PROD_DTLS_C;

END IF;

END LOOP;

CLOSE PROD_DTLS_C;

COMMIT;

END;

select * from PROD_DETAILS;

TRUNCATE TABLE prod_details;

BEGIN

--Inserting data into prod_details table

FOR i IN 1..50 LOOP


INSERT INTO prod_details VALUES(i,'pname'||i);

END LOOP;

commit;

END;

DECLARE

CURSOR PROD_DTLS_C IS

SELECT * FROM PROD_DETAILS T1 FOR UPDATE OF P_ID;

V_PID PROD_DETAILS.P_ID%TYPE;

V_PRDNAME PROD_DETAILS.P_NAME%TYPE;

BEGIN

OPEN PROD_DTLS_C;

LOOP

FETCH PROD_DTLS_C INTO V_PID, V_PRDNAME;

IF PROD_DTLS_C%NOTFOUND THEN

EXIT;

ELSE
UPDATE PROD_DETAILS P

SET P.P_ID = LPAD(P_ID, 10, 0)

WHERE CURRENT OF PROD_DTLS_C;

END IF;

COMMIT;

END LOOP;

CLOSE PROD_DTLS_C;

--COMMIT;

END;

select * from PROD_DETAILS;

Posted 29th September 2014 by Unknown

0 Add a comment

MAY

28

Escape Sequence in Oracle

Escape special characters when writing SQL queries


--to include single '

SELECT 'Steven's salary is more than 50k INR' AS "SAL_DETAILS"

FROM Dual;

ORA-01756 : quoted string not properly terminated

SELECT 'Steven''s salary is more than 50k INR' AS "SAL_DETAILS"

FROM Dual;

SAL_DETAILS

---------------------------------------

Steven's salary is more than 50k INR

--to include double '

SELECT 'You can print double quot ('''') in oracle' "Info"

FROM Dual;

Info
---------------------------------------

You can print double quot ('') in oracle

SELECT q'[some test ' some test ' some text ']' AS "In 10g"

FROM dual;

In 10g

------------------------------------

some test ' some test ' some text '

--Escape wild card characters ( _ and % )

The LIKE keyword allows for string searches.

The '_' wild card character is used to match exactly one character

While '%' is used to match zero or more occurrences of any characters.

These characters can be escaped in SQL as follows.

WITH mail_ids AS

SELECT 'an.murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an_murugappan@gmail.com' mail FROM Dual


UNION

SELECT 'an%murugappan@gmail.com' mail FROM Dual

SELECT * FROM mail_ids

WHERE mail LIKE '__$_%' ESCAPE '$';

mail

----------------------------------

an_murugappan@gmail.com

WITH mail_ids AS

SELECT 'an.murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an_murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an%murugappan@gmail.com' mail FROM Dual

SELECT * FROM mail_ids

WHERE mail LIKE '__/%%' ESCAPE '/';

mail

----------------------------------
an%murugappan@gmail.com

Escape ampersand (&) characters in SQL*Plus

SQL> select '&a' FROM dual;

'23'

----

23

SQL> SET ESCAPE '\'

SQL> select '\&a' FROM dual;

'&A'

----

&a

SQL> SET SCAN OFF;

SQL> select '&a' FROM dual;

'&A'

----

&a
SQL> SET SCAN ON;

SQL> select '&a' FROM dual;

'45'

----

45

Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Data Manipulation Language

Data Manipulation Language (DML) statements are used for managing data within schema
objects. Some examples:

INSERT - insert data into a table

UPDATE - updates existing data within a table

DELETE - deletes all records from a table, the space for the records remain
MERGE - UPSERT operation (insert or update)

CREATE TABLE prod_details

prod_id NUMBER(4) ,

prod_name VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

Deliver_dt DATE DEFAULT SYSDATE+3 ,

comments VARCHAR2(300)

);

SELECT * FROM prod_details;

no_data_found

INSERT

INSERT INTO prod_details(prod_id,prod_name,order_dt,deliver_dt,comments)

VALUES(100,'Apple iphone 5s','21-May-14','24-May-14','Color : Black');

SELECT * FROM prod_details;

---------------------------------------------------------------------------
PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

---------------------------------------------------------------------------

--Inserting records with out mentioning column name

INSERT INTO prod_details

VALUES(101,'Samsung Galaxy III','20-Aug-14','23-Aug-14','Color : White');

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

---------------------------------------------------------------------------

--Inserting selective number of values

INSERT INTO prod_details

VALUES(103,'Moto X','11-May-14','13-May-14');

ORA-00947 : not enough values


--While inserting selective number of values mentioning column name is compulsory.

INSERT INTO prod_details (prod_id,prod_name,order_dt,deliver_dt)

VALUES(103,'Moto X','11-May-14','13-May-14');

SELECT * FROM prod_details;

--------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

--------------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

--------------------------------------------------------------------------------

--Inserting NULL value.

--If you want to insert NULL value you can ignore that column at the time of inserting

--or we can use NULL keyword to insert NULL.

INSERT INTO prod_details

VALUES(104,'Moto G','19-May-14','22-May-14',NULL);
SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Noto G 5/19/2014 5/22/2014

---------------------------------------------------------------------------

--if you are not providing values for order_dt and deliver_dt column default value can be taken.

INSERT INTO prod_details(prod_id,prod_name,comments)

VALUES(105,'Nokia Lumis 720p','Color : Red');

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

----------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014


104 Moto G 5/19/2014 5/22/2014

105 Nokia Lumis 720p 5/26/2014 5/29/2014 Color : Red

---------------------------------------------------------------------------

--Inserting data by using sub query

CREATE TABLE test_tab (id NUMBER, Name VARCHAR2(30));

INSERT INTO test_tab VALUES(1,'Name1');

INSERT INTO test_tab VALUES(2,'Name2');

INSERT INTO test_tab VALUES(3,'Name3');

SELECT COUNT(*) FROM test_tab;

COUNT(*)

-------

--creating table by using sub query (with out data)

CREATE TABLE ins_chk


SELECT * FROM test_tab

WHERE id = 900;

SELECT COUNT(*) FROM ins_chk;

COUNT(*)

-------

--Inserting data by using sub query

--copying data from test_tab to ins_chk

INSERT INTO ins_chk (SELECT * FROM test_tab);

3 rows inserted in 0.047 seconds.

SELECT COUNT(*) FROM ins_chk;

COUNT(*)

-------

3
DROP TABLE test_tab;

DROP TABLE ins_chk;

UPDATE

Syntax :

UPDATE table_name

SET column1_name = column1_value,

column2_name = column2_value,

column2_name = column3_value,

columnn_name = columnn_value

WHERE condition(s);

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

----------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014


104 Moto G 5/19/2014 5/22/2014

105 Nokia Lumis 720p 5/26/2014 5/29/2014 Color : Red

---------------------------------------------------------------------------

UPDATE prod_details ps

SET ps.prod_name = 'iphone 5s'

WHERE ps.prod_id = 100;

1 row updated in 0.031 seconds

SELECT *

FROM prod_details ps

WHERE ps.prod_id = 100;

--------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

--------------------------------------------------------------------

100 iphone 5s 5/21/2014 5/24/2014 Color : Black

--------------------------------------------------------------------

--update statement with out condition

--If you try to execute update statement without condition it'll update all the records inside the
table.

UPDATE prod_details ps

SET ps.comments = 'None';


5 row updated in 0.031 seconds

SELECT *

FROM prod_details ps;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 None

101 Samsung Galaxy III 8/20/2014 8/23/2014 None

103 Moto X 5/11/2014 5/24/2014 None

104 Moto G 5/19/2014 5/22/2014 None

105 Nokia Lumis 720p 5/26/2014 5/29/2014 None

----------------------------------------------------------------------

--if your update text contain ' means you can use following metnod (use '')

UPDATE prod_details ps

SET ps.comments = 'Some product''s are not available'

WHERE ps.prod_id = 100;

1 row updated in 0.031 seconds


SELECT *

FROM prod_details ps

WHERE ps.prod_id = 100;

------------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

------------------------------------------------------------------------------------

100 iphone 5s 5/21/2014 5/24/2014 Some product's are not available

------------------------------------------------------------------------------------

DELETE

Syntax:

DELETE FROM table_name

WHERE condition(s);

DELETE FROM prod_details

WHERE prod_id IN (104, 105);

2 row(S) deleted in 0.032 seconds


SELECT *

FROM prod_details ps;

---------------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Some product's are not available

101 Samsung Galaxy III 8/20/2014 8/23/2014 None

103 Moto X 5/11/2014 5/24/2014 None

---------------------------------------------------------------------------------------

DELETE FROM prod_details;

3 row(s) deleted in 0.062 seconds.

SELECT * FROM prod_details;

no rows selected.

DROP TABLE prod_details;

MERGE = Insert + Update

-- will update soon.


Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Data Define Language

Data Definition Language (DDL) statements are used to define the database structure or schema.

Some examples:

CREATE - to create objects in the database.

ALTER - alters the structure of the database.

ADD

RENAME

MODIFY

DROP

DROP - delete objects from the database

TRUNCATE - remove all records from a table,

including all spaces allocated for the records are removed.

COMMENT - add comments to the data dictionary.


RENAME - rename an object.

Creating Table

--------------------------------------------------------------------------

Data Types Size Default Size Explanation

--------------------------------------------------------------------------

NUMBER(P,S) P: 1 to 38 we can store number between 0-9

S: -84 to 127

VARCHAR2 4000 Bytes we can store 0-9, a-z, A-Z and special characters

CHAR 2000 Bytes 1

DATE 7 Used to store Date

TIMESTAMP Includes year, month, day, hour, minute, and seconds.

LONG 2 GB Only one long column is allowed in a table.

We can't use this column in ORDER BY clause.

CLOB 4 GB Character Large Object

BLOB Binary Larger Object

--------------------------------------------------------------------------

CREATE

ALTER : ADD RENAME MODIFY DROP RENAME

RENAME

DROP

TRUNCATE
--creating table

CREATE TABLE friends_details_tb

Name VARCHAR2(30) ,

Phone NUMBER(10) ,

Gender CHAR ,

dob DATE ,

other_details LONG ,

make_dtm TIMESTAMP

);

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)
-----------------------------

--maximum you can keep 255 columns in a table

ALTER : Colum level operations

ADD RENAME MODIFY DROP

ADD : Used to add a column after the table hase been created

ALTER TABLE friends_details_tb

ADD email VARCHAR2(30);

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG
MAKE_DTM TIMESTAMP(6)

EMAIL VARCHAR2(30)

-----------------------------

--adding multiple columns by using single ALTER statement

SYNTAX

ALTER TABLE friends_details_tb

ADD (

column_1 Data_type(size),

column_2 Data_type(size),

column_3 Data_type(size),

column_4 Data_type(size)

);

RENAME : Used to Rename a column

ALTER TABLE friends_details_tb

RENAME COLUMN email TO email_id;

DESC friends_details_tb;
-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

MODIFY : Used to change the data type or size of the data type.

ALTER TABLE friends_details_tb

MODIFY other_details CLOB;

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------
NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS CLOB

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

--Modifying multiple columns at a time

ALTER TABLE friends_details_tb

MODIFY ( column_name_1 old_datatype(new_size),

column_name_2 new_datatype(old_size),

column_name_3 new_datatype(new_size)

);

DROP : Used to drop the column after the table has been created.

ALTER TABLE friends_details_tb

DROP COLUMN other_details;

DESC friends_details_tb;
-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

RENAME : Used to Rename a particular table.

SYNTAX

RENAME old_table_name TO new_table_name;

RENAME friends_details_tb TO fnd_det;

DESCRIBE fnd_det;

-----------------------------

NAME TYPE
-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

TRUNCATE : Used to remove the entire content of the table (not a structure)

SYNTAX

TRUNCATE TABLE table_name;

TRUNCATE TABLE fnd_det;

DROP : Used to drop the tabel (Data + stucture of the table get removed from the database )

DROP TABLE fnd_det;

*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Statements in Oracle

Data Definition Language (DDL)

DDL statements are used to define the database structure or schema. Some examples:

CREATE - to create objects in the database

ALTER - alters the structure of the database

ADD

RENAME

MODIFY

DROP

DROP - delete objects from the database

TRUNCATE - remove all records from a table,

including all spaces allocated for the records are removed

RENAME - rename an object


Data Manipulation Language (DML)

DML statements are used for managing data within schema objects. Some examples:

INSERT - insert data into a table

UPDATE - updates existing data within a table

DELETE - deletes all records from a table, the space for the records remain

MERGE - UPSERT operation (insert or update)

Data Control Language (DCL)

DCL statements. Some examples:

GRANT - gives users access privileges to database

REVOKE - withdraw access privileges given with the GRANT command

Transaction Control (TCL)

TCL statements are used to manage the changes made by DML statements. It allows
statements to be grouped together into logical transactions.

COMMIT - save work done

SAVEPOINT - identify a point in a transaction to which you can later roll back

ROLLBACK - restore database to original since the last COMMIT


Posted 28th May 2014 by Unknown

0 Add a comment

MAY

19

DECODE and CASE statement

CREATE TABLE students (

roll_no NUMBER(4) ,

Name VARCHAR2(30) ,

dept_cd VARCHAR2(20) ,

total_marks NUMBER(3)

);

BEGIN

INSERT INTO students VALUES (2000,'Rahul','CSE',480);

INSERT INTO students VALUES (2001,'Bala','IT', 390);

INSERT INTO students VALUES (2002,'Ramesh','CSE',250);

INSERT INTO students VALUES (2003,'Karthi','EEE',185);


INSERT INTO students VALUES (2004,'Ravi','IT',345);

END;

SELECT * FROM students;

DECODE

Decode is a function. Its a Oracle one.

Works like IF-THEN-ELSE.

You can use DECODE only in SELECT clause.

In DECODE you can include 255 things include Exep, search , result and default value.

Example

SELECT roll_no,

NAME,

dept_cd,

DECODE(dept_cd,

'CSE',

'Computer Science and Engineering',

'IT',

'Information Technology',

'Default Value') AS "DEPARTMENT NAME"

FROM students;
Sample Output

------------------------------------------------------------

ROLL_NO NAME DEPT_CD DEPARTMENT NAME

------------------------------------------------------------

2000 Rahul CSE Computer Science and Engineering

2001 Bala IT Information Technology

2002 Ramesh CSE Computer Science and Engineering

2003 Karthi EEE Default Value

2004 Ravi IT Information Technology

------------------------------------------------------------

CASE

CASE is an expression. Its a ANSI standard.

Compare to DECODE case will be more faster.

Example

SELECT roll_no,

NAME,

dept_cd,

total_marks,

CASE

WHEN total_marks > 500 THEN

'A Grade'
WHEN total_marks > 400 THEN

'B Grade'

WHEN total_marks > 300 THEN

'C Grade'

ELSE

'U Grade'

END AS "GRADE"

FROM students;

-----------------------------------------------

ROLL_NO NAME DEPT_CD TOTAL_MARKS GRADE

-----------------------------------------------

2000 Rahul CSE 480 B Grade

2001 Bala IT 390 C Grade

2002 Ramesh CSE 250 U Grade

2003 Karthi EEE 185 U Grade

2004 Ravi IT 345 C Grade

-----------------------------------------------

Interview Questions:

What is DECODE?

What is CASE?

Difference between CASE and DECODE? Which one is faster?


Posted 19th May 2014 by Unknown

0 Add a comment

MAY

19

Sub Query

Query with in another query

1. Single Row sub query

2. Multi row Sub query

select * from employees;

Want to fetch the person Who are all getting salary more than Neena's salary ?

Neena's Salary : 17000

Select First_name, salary

From Employees

Where salary > 17000;


--change in Neena's salary won't work for the above query.

Select salary From Employees

Where First_name = 'Neena';

Sub Query :

Select First_name, salary

From Employees

Where salary > (

Select salary From Employees

Where First_name = 'Neena'

);

Select * from employees;

Select salary From Employees

Where First_name = 'Alexander';

Sub Query Returns one value it is called as Single row sub query
Sub Query Returns more than one value it is called as Multi row sub query

Single row sub query operators :

> < >= <= = <>

Multiple Row Sub query operators :

IN ALL ANY

Who are all getting salary more than the average salary?

Select

First_name,

Salary

From

Employees

WHERE

Salary > (

SELECT Round(avg(salary),0)

FROM Employees

);
Multiple Row Sub query (In ANY ALL)

Select First_name,Department_id, salary

From Employees

Where salary in(

Select Salary From Employees

Where First_name = 'Alexander'

);

Any : Minimum Value will be taken (3100)

Select First_name,Department_id, salary

From Employees

Where salary > ANY(

Select Salary From Employees

Where First_name = 'Alexander'

);

All : Maximum Value will be taken (9000)

Select First_name,Department_id, salary

From Employees

Where salary > All(

Select Salary From Employees


Where First_name = 'Alexander'

);

We can use sub query in all the classes except Group by and order by class.

Select

From

Where

-----------Group by

having

-----------Order by

SELECT

( Select Count(*) from Employees Where Department_id = 90 )Executive,

( Select Count(*) from Employees Where Department_id = 60 ) IT,

( Select Count(*) from Employees Where Department_id = 10 ) Administration,

( Select Count(*) from Employees Where Department_id = 100) Finance

FROM

Dual;

Select Min(salary) From Employees;

Select Min(salary) from


(

Select * from Employees

Where Department_id = 60

);

What is INLINE VIEW?

If u use sub query in From it is call it is as INLINE VIEW.

Intermediate result set

Correlated sub query

SELECT employee_number, name

FROM employees Bob

WHERE salary > (

SELECT AVG(salary)

FROM employees

WHERE department = Bob.department

);

Posted 19th May 2014 by Unknown

0 Add a comment
Loading

Dynamic Views theme. Powered by Blogger.

Oracle sql & Pl/sql

search

Home Sql and pl/sql Sql Interview Questions

JUL

20

INLINE view in Oracle with 12c New Features

Named sub Query in FROM clause is call it as INLINE VIEW.

Oracle process a inline view faster than sub query

Inline View in Oracle

--Query to display all the employees who are all getting salary more than their department
average salary

SELECT First_name

, last_name

, salary

, department_id
FROM employees a , ( SELECT b.department_id

, AVG(b.salary) avg_sal

FROM employees b

GROUP BY b.department_id

)b

WHERE a.department_id = b.department_id

AND a.salary > b.avg_salary;

Display all the customer who have placed more number of orders by using INLINE view

CREATE TABLE customer_order_det_tb

( custm_id NUMBER ,

custm_nm VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

ttl_amt NUMBER(7,2)

);

BEGIN

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '11-Jul-15' , 45000.00);

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '14-Jul-15' , 27000.00);

INSERT INTO customer_order_det_tb VALUES(101, 'Raja' , '13-Jul-15' , 17000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 34000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 38000.00);

COMMIT;
END;

SELECT c.*

FROM customer_order_det_tb c;

--------------------------------------------

custm_id custm_nm order_dt ttl_amt

--------------------------------------------

100 Murugappan 7/11/2015 45000.00

100 Murugappan 7/14/2015 27000.00

101 Raja 7/13/2015 17000.00

102 Ramesh 7/15/2015 34000.00

102 Ramesh 7/15/2015 38000.00

--------------------------------------------

--Writing a Quer to display all the customer who have placed maximum number of order

--Query #1 for inline view

SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC;


--------------------------------

custm_id custm_nm total_odr

--------------------------------

100 Murugappan 2

102 Ramesh 2

101 Raja 1

--------------------------------

--Query #2 for inline view

SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm;

----------

total_odr

----------

----------

Inline view to find all the customers who have placed maximum number of orders

/****************************************

Syntax
SELECT * FROM <query1> x, <query2> y

WHERE contition;

****************************************/

SELECT query1.* FROM

( SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC

) query1,

( SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm

) query2

WHERE query1.total_odr = query2.total_odr;

-------------------------------

custm_id custm_nm total_odr

-------------------------------

100 Murugappan 2

102 Ramesh 2

-------------------------------

DROP TABLE customer_order_det_tb;


--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT

SELECT first_name, salary

FROM ( SELECT first_name, salary

FROM employees e

WHERE job_id NOT IN ('SALESMAN','PRESIDENT')

ORDER BY salary DESC

WHERE ROWNUM < 4;

New Oracle 12c Inline view Syntax

LATERAL clause for In-line views

Allows for columns in the inline view to be accessed!!

Example :

--in 11g

SELECT * FROM employees e, (

SELECT *

FROM departments d

WHERE e.department_id = d.department_id);


ORA-0090: "E"."DEPARTMENT_ID": Invalid Identifier

--in 12c

SELECT * FROM employees e, LATERAL(

SELECT *

FROM departments d

WHERE e.department_id = d.department_id

);

--in 11g

WITH t

AS

( SELECT LEVEL a

FROM dual

CONNECT BY LEVEL <= 30)

SELECT *

FROM t, (SELECT *

FROM employees

WHERE department_id = t.a

);

ORA-00904: "T"."A": invalid Identifier


--in 12c

WITH t

AS

(SELECT LEVEL a FROM dual CONNECT BY LEVEL <= 30)

SELECT * FROM t,

LATERAL(SELECT *

FROM employees

WHERE department_id = t.a);

Hope you have enjoyed this little article

Feed backs are always Welcome :) (:

Posted 20th July 2015 by Unknown

0 Add a comment

JAN

23

Salary Related Questions in Oracle

--creating table
CREATE TABLE employee_data

eid NUMBER(4),

ename VARCHAR2(30),

depno NUMBER(3),

salary NUMBER(8)

);

BEGIN

--Inserting records

INSERT INTO employee_data VALUES(1000,'Name01',90,30000);

INSERT INTO employee_data VALUES(1001,'Name02',90,6000);

INSERT INTO employee_data VALUES(1002,'Name03',90,23000);

INSERT INTO employee_data VALUES(1003,'Name04',60,35000);

INSERT INTO employee_data VALUES(1004,'Name05',60,60000);

INSERT INTO employee_data VALUES(1005,'Name06',60,30000);

INSERT INTO employee_data VALUES(1006,'Name07',80,36000);

INSERT INTO employee_data VALUES(1007,'Name08',80,29000);

INSERT INTO employee_data VALUES(1008,'Name09',80,37000);

INSERT INTO employee_data VALUES(1009,'Name10',80,41000);

COMMIT;

END;
/

SELECT * FROM employee_data

ORDER BY salary DESC;

--query to find maximum salary from employee_data table

SELECT MAX(salary) FROM employee_data;

--query to find minimum salary from employee_data table

SELECT MIN(salary) FROM employee_data;

--query to find second maximum salary from employee_data table

SELECT MAX(salary)

FROM employee_data

WHERE salary NOT IN (SELECT MAX(salary)

FROM employee_data);

--query to select 5th maximum salary

SELECT MIN(salary)

FROM (SELECT salary


FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= 5);

--query to select nth maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= &n);

--query to select all the details of the employee whose getting nth maximum salary

SELECT *

FROM (SELECT emp.*,

rownum rn

FROM (SELECT *

FROM employee_data

ORDER BY salary DESC) emp)

WHERE rn = 9;
--same query using row_numbr( ) function

SELECT *

FROM (SELECT emp.*,

row_number() over(ORDER BY salary) rank

FROM employee_data emp)

WHERE rank = 9;

--same query using rank( ) function

SELECT *

FROM (SELECT emp.*,

rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--same query using dense_rank( ) function

SELECT *

FROM (SELECT emp.*,

dense_rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;
--query to display display maximum salary in all the department

SELECT e.depno "Department id",

MAX(salary) "Maximum Salary"

FROM employee_data e

GROUP BY e.depno;

--query to display all the employees who are all getting salary more than average salary of the
company

SELECT e.* FROM employee_data e

WHERE salary > (SELECT AVG(salary) FROM employee_data);

--query to display all the employees who are all getting salary more than their department
average salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE department_id = OUT.department_id);


--query to display all the employees who are all getting salary more than their manager salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE employee_id = OUT.manager_id);

Documented By : Murugappan Annamalai

Posted on : 23-Jan-15 16:34:00 IST.

Hope you have enjoyed this little article

Feed backs are always welcome :)

Posted 23rd January 2015 by Unknown

7 View comments

JAN
22

Why prefer COALESCE over NVL

Documented By : Nimish Garg

I prefer using "COALESCE" over "NVL" is some of the scenarios. Last week One of my friend
asked me what is the advantage of using "COALESCE" where we can simply use "NVL". I simply
gave him the reply from Oracle Docs i.e. NVL lets you replace null (returned as a blank) with a
string in the results of a query and COALESCE returns the first non-null expr in the expression list.
Oracle Database uses short-circuit evaluation with "COALESCE".

He replied that he knows the difference, he knows that "COALESCE" can take multiple arguments
and so on. He was more interested in understanding "short-circuit evaluation" of "COALESCE"
and the scenarios where I prefer using "COALESCE" over "NVL".

To make him understand I created following function which takes One second in every execution
and simply returns '--null--' and executed 2 very similar queries one with NVL and other with
COALESCE.

SQL> create or replace function f_null return varchar2

2 is

3 begin

4 dbms_lock.sleep(1);

5 return '--null--';

6 end;

7 /

Function created.
Following are the queries which I used to demonstrate that NVL evaluates both arguments even
if the second argument is not used and COALESCE uses short-circuit evaluation i.e. it only
evaluates the arguments only if they are needed.

SQL> select e.empno, e.ename ename, nvl(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--


14 rows selected.

Elapsed: 00:00:14.01

SQL> select e.empno, e.ename ename, coalesce(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--


14 rows selected.

Elapsed: 00:00:01.01

Here we can see easily that the first query with NVL took 14+ seconds, one second for each
record even if the "f_null" value was used only in one record. On the contrary as mentioned in
Oracle Documentation "COALESCE" uses its "short-circuit evaluation" and "f_null" was called
only once and so second query took only One Second. "COALESCE" is certainly use less resources
than NVL.

Posted 22nd January 2015 by Unknown

0 Add a comment

DEC

21

Constraints

It Enforce Rule On Table

We can create constraint at the time of Creating Table


1. Column Level Declaration

2. Table Level Declaration

1. We can provide own name.

Format : [part_of_project_name-table_name-column_name-constraint_type]

Example : gmind_emp_id_pk _uk _ck _f

2. system name name

Format : sys_cn

Example : SYS_C405323

We can create constraint after the table has been created

Types

Primary Key

Not allowed Null value

Not allowed you to enter duplicate value

Ex : Employee_id, Student_id
Unique Key

allowed Null value

Not allowed you to enter duplicate value

Ex : Contact_no, email

Foreign Key

It will allowed you to enter NULL and Duplicate value.

c1(pk) : 1 2 3

c2(f) : 1 1 2 3 4 Not allowed

Allowed you to enter duplicate value and null value

Not Null

It will not allowed you to enter null value

Check

You can check your own condition


Simple Table for understanding

------------------------------------

Duplicate NULL

------------------------------------

Primary Key X X

Unique Key X Allowed

Foreign Key Allowed Allowed

------------------------------------

creating table with all constraint type

Create table my_stu_details

S_id Number(2),

S_name Varchar2(30) Not Null, --SYS_Cn

s_mail Varchar2(30),

s_gender char(1),

s_did Number(3),

Constraint my_stu_sid_pk PRIMARY KEY (s_id),

constraint my_stu_mail_uk UNIQUE (s_mail) ,

Constraint my_stu_gen_ck CHECK (s_gender IN ('M', 'F', 'm', 'f')),


Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

);

DESC my_stu_details;

------------------------------------

Name Type Nullable

------------------------------------

S_ID NUMBER(2)

S_NAME VARCHAR2(30)

S_MAIL VARCHAR2(30) Y

S_GENDER CHAR(1) Y

S_DID NUMBER(3) Y

------------------------------------

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name1' , 'name1@gmail.com' , 'm' , 60 );

Select * from my_stu_details;


Validating Primary Key

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-00001: unique constraint (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (NULL, 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-01400: cannot insert NULL into (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (2 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

Validating NOT NULL Constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)


values (3 , NULL , 'name3@gmail.com' , 'F' , 80 );

ORA-01400: cannot insert NULL into ("HR"."MY_STU_DETAILS"."S_NAME")

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , 'Name3' , 'name3@gmail.com' , 'F' , 80 );

Select * from my_stu_details;

Validating Unique Key Constraint

--Duplicate Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , 'name3@gmail.com' , 'F' , 80 );

ORA-00001: unique constraint (HR.MY_STU_MAIL_UK) violated

--Null Check
Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , null , 'M' , 70 );

Select * from my_stu_details;

Validating Check constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'j' , 70 );

ORA-02290: check constraint (HR.MY_STU_GEN_CK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'M' , 70 );

Select * from my_stu_details;

Validating Foreign Key


Select * from Departments;

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 3 );

ORA-02291: integrity constraint (HR.MY_STU_DID_FK) violated - parent key not found

Departments table : parent table

my_stu_details : Child table

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

--------------------------------------------------------

s_id s_name s_mail s_gender s_did

--------------------------------------------------------

1 name1 name1@gmail.com m 60

2 name2 name2@gmail.com F 90
3 Name3 name3@gmail.com F 80

4 Name4 M 70

5 Name5 name5@gmail.com M 70

6 Name6 name6@gmail.com F 90

--------------------------------------------------------

Deleting the Primary key value which is referred by Foreign Key

Select * from Departments;

DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID

------------------------------------------------------------

60 IT 103 1400 <---- Delete

-- don't execute this query

--Delete From Departments

--Where Department_id = 60;

1) ON DELETE SET NULL


-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

1 name1 name1@gmail.com m -

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

2) ON DELETE SET CASCADE

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

Syntax
Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE CASCADE

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE SET NULL

Constraint Related Data Dictionary Table information.

To view constraint Information

SELECT c.owner,

c.constraint_name,

c.constraint_type,

c.table_name,

c.r_constraint_name,

c.status

FROM user_constraints c

WHERE c.table_name = 'MY_STU_DETAILS';

------------------------------------------------------------------------------------

owner constraint_name constraint_type table_name r_constraint_name status

------------------------------------------------------------------------------------
HR SYS_C004023 C MY_STU_DETAILS ENABLED

HR MY_STU_GEN_CK C MY_STU_DETAILS ENABLED

HR MY_STU_SID_PK P MY_STU_DETAILS ENABLED

HR MY_STU_MAIL_UK U MY_STU_DETAILS ENABLED

HR MY_STU_DID_FK R MY_STU_DETAILS DEPT_ID_PK ENABLED

------------------------------------------------------------------------------------

To view constraint name with corresponding column name

SELECT * FROM user_cons_columns c

WHERE c.table_name = 'MY_STU_DETAILS';

-------------------------------------------------------------

owner constraint_name table_name column_name position

-------------------------------------------------------------

HR MY_STU_MAIL_UK MY_STU_DETAILS S_MAIL 1

HR MY_STU_SID_PK MY_STU_DETAILS S_ID 1

HR MY_STU_GEN_CK MY_STU_DETAILS S_GENDER

HR SYS_C004023 MY_STU_DETAILS S_NAME

HR MY_STU_DID_FK MY_STU_DETAILS S_DID 1

-------------------------------------------------------------
Creating Composite Primary Key

Creating Primary Key with more than one number of column

ALTER TABLE table_name

ADD CONSTRAINT constraint_name PRIMARY KEY(column1, column_2 , column3);

In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.

creating constraint after the table creation

ALTER TABLE table_name

ADD CONSTRAINT constraint_name CONSTRAINT_TYPE(column_name);

ALTER TABLE table_name

DROP CONSTRAINT constraint_name;

ALTER TABLE table_name

DROP PRIMARY KEY;

To drop related foreign key


ALTER TABLE table_name

DROP PRIMARY KEY CASCADE;

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name;

Disable constraint with related foreign key constraint

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name CASCADE;

ALTER TABLE table_name

ENABLE CONSTRAINT constraint_name;

Interview Questions

What are all the type of constraint available in oracle?

Difference between PRIMARY KEY and UNIQUE key.


Difference between PRIMARY KEY ans FOREIGN KEY.

Difference between UNIQUE key and FOREIGN KEY.

Is it possible to create tow primary key in single table.

Write a syntax to create FOREIGN constraint.

How to create constraint after the table has been created?

How to enable and disable a constraint.

Which data dictionary table contains information about constraints?

Which Data Dictionary table contains information about constraint with corresponding column
name?

What is composite primary key?

Explain ON DELETE CASCADE and ON DELETE SET NULL option.

~Thanks For Reading~

Post your valuable feedback below

Posted 21st December 2014 by Unknown

1 View comments

UnknownMay 22, 2017 at 12:39 AM

good
Reply

DEC

listagg in Oracle 11g

Oracle 11gR2 listagg built-in function allows for many table columns to be displayed within a
single row, a non-first-normal form display

Syntax :

listagg(column_value,'delimiter') WITHIN GROUP(ORDER BY column_name)

--Example 1:

CREATE TABLE test_ins(empid NUMBER,product VARCHAR2(30));

BEGIN

INSERT INTO test_ins VALUES( 101,'pendrive');

INSERT INTO test_ins VALUES( 102,'toy');

INSERT INTO test_ins VALUES( 101,'ipod');

INSERT INTO test_ins VALUES( 102,'hat');

INSERT INTO test_ins VALUES( 103,'cpu');

INSERT INTO test_ins VALUES( 104,'pen');

INSERT INTO test_ins VALUES( 104,'car');


INSERT INTO test_ins VALUES( 104,'mat');

INSERT INTO test_ins VALUES( 105,'tv');

INSERT INTO test_ins VALUES( 106,'laptop');

commit;

END;

SELECT * FROM test_ins;

SELECT empid "Employee",

listagg(product,

',') within

GROUP (ORDER BY empid) "Products"

FROM test_ins

GROUP BY empid;

-->-- Result set --<--


DROP TABLE test_ins;

-->-- Example 2

select department_id "Department id", listagg(first_name,', ') WITHIN GROUP(ORDER BY


employee_id) "Employees"

FROM employees

WHERE department_id IN (10,20,30,60)

GROUP BY department_id;

-->-- Result set --<--

Posted 4th December 2014 by Unknown

0 Add a comment

NOV

8
Condition and Looping Statement

IF

IF ELSE

Multiple IF ELSE

LOOP

FOR LOOP

WHILE LOOP

create table test_udt(id NUMBER, salary NUMBER);

BEGIN

INSERT INTO test_udt VALUES(001,23000);

INSERT INTO test_udt VALUES(002,43000);

INSERT INTO test_udt VALUES(003,78000);

INSERT INTO test_udt VALUES(004,25000);

INSERT INTO test_udt VALUES(005,26000);

INSERT INTO test_udt VALUES(006,90000);

Commit;

END;
select * from test_udt;

IF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 1;

IF v_salary > 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

END IF;

commit;

END;

/
IF ELSE

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

ELSE

UPDATE test_udt t

SET t.salary = v_salary+20007

WHERE t.id = v_id ;

END IF;

commit;

END;

/
--same example with less number of lines

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

v_salary := v_salary+10005;

ELSE

v_salary := v_salary+20007;

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

/
select * from test_udt;

Multiple IF ELSIF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 3;

IF v_id = 1 THEN

v_salary := 1000;

dbms_output.put_line('1 inside');

ELSIF v_id = 2 THEN

v_salary := 2000;

dbms_output.put_line('2 inside');

ELSIF v_id = 3 THEN

v_salary := 3000;

dbms_output.put_line('3 inside');

ELSIF v_id = 4 THEN

v_salary := 4000;

dbms_output.put_line('4 inside');
END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

LOOP

--syntax

LOOP

--statements

--increment

--exit statement

END LOOP;

CREATE TABLE prod_details (pid VARCHAR2(3), pname VARCHAR2(30));


DECLARE

i NUMBER := 1;

x VARCHAR2(3);

BEGIN

LOOP

x := lpad(i,3,'0');

dbms_output.put_line('x value : '|| x);

INSERT INTO prod_details VALUES(i, 'Product '||i);

EXIT WHEN i >900;

i := i+1;

IF MOD(i,100) = 0 THEN

commit;

dbms_output.put_line('commit executed');

END IF;

END LOOP;

END;

SELECT * FROM prod_details ORDER BY 1;

DROP TABLE prod_details;

FOR LOOP
BEGIN

FOR I in 1..5

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

FOR LOOP - Reverse

BEGIN

FOR I in REVERSE 14..50

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

WHILE LOOP

DECLARE

i_val NUMBER:=0;

BEGIN

WHILE (i_val < 11)

LOOP
dbms_output.put_line('The value of I is '||i_val);

i_val := i_val + 1;

END LOOP;

END;

sample output:

The value of I is 0

The value of I is 1

The value of I is 2

The value of I is 3

The value of I is 4

The value of I is 5

The value of I is 6

The value of I is 7

The value of I is 8

The value of I is 9

The value of I is 10

Posted 8th November 2014 by Unknown

0 Add a comment
OCT

21

Bulk Collect

This is used for array fetches

With this you can retrieve multiple rows of data with a single round trip.

This reduces the number of context switches between the pl/sql and sql engines.

You can use bulk collect in both dynamic and static sql.

You can use bulk collect in select, fetch into and returning into clauses.

SQL engine automatically initializes and extends the collections you reference in the bulk
collect clause.

You can fetch into multiple collections with one column each.

You can use the limit clause of bulk collect to restrict the no of rows retrieved.

SELECT * FROM product_details;

-->-- Bulk collect in FETCH INTO --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS
SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Bulk collect in SELECT clause --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

BEGIN

SELECT * BULK COLLECT INTO dta FROM product_details;

FOR i IN dta.FIRST .. dta.LAST LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;
-->-- LIMIT in Bulk collect --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta LIMIT 30;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Multiple fetches in INTO clause --<--


SELECT * FROM product_details;

DECLARE

TYPE alldata_typ1 IS TABLE OF product_details.p_id%TYPE;

TYPE alldata_typ2 IS TABLE OF product_details.p_name%TYPE;

dta1 alldata_typ1;

dta2 alldata_typ2;

CURSOR proddt_cur IS

SELECT p_id, p_name FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta1, dta2;

CLOSE proddt_cur;

FOR i IN dta1.FIRST .. dta1.COUNT LOOP

dbms_output.put_line('Department Id : ' || dta1(i));

END LOOP;

FOR i IN dta2.FIRST .. dta2.COUNT LOOP

dbms_output.put_line('Department Name : ' || dta2(i));

END LOOP;

END;
/

DROP TABLE dep_details;

DROP TABLE product_details;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Ref Cursor

This is unconstrained cursor which will return different types depends upon the user input.

Ref cursors cannot be closed implicitly.

Ref cursor with return type is called strong cursor.

Ref cursor without return type is called weak cursor.

You can declare ref cursor type in package spec as well as body.

You can declare ref cursor types in local subprograms or anonymous blocks.

CREATE OR REPLACE PROCEDURE ref_c_sp(dep_det_c IN OUT SYS_REFCURSOR)

AS
BEGIN

OPEN dep_det_c

FOR

SELECT * FROM dep_details d;

END;

DECLARE

dep_det_c SYS_REFCURSOR;

tab_data dep_details%ROWTYPE;

BEGIN

ref_c_sp(dep_det_c);

LOOP

FETCH dep_det_c INTO tab_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department Name : '|| tab_data.d_name);

END LOOP;

CLOSE dep_det_c;

END;

/*sample output*/
Department Name : Admin

Department Name : HR

Department Name : Sales

Department Name : Marketing

DROP PROCEDURE ref_c_sp;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Cursor

SQL Private work Area where the query get passed and executed.

Types

******

Implicit(SQL)

Explicit

-->-- advanced cursor types --<--


Parametrized Cursor

Ref Cursor

Implicit

********

ORACLE implicitly opens a cursor to process each SQL statement not associated with an
explicitly declared cursor.

PL/SQL lets you refer to the most recent implicit cursor as the SQL” cursor. So, although you
cannot use the OPEN,

FETCH, and CLOSE statements to control an implicit cursor, you can still use cursor attributes to
access information

about the most recently executed SQL statement.

Cursor Stages

**************

OPEN cursor_name

FETCH (with in loop)

CLOSE cursor_name

Explicit

The set of rows returned by a query can consist of zero, one, or multiple rows,

depending on how many rows meet your search criteria. When a query returns multiple rows,

you can explicitly define a cursor to process the rows. You use three commands to control the
cursor

Cursor Attributes

*****************

%FOUND

%NOTFOUND

%ISOPEN

%ROWCOUNT

%BULK_ROWCOUNT --<-- used to handle error while using bulk collection.

%BULK_EXCEPTIONS --<-- used to handle error while using bulk collection.

Cursor Declaration

DECLARE

CURSOR <cursor_name>

IS

<SELECT statement>

BEGIN

--> some stmt

END;

Cursor Loop

Loop
While Loop

For Loop

Cursor Clauses

Return

For update

Where current of

Bulk collect

-->-- creating table

create table product_details

p_id NUMBER,

p_name VARCHAR2(30),

p_order_dt DATE

);

-->-- Inserting data

BEGIN

FOR i IN 1 .. 75 LOOP

INSERT INTO product_details VALUES (i, 'prod_name_' || i, SYSDATE + i);

END LOOP;
commit;

END;

-->-- selecting data

SELECT * FROM product_details;

---------------------------------------------

p_id p_name p_order_dt

---------------------------------------------

1 prod_name_1 10/11/2014 3:48:32 PM

2 prod_name_2 10/12/2014 3:48:32 PM

3 prod_name_3 10/13/2014 3:48:32 PM

4 prod_name_4 10/14/2014 3:48:32 PM

5 prod_name_5 10/15/2014 3:48:32 PM

6 prod_name_6 10/16/2014 3:48:32 PM

7 prod_name_7 10/17/2014 3:48:32 PM

8 prod_name_8 10/18/2014 3:48:32 PM

9 prod_name_9 10/19/2014 3:48:32 PM

10 prod_name_10 10/20/2014 3:48:32 PM

11 prod_name_11 10/21/2014 3:48:32 PM

12 prod_name_12 10/22/2014 3:48:32 PM

13 prod_name_13 10/23/2014 3:48:32 PM

14 prod_name_14 10/24/2014 3:48:32 PM


15 prod_name_15 10/25/2014 3:48:32 PM

16 prod_name_16 10/26/2014 3:48:32 PM

17 prod_name_17 10/27/2014 3:48:32 PM

18 prod_name_18 10/28/2014 3:48:32 PM

19 prod_name_19 10/29/2014 3:48:32 PM

20 prod_name_20 10/30/2014 3:48:32 PM

---------------------------------------------

----------------------------------------------

Implicit Cursor

----------------------------------------------

--will update soon

----------------------------------------------

Explicit Cursor

----------------------------------------------

**********************************************

Processing cursor data by using LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;
--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND; --<-- if next record not found means control will
come out from the loop

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )


DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

EXIT WHEN prod_detail_cur%FOUND; --<-- if next record found means control will come
out from the loop

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )


DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE
dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor Already closed

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN
OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

-->-- CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )


Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor closed

**********************************************

Processing cursor data by using WHILE LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

OPEN prod_detail_cur;

FETCH prod_detail_cur

INTO all_data;

WHILE prod_detail_cur%FOUND LOOP

dbms_output.put_line('Product id : ' || all_data.p_id ||


' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

FETCH prod_detail_cur

INTO all_data;

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

************************************************************

Processing cursor data by using FOR LOOP - CURSOR FOR LOOP

************************************************************

DECLARE

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;


BEGIN

FOR i IN prod_detail_cur

LOOP

dbms_output.put_line('Product id : ' || i.p_id ||

' Product Name : ' || i.p_name ||

' ( Orderd on : ' || TRIM(i.p_order_dt) || ' )');

END LOOP;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

Parameterized Cursor

*********************

This was used when you are going to use the cursor in more than one place with different
values for the same where clause.

Cursor parameters must be in mode.


Cursor parameters may have default values.

The scope of cursor parameter is within the select statement.

CREATE TABLE dep_details(d_id NUMBER,d_name VARCHAR2(30), location_id NUMBER);

BEGIN

INSRT INTO dep_details VALUES(001,'Admin',1010);

INSRT INTO dep_details VALUES(002,'HR',1010);

INSRT INTO dep_details VALUES(003,'Sales',1020);

INSRT INTO dep_details VALUES(004,'Marketing',1020);

commit;

END;

SELECT * FROM dep_details;

----------------------------

d_id d_name location_id

----------------------------

1 Admin 1010

2 HR 1010

3 Sales 1020

4 Marketing 1020

----------------------------
DECLARE

-->--Declaring parameterized cursor

CURSOR dep_det_c(p_location_id NUMBER) IS

SELECT * FROM dep_details d WHERE d.location_id = p_location_id;

all_data dep_details%ROWTYPE;

BEGIN

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

OPEN dep_det_c(1010);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

-->-- opening same cursor with different input value

OPEN dep_det_c(1020);

LOOP
FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

END;

/*sample output*/

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 1 Department Name : Admin

Department id : 2 Department Name : HR

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 3 Department Name : Sales

Department id : 4 Department Name : Marketing

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Posted 21st October 2014 by Unknown

0 Add a comment
OCT

21

Handling Exception

Error Handling in oracle

ERROR

Any departure from the expected behavior of the system or program,

which stops the working of the system is an error.

Types : compile time error

Run time error

EXCEPTION

Any error or problem which one can handle and continue to work normally.

Handling Exception

When exception is raised, control passes to the exception section of the block.

i.e. EXCEPTION

WHEN name_of_exception THEN

Types : Pre Defined Exceptions


User Defined Exceptions

Predefined Exception

*********************

Oracle has predefined several exceptions that correspond to the most common oracle errors.

------------------------------------------------------------------------

Exception Oracle Error SQL Code Value

------------------------------------------------------------------------

ZERO_DIVIDE ORA-01476 -1476

NO_DATA_FOUND ORA-01403 +100

DUP_VAL_ON_INDEX ORA-00001 -1

TOO_MANY_ROWS ORA-01422 -1422

VALUE_ERROR ORA-06502 -6502

CURSOR_ALREADY_OPEN ORA-06511 -6511

OTHERS

------------------------------------------------------------------------

-->-- ZERO_DIVIDE --<--

Your program attempts to divide a number by zero.


DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN ZERO_DIVIDE THEN

dbms_output.put_line('Divisor is equal to zero');

END;

-->-- NO_DATA_FOUND --<--

Single row SELECT returned no rows or your program referenced a deleted element in a nested
table

or an uninitialized element in an associative array (index-by table).

CREATE TABLE test_tb(id NUMBER PRIMARY KEY);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN NO_DATA_FOUND THEN

dbms_output.put_line('There is no data inside the table');


END;

-->-- DUP_VAL_ON_INDEX --<--

A program attempted to insert duplicate values in a column that is constrained by a unique


index.

INSERT INTO test_tb VALUES (1);

INSERT INTO test_tb VALUES (2);

commit;

BEGIN

INSERT INTO test_tb VALUES (2);

EXCEPTION

WHEN DUP_VAL_ON_INDEX THEN

dbms_output.put_line('Duplicate values are not allowed');

END;

-->-- TOO_MANY_ROWS --<--

Single row SELECT returned multiple rows.


DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN TOO_MANY_ROWS THEN

dbms_output.put_line('Query returning more than one row');

END;

DROP TABLE test_tb;

-->-- VALUE_ERROR --<--

An arithmetic, conversion, truncation, or size constraint error occurred.

DECLARE

num1 NUMBER(2);

BEGIN

num1 := 345;

EXCEPTION

WHEN VALUE_ERROR THEN

dbms_output.put_line('check the size of the variable');

END;
-->-- CURSOR_ALREADY_OPEN --<--

A program attempted to open an already opened cursor.

CREATE TABLE emp(id NUMBER, name VARCHAR2(30));

BEGIN

INSERT INTO emp VALUES(1,'Name1');

INSERT INTO emp VALUES(2,'Name2');

INSERT INTO emp VALUES(3,'Name3');

INSERT INTO emp VALUES(4,'Name4');

COMMIT;

END;

SELECT * FROM emp;

DECLARE

cursor emp_c IS

SELECT * FROM emp;

all_data emp%ROWTYPE;

BEGIN

OPEN emp_c;
OPEN emp_c;

NULL;

CLOSE emp_c;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

END;

DROP TABLE emp;

-->-- OTHERS --<--

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

WHEN OTHERS THEN

dbms_output.put_line('Some other error ' || SQLERRM);

END;
User Defined Exception

**********************

A user-defined exception is an error that is defined by the programmer.

User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,

exceptions have a type EXCEPTION and scope.

DECLARE

v_gender CHAR := '&gender';

gender_ex EXCEPTION;

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE gender_ex;

END IF;

dbms_output.put_line('Gender : '||v_gender);

EXCEPTION

WHEN gender_ex THEN

dbms_output.put_line('Please Enter valid gender');

END;

create table test_insert (id NUMBER, Name VARCHAR2(30));


DECLARE

abort_ex EXCEPTION;

BEGIN

FOR i IN 1..100

LOOP

BEGIN

IF mod(i,10)=0 THEN

RAISE abort_ex;

END IF;

INSERT INTO test_insert VALUES(i, 'Name'||i);

EXCEPTION

WHEN abort_ex THEN

NULL;

END;

END LOOP;

COMMIT;

END;

SELECT * FROM test_insert;

DROP TABLE test_insert;

SQLERRM and SQLCODE

********************
SQLCODE returns the current error code, and SQLERRM returns the current error message
text;

For user-defined exception SQLCODE returns 1 and SQLERRM returns “user-defined


exception”.

SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.

CREATE TABLE test_tb (id NUMBER);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

dbms_output.put_line(v_id);

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('SQLERRM : ' || SQLERRM);

dbms_output.put_line('SQLCODE : ' || SQLCODE);

END;

/*sample output*/

SQLERRM : ORA-01403: no data found

SQLCODE : 100
DROP TABLE test_tb;

PRAGMA EXCEPTION_INIT

*********************

Using this you can associate a named exception with a particular oracle error.

This gives you the ability to trap this error specifically, rather than via an OTHERS handler.

Syntax:

PRAGMA EXCEPTION_INIT(exception_name, oracle_error_number);

DECLARE

v_result NUMBER;

PRAGMA EXCEPTION_INIT(Invalid, -1476);

BEGIN

SELECT 453 / 0 INTO v_result FROM dual;

dbms_output.put_line('Result : ' || v_result);

EXCEPTION

WHEN INVALID THEN

dbms_output.put_line('Invalid Exception');

END;
RAISE_APPLICATION_ERROR

************************

You can use this built-in function to create your own error messages, which can be more
descriptive than named exceptions.

Error Number :

Oracle Error Range : From -00000 to -19999

User Error Range : From -20000 to -20999

DECLARE

v_gender CHAR := '&gender';

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE_APPLICATION_ERROR(-20003, 'Enter valid gender');

END IF;

dbms_output.put_line('Gender : ' || v_gender);

END;

Posted 21st October 2014 by Unknown


1 View comments

RajmohanMarch 13, 2018 at 6:49 AM

How to get the two table data without using Joins and sub query,union?

Reply

OCT

Package

1. You can groups logical related subprogram (procedures and functions)

2. It consist of two parts

I) specification

II) Body

3. It allows the oracle server to read multiple object in to a memory once

4. You can declare global variable,cursor, user define exeption

5. Overloading

6. we can't create anonyms block inside the package

create table err_log(sno NUMBER, u_name VARCHAR2(30), error_msg CLOB, hap_tm


TIMESTAMP);
select * from err_log;

--stand alone procedure

CREATE OR REPLACE PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id


%TYPE) IS

v_salary employees.salary%TYPE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT salary,

first_name

INTO v_salary,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line('Salary of ' || v_first_name || ' is ' || v_salary);

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,
v_error,

systimestamp);

commit;

END emp_sal_sp;

BEGIN

-- Call the procedure

emp_sal_sp(p_employee_id => :p_employee_id);

END;

CREATE OR REPLACE PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id


%TYPE) IS

v_hire_date DATE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT hire_date,

first_name

INTO v_hire_date,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line(v_first_name || ' hired on ' || to_char(v_hire_date,'month ddth,


yyyy'));
EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_hdt_sp;

BEGIN

-- Call the procedure

emp_hdt_sp(p_employee_id => :p_employee_id);

END;

create or replace function sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER

IS

v_c NUMBER;

BEGIN
v_c := p_a + p_b;

RETURN v_c;

END;

--Specification Part

CREATE OR REPLACE PACKAGE emp_pkg

IS

PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id%TYPE);

PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id%TYPE);

FUNCTION sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER;

END emp_pkg ;

--Body Part

CREATE OR REPLACE PACKAGE BODY emp_pkg

IS
PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id%TYPE) IS

v_salary employees.salary%TYPE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT salary,

first_name

INTO v_salary,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line('Salary of ' || v_first_name || ' is ' || v_salary);

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_sal_sp;
PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id%TYPE) IS

v_hire_date DATE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT hire_date,

first_name

INTO v_hire_date,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line(v_first_name || ' hired on ' || to_char(v_hire_date,'month ddth,


yyyy'));

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_hdt_sp;

FUNCTION sum_fn (p_a IN NUMBER, p_b IN NUMBER)


RETURN NUMBER

IS

v_c NUMBER;

BEGIN

v_c := p_a + p_b;

RETURN v_c;

END;

END emp_pkg;

A package specification can exist without a package body, but

a package body can't exist without a package specification.

--Executing procedure inside the package

BEGIN

emp_pkg.emp_sal_sp(120);

END;

--Executing function inside the package

SELECT emp_pkg.sum_fn(23,567) FROM dual;


-- You can declare global variable,cursor, user define exeption

create or replace package all_detail

as

PROCEDURE emp2sal (a IN NUMBER);

PROCEDURE emp2exep (a IN NUMBER);

FUNCTION add2num (a IN NUMBER, b IN NUMBER)

RETURN NUMBER;

c NUMBER(8); --global declaration

abort_ex EXCEPTION; --global exception declaration

CURSOR emp_rec --global cursor declaration

IS

SELECT first_name, salary, hire_date, department_id

FROM employees;

End all_detail;

create or replace package body all_detail

as
PROCEDURE emp2sal (a IN NUMBER)

AS

BEGIN

SELECT salary

INTO c

FROM Employees

WHERE Employee_id = a;

Dbms_output.put_line('Salary of Employee ' || a || ' is ' || c);

EXCEPTION

WHEN no_data_found THEN

Dbms_output.put_line('Please enter valid id');

END emp2sal;

PROCEDURE emp2exep (a IN NUMBER)

AS

BEGIN

SELECT Round(Months_between(sysdate,hire_date)/12)

INTO c

FROM Employees

WHERE Employee_id = a;
Dbms_output.put_line( c || ' Years');

EXCEPTION

WHEN no_data_found THEN

Dbms_output.put_line('Please enter valid id');

END emp2exep;

FUNCTION add2num (a IN NUMBER, b IN NUMBER)

RETURN NUMBER

AS

BEGIN

c := a+b;

RETURN C;

END;

End all_detail;

/*Declaring a Bodiless Package */

CREATE OR REPLACE PACKAGE global_constant

IS

mile_2_kilo CONSTANT NUMBER := 1.6093;


kilo_2_mile CONSTANT NUMBER := 0.6214;

yard_2_meter CONSTANT NUMBER := 0.9144;

meter_2_yard CONSTANT NUMBER := 1.0936;

END global_constant;

BEGIN

DBMS_OUTPUT.PUT_LINE('20 miles = ' || 20*global_constant.mile_2_kilo||' km');

END;

/*Forward Declaration in package */

DECLARE

PROCEDURE P2; -- forward declaration

PROCEDURE P3;

PROCEDURE P1 IS

BEGIN

dbms_output.put_line('From procedure p1');

p2;

END P1;

PROCEDURE P2 IS

BEGIN
dbms_output.put_line('From procedure p2');

p3;

END P2;

PROCEDURE P3 IS

BEGIN

dbms_output.put_line('From procedure p3');

END P3;

BEGIN

p1;

END;

sample output:

From procedure p1

From procedure p2

From procedure p3

Drop package package_name;

Drop package body package_name;

SELECT text FROM user_source u


WHERE u.name = 'EMP_PKG';

Interview Questions:

What is package?

Advantage of package

Is it possible to create package body with out package specification?

what is package overloading?

what is forward declaration in package?

which data dictionary table contain source code of package?

How to declare global variable, exception and cursor?

How to execute procedure and function inside the package?

Posted 4th October 2014 by Unknown

0 Add a comment

OCT

%TYPE and %ROWTYPE


--%type is used to fetch the data type of the particular column

create table product_details

p_id NUMBER(3),

p_nm VARCHAR2(30),

p_qty NUMBER(8),

order_dt DATE

);

BEGIN

INSERT INTO product_details VALUES(100,'Name0',400,'23-Mar-13');

INSERT INTO product_details VALUES(101,'Name1',600,'26-Apr-13');

INSERT INTO product_details VALUES(102,'Name2',800,'27-Jan-12');

INSERT INTO product_details VALUES(103,'Name3',300,'23-Jul-11');

INSERT INTO product_details VALUES(104,'Name4',200,'22-Aug-11');

INSERT INTO product_details VALUES(105,'Name5',500,'25-Oct-12');

commit;

END;

SELECT * FROM product_details;


------------------------------------

P_ID P_NM P_QTY ORDER_DT

------------------------------------

100 Name0 400 03/23/2013

101 Name1 600 04/26/2013

102 Name2 800 01/27/2012

103 Name3 300 07/23/2011

104 Name4 200 08/22/2011

105 Name5 500 10/25/2012

------------------------------------

DECLARE

v_name VARCHAR2(4);

BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 100;

dbms_output.put_line('Product Name : ' || v_name);

--error numeric or value error

END;
DECLARE

v_name VARCHAR2(5);

BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 100;

dbms_output.put_line('Product Name : ' || v_name);

END;

ALTER TABLE product_details

MODIFY p_nm VARCHAR2(15);

INSERT INTO product_details

VALUES

(106,

'name6',

700,

'26-Dec-12');

commit;
106 name6 700 12/26/2012

DECLARE

v_name VARCHAR2(5);

BEGIN

SELECT p_nm INTO v_name

FROM product_details

WHERE p_id = 106;

dbms_output.put_line('Product Name : ' || v_name);

--error

END;

DECLARE

v_name product_details.p_nm%TYPE;

BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 106;


dbms_output.put_line('Product Name : ' || v_name);

END;

DROP TABLE product_details;

DECLARE

dep_id departments.department_id%TYPE;

dep_name departments.department_name%TYPE;

dep_man_id departments.manager_id%TYPE;

dep_loc_id departments.location_id%TYPE;

BEGIN

SELECT department_id,

department_name,

manager_id,

location_id

INTO dep_id,

dep_name,

dep_man_id,

dep_loc_id
FROM departments

WHERE department_id = 10;

dbms_output.put_line('Department_id : ' || dep_id);

dbms_output.put_line('Department_name : ' || dep_name);

dbms_output.put_line('Manager_id : ' || dep_man_id);

dbms_output.put_line('Location_id : ' || dep_loc_id);

END;

--%rowtype is used to fetch the data type of all the column

--Insted of using %type if we use %rowtype means we can reduce the no of variables that we
declare

DECLARE

dep_detail departments%ROWTYPE;

BEGIN

SELECT *

INTO dep_detail

FROM departments

WHERE department_id = 10;


dbms_output.put_line('Department_id : ' || dep_detail.department_id);

dbms_output.put_line('Department_name : ' || dep_detail.department_name);

dbms_output.put_line('Manager_id : ' || dep_detail.manager_id);

dbms_output.put_line('Location_id : ' || dep_detail.location_id);

END;

DROP TABLE dept_details;

CREATE TABLE dept_details

dept_id number(3) ,

dept_name varchar2(30),

dept_manager_name varchar2(30)

);

insert into dept_details values(10,'dept1','manager_name1');

insert into dept_details values(20,'dept2','manager_name2');

SELECT * FROM dept_details;


-------------------------------------------------------

| DEPT_ID | DEPT_NAME | DEPT_MANAGER_NAME |

+------------+-----------------------+-----------------

| 10 | dept1 | manager_name1 |

| 20 | dept2 | manager_name2 |

------------+-----------------------+------------------

DECLARE

all_data dept_details%ROWTYPE;

BEGIN

all_data.dept_id := 100;

all_data.dept_name := 'Admin';

all_data.dept_manager_name := 'John';

UPDATE dept_details

SET ROW = all_data

WHERE dept_id = 10;

dbms_output.put_line(SQL%ROWCOUNT || ' Row(s) get updated');

END;

/
1 Row(s) get updated

select * from dept_details;

---------------------------------------------------

| DEPT_ID | DEPT_NAME | DEPT_MANAGER_NAME|

---------------------------------------------------

| 100 | Admin | John |

| 20 | dept2 | manager_name2 |

---------------------------------------------------

Interview Question :

1. What is the use of %TYPE?

2. What is the use of %ROWTYPE?

3. Difference between %TYPE and %ROWTYPE?

Posted 2nd October 2014 by Unknown

0 Add a comment
SEP

29

BULK Exceptions

/************************************************************************

* Handling Exceptions in Bulk Operations *

* Documented on 29-SEP-14 04.35.35.980894 PM +05:30 *

* Document By : Murugappan Annamalai *

* Reference : http://www.dba-oracle.com/plsql/t_plsql_exceptions.htm *

************************************************************************/

CREATE TABLE bulk_tb (ran_num NUMBER NOT NULL);

--inserting data using bulk collect

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN
FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

commit;

END;

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

200

TRUNCATE TABLE bulk_tb;

sample2.sql --without exception part


DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

commit;

END;

/*

Error Message :

ORA-01400: cannot insert NULL into ("HR"."bulk_tb"."ran_num")

ORA-06512: at line 15
*/

sample2.sql --with exception part

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

BEGIN

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

COMMIT;

EXCEPTION
WHEN OTHERS THEN

dbms_output.put_line('Error while inserting bulk record '||SQLERRM);

END;

END;

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

99

SQL%BULK_EXCEPTIONS(i).ERROR_INDEX

Holds the iteration (not the subscript) of the original FORALL statement that raised the
exception.

In sparsely populated collections,

the exception row must be found by looping through the original collection the correct
number of times.

SQL%BULK_EXCEPTIONS(i).ERROR_CODE
Holds the exceptions error code.

The total number of exceptions can be returned using the collections COUNT method,

which returns zero if no exceptions were raised. The save_exceptions.sql script,

a modified version of the handled_exception.sql script, demonstrates this functionality.

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

v_ex_count NUMBER(4);

abort_ex EXCEPTION;

PRAGMA EXCEPTION_INIT(abort_ex, -24381);

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

v_dat(150) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */


EXECUTE IMMEDIATE 'TRUNCATE TABLE bulk_tb';

BEGIN

FORALL i IN v_dat.FIRST..v_dat.LAST SAVE EXCEPTIONS

INSERT INTO bulk_tb VALUES(v_dat(i));

COMMIT;

EXCEPTION

WHEN abort_ex THEN

v_ex_count := SQL%BULK_EXCEPTIONS.COUNT;

FOR i IN 1..v_ex_count LOOP

dbms_output.put_line('Error: ' || i ||' Array Index: ' || SQL


%BULK_EXCEPTIONS(i).error_index ||

' Message: ' || SQLERRM(SQL%BULK_EXCEPTIONS(i).ERROR_CODE));

END LOOP;

END;

END;

/*

Sample output:

Error: 1 Array Index: 100 Message: -1400: non-ORACLE exception

Error: 2 Array Index: 150 Message: -1400: non-ORACLE exception

*/
SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

198

SAVE EXCEPTIONS clause being removed, in the above script now traps a different error number.

The output from this script is listed below.

/*

Sample output:

Error: 1 Array Index: 100 Message: -1400: non-ORACLE exception

*/

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)
-------

99

SELECT COUNT(*) FROM bulk_tb;

DROP TABLE bulk_tb;

Posted 29th September 2014 by Unknown

0 Add a comment

SEP

29

Cursor - FOR UPDATE

/************************************************************************

* FOR UPDATE clause in oracle *

* Document By : Murugappan Annamalai *

************************************************************************/
create table prod_details(p_id VARCHAR2(30), P_name VARCHAR2(30));

BEGIN

--Inserting data into prod_details table

FOR i IN 1..50 LOOP

INSERT INTO prod_details VALUES(i,'pname'||i);

END LOOP;

commit;

END;

SELECT * FROM prod_details;

DECLARE

CURSOR PROD_DTLS_C IS

SELECT * FROM PROD_DETAILS T1 FOR UPDATE OF P_ID;

V_PID PROD_DETAILS.P_ID%TYPE;

V_PRDNAME PROD_DETAILS.P_NAME%TYPE;

BEGIN
OPEN PROD_DTLS_C;

LOOP

FETCH PROD_DTLS_C INTO V_PID, V_PRDNAME;

IF PROD_DTLS_C%NOTFOUND THEN

EXIT;

ELSE

UPDATE PROD_DETAILS P

SET P.P_ID = LPAD(P_ID, 10, 0)

WHERE CURRENT OF PROD_DTLS_C;

END IF;

END LOOP;

CLOSE PROD_DTLS_C;

COMMIT;

END;

select * from PROD_DETAILS;

TRUNCATE TABLE prod_details;

BEGIN
--Inserting data into prod_details table

FOR i IN 1..50 LOOP

INSERT INTO prod_details VALUES(i,'pname'||i);

END LOOP;

commit;

END;

DECLARE

CURSOR PROD_DTLS_C IS

SELECT * FROM PROD_DETAILS T1 FOR UPDATE OF P_ID;

V_PID PROD_DETAILS.P_ID%TYPE;

V_PRDNAME PROD_DETAILS.P_NAME%TYPE;

BEGIN

OPEN PROD_DTLS_C;

LOOP

FETCH PROD_DTLS_C INTO V_PID, V_PRDNAME;

IF PROD_DTLS_C%NOTFOUND THEN
EXIT;

ELSE

UPDATE PROD_DETAILS P

SET P.P_ID = LPAD(P_ID, 10, 0)

WHERE CURRENT OF PROD_DTLS_C;

END IF;

COMMIT;

END LOOP;

CLOSE PROD_DTLS_C;

--COMMIT;

END;

select * from PROD_DETAILS;

Posted 29th September 2014 by Unknown

0 Add a comment

MAY

28

Escape Sequence in Oracle


Escape special characters when writing SQL queries

--to include single '

SELECT 'Steven's salary is more than 50k INR' AS "SAL_DETAILS"

FROM Dual;

ORA-01756 : quoted string not properly terminated

SELECT 'Steven''s salary is more than 50k INR' AS "SAL_DETAILS"

FROM Dual;

SAL_DETAILS

---------------------------------------

Steven's salary is more than 50k INR

--to include double '

SELECT 'You can print double quot ('''') in oracle' "Info"

FROM Dual;
Info

---------------------------------------

You can print double quot ('') in oracle

SELECT q'[some test ' some test ' some text ']' AS "In 10g"

FROM dual;

In 10g

------------------------------------

some test ' some test ' some text '

--Escape wild card characters ( _ and % )

The LIKE keyword allows for string searches.

The '_' wild card character is used to match exactly one character

While '%' is used to match zero or more occurrences of any characters.

These characters can be escaped in SQL as follows.

WITH mail_ids AS

SELECT 'an.murugappan@gmail.com' mail FROM Dual


UNION

SELECT 'an_murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an%murugappan@gmail.com' mail FROM Dual

SELECT * FROM mail_ids

WHERE mail LIKE '__$_%' ESCAPE '$';

mail

----------------------------------

an_murugappan@gmail.com

WITH mail_ids AS

SELECT 'an.murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an_murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an%murugappan@gmail.com' mail FROM Dual

SELECT * FROM mail_ids

WHERE mail LIKE '__/%%' ESCAPE '/';


mail

----------------------------------

an%murugappan@gmail.com

Escape ampersand (&) characters in SQL*Plus

SQL> select '&a' FROM dual;

'23'

----

23

SQL> SET ESCAPE '\'

SQL> select '\&a' FROM dual;

'&A'

----

&a

SQL> SET SCAN OFF;

SQL> select '&a' FROM dual;

'&A'
----

&a

SQL> SET SCAN ON;

SQL> select '&a' FROM dual;

'45'

----

45

Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Data Manipulation Language

Data Manipulation Language (DML) statements are used for managing data within schema
objects. Some examples:

INSERT - insert data into a table


UPDATE - updates existing data within a table

DELETE - deletes all records from a table, the space for the records remain

MERGE - UPSERT operation (insert or update)

CREATE TABLE prod_details

prod_id NUMBER(4) ,

prod_name VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

Deliver_dt DATE DEFAULT SYSDATE+3 ,

comments VARCHAR2(300)

);

SELECT * FROM prod_details;

no_data_found

INSERT

INSERT INTO prod_details(prod_id,prod_name,order_dt,deliver_dt,comments)

VALUES(100,'Apple iphone 5s','21-May-14','24-May-14','Color : Black');

SELECT * FROM prod_details;


---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

---------------------------------------------------------------------------

--Inserting records with out mentioning column name

INSERT INTO prod_details

VALUES(101,'Samsung Galaxy III','20-Aug-14','23-Aug-14','Color : White');

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

---------------------------------------------------------------------------

--Inserting selective number of values

INSERT INTO prod_details

VALUES(103,'Moto X','11-May-14','13-May-14');
ORA-00947 : not enough values

--While inserting selective number of values mentioning column name is compulsory.

INSERT INTO prod_details (prod_id,prod_name,order_dt,deliver_dt)

VALUES(103,'Moto X','11-May-14','13-May-14');

SELECT * FROM prod_details;

--------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

--------------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

--------------------------------------------------------------------------------

--Inserting NULL value.

--If you want to insert NULL value you can ignore that column at the time of inserting

--or we can use NULL keyword to insert NULL.

INSERT INTO prod_details

VALUES(104,'Moto G','19-May-14','22-May-14',NULL);
SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Noto G 5/19/2014 5/22/2014

---------------------------------------------------------------------------

--if you are not providing values for order_dt and deliver_dt column default value can be taken.

INSERT INTO prod_details(prod_id,prod_name,comments)

VALUES(105,'Nokia Lumis 720p','Color : Red');

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

----------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black


101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Moto G 5/19/2014 5/22/2014

105 Nokia Lumis 720p 5/26/2014 5/29/2014 Color : Red

---------------------------------------------------------------------------

--Inserting data by using sub query

CREATE TABLE test_tab (id NUMBER, Name VARCHAR2(30));

INSERT INTO test_tab VALUES(1,'Name1');

INSERT INTO test_tab VALUES(2,'Name2');

INSERT INTO test_tab VALUES(3,'Name3');

SELECT COUNT(*) FROM test_tab;

COUNT(*)

-------

--creating table by using sub query (with out data)

CREATE TABLE ins_chk


SELECT * FROM test_tab

WHERE id = 900;

SELECT COUNT(*) FROM ins_chk;

COUNT(*)

-------

--Inserting data by using sub query

--copying data from test_tab to ins_chk

INSERT INTO ins_chk (SELECT * FROM test_tab);

3 rows inserted in 0.047 seconds.

SELECT COUNT(*) FROM ins_chk;

COUNT(*)

-------

3
DROP TABLE test_tab;

DROP TABLE ins_chk;

UPDATE

Syntax :

UPDATE table_name

SET column1_name = column1_value,

column2_name = column2_value,

column2_name = column3_value,

columnn_name = columnn_value

WHERE condition(s);

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

----------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black


101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Moto G 5/19/2014 5/22/2014

105 Nokia Lumis 720p 5/26/2014 5/29/2014 Color : Red

---------------------------------------------------------------------------

UPDATE prod_details ps

SET ps.prod_name = 'iphone 5s'

WHERE ps.prod_id = 100;

1 row updated in 0.031 seconds

SELECT *

FROM prod_details ps

WHERE ps.prod_id = 100;

--------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

--------------------------------------------------------------------

100 iphone 5s 5/21/2014 5/24/2014 Color : Black

--------------------------------------------------------------------

--update statement with out condition

--If you try to execute update statement without condition it'll update all the records inside the
table.
UPDATE prod_details ps

SET ps.comments = 'None';

5 row updated in 0.031 seconds

SELECT *

FROM prod_details ps;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 None

101 Samsung Galaxy III 8/20/2014 8/23/2014 None

103 Moto X 5/11/2014 5/24/2014 None

104 Moto G 5/19/2014 5/22/2014 None

105 Nokia Lumis 720p 5/26/2014 5/29/2014 None

----------------------------------------------------------------------

--if your update text contain ' means you can use following metnod (use '')

UPDATE prod_details ps

SET ps.comments = 'Some product''s are not available'

WHERE ps.prod_id = 100;


1 row updated in 0.031 seconds

SELECT *

FROM prod_details ps

WHERE ps.prod_id = 100;

------------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

------------------------------------------------------------------------------------

100 iphone 5s 5/21/2014 5/24/2014 Some product's are not available

------------------------------------------------------------------------------------

DELETE

Syntax:

DELETE FROM table_name

WHERE condition(s);

DELETE FROM prod_details

WHERE prod_id IN (104, 105);

2 row(S) deleted in 0.032 seconds


SELECT *

FROM prod_details ps;

---------------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Some product's are not available

101 Samsung Galaxy III 8/20/2014 8/23/2014 None

103 Moto X 5/11/2014 5/24/2014 None

---------------------------------------------------------------------------------------

DELETE FROM prod_details;

3 row(s) deleted in 0.062 seconds.

SELECT * FROM prod_details;

no rows selected.

DROP TABLE prod_details;

MERGE = Insert + Update


-- will update soon.

Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Data Define Language

Data Definition Language (DDL) statements are used to define the database structure or schema.

Some examples:

CREATE - to create objects in the database.

ALTER - alters the structure of the database.

ADD

RENAME

MODIFY

DROP

DROP - delete objects from the database

TRUNCATE - remove all records from a table,


including all spaces allocated for the records are removed.

COMMENT - add comments to the data dictionary.

RENAME - rename an object.

Creating Table

--------------------------------------------------------------------------

Data Types Size Default Size Explanation

--------------------------------------------------------------------------

NUMBER(P,S) P: 1 to 38 we can store number between 0-9

S: -84 to 127

VARCHAR2 4000 Bytes we can store 0-9, a-z, A-Z and special characters

CHAR 2000 Bytes 1

DATE 7 Used to store Date

TIMESTAMP Includes year, month, day, hour, minute, and seconds.

LONG 2 GB Only one long column is allowed in a table.

We can't use this column in ORDER BY clause.

CLOB 4 GB Character Large Object

BLOB Binary Larger Object

--------------------------------------------------------------------------

CREATE

ALTER : ADD RENAME MODIFY DROP RENAME

RENAME
DROP

TRUNCATE

--creating table

CREATE TABLE friends_details_tb

Name VARCHAR2(30) ,

Phone NUMBER(10) ,

Gender CHAR ,

dob DATE ,

other_details LONG ,

make_dtm TIMESTAMP

);

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE
OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

-----------------------------

--maximum you can keep 255 columns in a table

ALTER : Colum level operations

ADD RENAME MODIFY DROP

ADD : Used to add a column after the table hase been created

ALTER TABLE friends_details_tb

ADD email VARCHAR2(30);

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)
DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

EMAIL VARCHAR2(30)

-----------------------------

--adding multiple columns by using single ALTER statement

SYNTAX

ALTER TABLE friends_details_tb

ADD (

column_1 Data_type(size),

column_2 Data_type(size),

column_3 Data_type(size),

column_4 Data_type(size)

);

RENAME : Used to Rename a column

ALTER TABLE friends_details_tb

RENAME COLUMN email TO email_id;


DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

MODIFY : Used to change the data type or size of the data type.

ALTER TABLE friends_details_tb

MODIFY other_details CLOB;

DESC friends_details_tb;

-----------------------------
NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS CLOB

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

--Modifying multiple columns at a time

ALTER TABLE friends_details_tb

MODIFY ( column_name_1 old_datatype(new_size),

column_name_2 new_datatype(old_size),

column_name_3 new_datatype(new_size)

);

DROP : Used to drop the column after the table has been created.

ALTER TABLE friends_details_tb

DROP COLUMN other_details;


DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

RENAME : Used to Rename a particular table.

SYNTAX

RENAME old_table_name TO new_table_name;

RENAME friends_details_tb TO fnd_det;

DESCRIBE fnd_det;
-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

TRUNCATE : Used to remove the entire content of the table (not a structure)

SYNTAX

TRUNCATE TABLE table_name;

TRUNCATE TABLE fnd_det;

DROP : Used to drop the tabel (Data + stucture of the table get removed from the database )

DROP TABLE fnd_det;


*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Statements in Oracle

Data Definition Language (DDL)

DDL statements are used to define the database structure or schema. Some examples:

CREATE - to create objects in the database

ALTER - alters the structure of the database

ADD

RENAME

MODIFY

DROP

DROP - delete objects from the database

TRUNCATE - remove all records from a table,

including all spaces allocated for the records are removed

RENAME - rename an object


Data Manipulation Language (DML)

DML statements are used for managing data within schema objects. Some examples:

INSERT - insert data into a table

UPDATE - updates existing data within a table

DELETE - deletes all records from a table, the space for the records remain

MERGE - UPSERT operation (insert or update)

Data Control Language (DCL)

DCL statements. Some examples:

GRANT - gives users access privileges to database

REVOKE - withdraw access privileges given with the GRANT command

Transaction Control (TCL)

TCL statements are used to manage the changes made by DML statements. It allows
statements to be grouped together into logical transactions.

COMMIT - save work done


SAVEPOINT - identify a point in a transaction to which you can later roll back

ROLLBACK - restore database to original since the last COMMIT

Posted 28th May 2014 by Unknown

0 Add a comment

MAY

19

DECODE and CASE statement

CREATE TABLE students (

roll_no NUMBER(4) ,

Name VARCHAR2(30) ,

dept_cd VARCHAR2(20) ,

total_marks NUMBER(3)

);

BEGIN

INSERT INTO students VALUES (2000,'Rahul','CSE',480);

INSERT INTO students VALUES (2001,'Bala','IT', 390);


INSERT INTO students VALUES (2002,'Ramesh','CSE',250);

INSERT INTO students VALUES (2003,'Karthi','EEE',185);

INSERT INTO students VALUES (2004,'Ravi','IT',345);

END;

SELECT * FROM students;

DECODE

Decode is a function. Its a Oracle one.

Works like IF-THEN-ELSE.

You can use DECODE only in SELECT clause.

In DECODE you can include 255 things include Exep, search , result and default value.

Example

SELECT roll_no,

NAME,

dept_cd,

DECODE(dept_cd,

'CSE',

'Computer Science and Engineering',

'IT',

'Information Technology',

'Default Value') AS "DEPARTMENT NAME"


FROM students;

Sample Output

------------------------------------------------------------

ROLL_NO NAME DEPT_CD DEPARTMENT NAME

------------------------------------------------------------

2000 Rahul CSE Computer Science and Engineering

2001 Bala IT Information Technology

2002 Ramesh CSE Computer Science and Engineering

2003 Karthi EEE Default Value

2004 Ravi IT Information Technology

------------------------------------------------------------

CASE

CASE is an expression. Its a ANSI standard.

Compare to DECODE case will be more faster.

Example

SELECT roll_no,

NAME,

dept_cd,

total_marks,

CASE
WHEN total_marks > 500 THEN

'A Grade'

WHEN total_marks > 400 THEN

'B Grade'

WHEN total_marks > 300 THEN

'C Grade'

ELSE

'U Grade'

END AS "GRADE"

FROM students;

-----------------------------------------------

ROLL_NO NAME DEPT_CD TOTAL_MARKS GRADE

-----------------------------------------------

2000 Rahul CSE 480 B Grade

2001 Bala IT 390 C Grade

2002 Ramesh CSE 250 U Grade

2003 Karthi EEE 185 U Grade

2004 Ravi IT 345 C Grade

-----------------------------------------------

Interview Questions:

What is DECODE?

What is CASE?
Difference between CASE and DECODE? Which one is faster?

Posted 19th May 2014 by Unknown

0 Add a comment

MAY

19

Sub Query

Query with in another query

1. Single Row sub query

2. Multi row Sub query

select * from employees;

Want to fetch the person Who are all getting salary more than Neena's salary ?

Neena's Salary : 17000

Select First_name, salary


From Employees

Where salary > 17000;

--change in Neena's salary won't work for the above query.

Select salary From Employees

Where First_name = 'Neena';

Sub Query :

Select First_name, salary

From Employees

Where salary > (

Select salary From Employees

Where First_name = 'Neena'

);

Select * from employees;

Select salary From Employees

Where First_name = 'Alexander';


Sub Query Returns one value it is called as Single row sub query

Sub Query Returns more than one value it is called as Multi row sub query

Single row sub query operators :

> < >= <= = <>

Multiple Row Sub query operators :

IN ALL ANY

Who are all getting salary more than the average salary?

Select

First_name,

Salary

From

Employees

WHERE

Salary > (

SELECT Round(avg(salary),0)

FROM Employees
);

Multiple Row Sub query (In ANY ALL)

Select First_name,Department_id, salary

From Employees

Where salary in(

Select Salary From Employees

Where First_name = 'Alexander'

);

Any : Minimum Value will be taken (3100)

Select First_name,Department_id, salary

From Employees

Where salary > ANY(

Select Salary From Employees

Where First_name = 'Alexander'

);

All : Maximum Value will be taken (9000)

Select First_name,Department_id, salary

From Employees
Where salary > All(

Select Salary From Employees

Where First_name = 'Alexander'

);

We can use sub query in all the classes except Group by and order by class.

Select

From

Where

-----------Group by

having

-----------Order by

SELECT

( Select Count(*) from Employees Where Department_id = 90 )Executive,

( Select Count(*) from Employees Where Department_id = 60 ) IT,

( Select Count(*) from Employees Where Department_id = 10 ) Administration,

( Select Count(*) from Employees Where Department_id = 100) Finance

FROM

Dual;

Select Min(salary) From Employees;


Select Min(salary) from

Select * from Employees

Where Department_id = 60

);

What is INLINE VIEW?

If u use sub query in From it is call it is as INLINE VIEW.

Intermediate result set

Correlated sub query

SELECT employee_number, name

FROM employees Bob

WHERE salary > (

SELECT AVG(salary)

FROM employees

WHERE department = Bob.department

);

Posted 19th May 2014 by Unknown


0 Add a comment

Loading

Dynamic Views theme. Powered by Blogger.owered by Blogger.

Oracle sql & Pl/sql

search

Home Sql and pl/sql Sql Interview Questions

JUL

20

INLINE view in Oracle with 12c New Features

Named sub Query in FROM clause is call it as INLINE VIEW.

Oracle process a inline view faster than sub query

Inline View in Oracle

--Query to display all the employees who are all getting salary more than their department
average salary

SELECT First_name

, last_name
, salary

, department_id

FROM employees a , ( SELECT b.department_id

, AVG(b.salary) avg_sal

FROM employees b

GROUP BY b.department_id

)b

WHERE a.department_id = b.department_id

AND a.salary > b.avg_salary;

Display all the customer who have placed more number of orders by using INLINE view

CREATE TABLE customer_order_det_tb

( custm_id NUMBER ,

custm_nm VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

ttl_amt NUMBER(7,2)

);

BEGIN

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '11-Jul-15' , 45000.00);

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '14-Jul-15' , 27000.00);

INSERT INTO customer_order_det_tb VALUES(101, 'Raja' , '13-Jul-15' , 17000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 34000.00);


INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 38000.00);

COMMIT;

END;

SELECT c.*

FROM customer_order_det_tb c;

--------------------------------------------

custm_id custm_nm order_dt ttl_amt

--------------------------------------------

100 Murugappan 7/11/2015 45000.00

100 Murugappan 7/14/2015 27000.00

101 Raja 7/13/2015 17000.00

102 Ramesh 7/15/2015 34000.00

102 Ramesh 7/15/2015 38000.00

--------------------------------------------

--Writing a Quer to display all the customer who have placed maximum number of order

--Query #1 for inline view

SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm
ORDER BY total_odr DESC;

--------------------------------

custm_id custm_nm total_odr

--------------------------------

100 Murugappan 2

102 Ramesh 2

101 Raja 1

--------------------------------

--Query #2 for inline view

SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm;

----------

total_odr

----------

----------

Inline view to find all the customers who have placed maximum number of orders

/****************************************
Syntax

SELECT * FROM <query1> x, <query2> y

WHERE contition;

****************************************/

SELECT query1.* FROM

( SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC

) query1,

( SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm

) query2

WHERE query1.total_odr = query2.total_odr;

-------------------------------

custm_id custm_nm total_odr

-------------------------------

100 Murugappan 2

102 Ramesh 2

-------------------------------
DROP TABLE customer_order_det_tb;

--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT

SELECT first_name, salary

FROM ( SELECT first_name, salary

FROM employees e

WHERE job_id NOT IN ('SALESMAN','PRESIDENT')

ORDER BY salary DESC

WHERE ROWNUM < 4;

New Oracle 12c Inline view Syntax

LATERAL clause for In-line views

Allows for columns in the inline view to be accessed!!

Example :

--in 11g

SELECT * FROM employees e, (

SELECT *
FROM departments d

WHERE e.department_id = d.department_id);

ORA-0090: "E"."DEPARTMENT_ID": Invalid Identifier

--in 12c

SELECT * FROM employees e, LATERAL(

SELECT *

FROM departments d

WHERE e.department_id = d.department_id

);

--in 11g

WITH t

AS

( SELECT LEVEL a

FROM dual

CONNECT BY LEVEL <= 30)

SELECT *

FROM t, (SELECT *

FROM employees

WHERE department_id = t.a

);
ORA-00904: "T"."A": invalid Identifier

--in 12c

WITH t

AS

(SELECT LEVEL a FROM dual CONNECT BY LEVEL <= 30)

SELECT * FROM t,

LATERAL(SELECT *

FROM employees

WHERE department_id = t.a);

Hope you have enjoyed this little article

Feed backs are always Welcome :) (:

Posted 20th July 2015 by Unknown

0 Add a comment

JAN

23

Salary Related Questions in Oracle


--creating table

CREATE TABLE employee_data

eid NUMBER(4),

ename VARCHAR2(30),

depno NUMBER(3),

salary NUMBER(8)

);

BEGIN

--Inserting records

INSERT INTO employee_data VALUES(1000,'Name01',90,30000);

INSERT INTO employee_data VALUES(1001,'Name02',90,6000);

INSERT INTO employee_data VALUES(1002,'Name03',90,23000);

INSERT INTO employee_data VALUES(1003,'Name04',60,35000);

INSERT INTO employee_data VALUES(1004,'Name05',60,60000);

INSERT INTO employee_data VALUES(1005,'Name06',60,30000);

INSERT INTO employee_data VALUES(1006,'Name07',80,36000);

INSERT INTO employee_data VALUES(1007,'Name08',80,29000);

INSERT INTO employee_data VALUES(1008,'Name09',80,37000);

INSERT INTO employee_data VALUES(1009,'Name10',80,41000);


COMMIT;

END;

SELECT * FROM employee_data

ORDER BY salary DESC;

--query to find maximum salary from employee_data table

SELECT MAX(salary) FROM employee_data;

--query to find minimum salary from employee_data table

SELECT MIN(salary) FROM employee_data;

--query to find second maximum salary from employee_data table

SELECT MAX(salary)

FROM employee_data

WHERE salary NOT IN (SELECT MAX(salary)

FROM employee_data);

--query to select 5th maximum salary


SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= 5);

--query to select nth maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= &n);

--query to select all the details of the employee whose getting nth maximum salary

SELECT *

FROM (SELECT emp.*,

rownum rn

FROM (SELECT *

FROM employee_data
ORDER BY salary DESC) emp)

WHERE rn = 9;

--same query using row_numbr( ) function

SELECT *

FROM (SELECT emp.*,

row_number() over(ORDER BY salary) rank

FROM employee_data emp)

WHERE rank = 9;

--same query using rank( ) function

SELECT *

FROM (SELECT emp.*,

rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--same query using dense_rank( ) function

SELECT *

FROM (SELECT emp.*,

dense_rank() over(ORDER BY salary DESC) rank


FROM employee_data emp)

WHERE rank = 4;

--query to display display maximum salary in all the department

SELECT e.depno "Department id",

MAX(salary) "Maximum Salary"

FROM employee_data e

GROUP BY e.depno;

--query to display all the employees who are all getting salary more than average salary of the
company

SELECT e.* FROM employee_data e

WHERE salary > (SELECT AVG(salary) FROM employee_data);

--query to display all the employees who are all getting salary more than their department
average salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees
WHERE department_id = OUT.department_id);

--query to display all the employees who are all getting salary more than their manager salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE employee_id = OUT.manager_id);

Documented By : Murugappan Annamalai

Posted on : 23-Jan-15 16:34:00 IST.

Hope you have enjoyed this little article

Feed backs are always welcome :)

Posted 23rd January 2015 by Unknown


7 View comments

JAN

22

Why prefer COALESCE over NVL

Documented By : Nimish Garg

I prefer using "COALESCE" over "NVL" is some of the scenarios. Last week One of my friend
asked me what is the advantage of using "COALESCE" where we can simply use "NVL". I simply
gave him the reply from Oracle Docs i.e. NVL lets you replace null (returned as a blank) with a
string in the results of a query and COALESCE returns the first non-null expr in the expression list.
Oracle Database uses short-circuit evaluation with "COALESCE".

He replied that he knows the difference, he knows that "COALESCE" can take multiple arguments
and so on. He was more interested in understanding "short-circuit evaluation" of "COALESCE"
and the scenarios where I prefer using "COALESCE" over "NVL".

To make him understand I created following function which takes One second in every execution
and simply returns '--null--' and executed 2 very similar queries one with NVL and other with
COALESCE.

SQL> create or replace function f_null return varchar2

2 is

3 begin

4 dbms_lock.sleep(1);

5 return '--null--';

6 end;

7 /
Function created.

Following are the queries which I used to demonstrate that NVL evaluates both arguments even
if the second argument is not used and COALESCE uses short-circuit evaluation i.e. it only
evaluates the arguments only if they are needed.

SQL> select e.empno, e.ename ename, nvl(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING


7369 SMITH FORD

7839 KING --null--

14 rows selected.

Elapsed: 00:00:14.01

SQL> select e.empno, e.ename ename, coalesce(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING


7369 SMITH FORD

7839 KING --null--

14 rows selected.

Elapsed: 00:00:01.01

Here we can see easily that the first query with NVL took 14+ seconds, one second for each
record even if the "f_null" value was used only in one record. On the contrary as mentioned in
Oracle Documentation "COALESCE" uses its "short-circuit evaluation" and "f_null" was called
only once and so second query took only One Second. "COALESCE" is certainly use less resources
than NVL.

Posted 22nd January 2015 by Unknown

0 Add a comment

DEC

21

Constraints

It Enforce Rule On Table


We can create constraint at the time of Creating Table

1. Column Level Declaration

2. Table Level Declaration

1. We can provide own name.

Format : [part_of_project_name-table_name-column_name-constraint_type]

Example : gmind_emp_id_pk _uk _ck _f

2. system name name

Format : sys_cn

Example : SYS_C405323

We can create constraint after the table has been created

Types

Primary Key

Not allowed Null value


Not allowed you to enter duplicate value

Ex : Employee_id, Student_id

Unique Key

allowed Null value

Not allowed you to enter duplicate value

Ex : Contact_no, email

Foreign Key

It will allowed you to enter NULL and Duplicate value.

c1(pk) : 1 2 3

c2(f) : 1 1 2 3 4 Not allowed

Allowed you to enter duplicate value and null value

Not Null

It will not allowed you to enter null value

Check
You can check your own condition

Simple Table for understanding

------------------------------------

Duplicate NULL

------------------------------------

Primary Key X X

Unique Key X Allowed

Foreign Key Allowed Allowed

------------------------------------

creating table with all constraint type

Create table my_stu_details

S_id Number(2),

S_name Varchar2(30) Not Null, --SYS_Cn

s_mail Varchar2(30),

s_gender char(1),

s_did Number(3),

Constraint my_stu_sid_pk PRIMARY KEY (s_id),


constraint my_stu_mail_uk UNIQUE (s_mail) ,

Constraint my_stu_gen_ck CHECK (s_gender IN ('M', 'F', 'm', 'f')),

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

);

DESC my_stu_details;

------------------------------------

Name Type Nullable

------------------------------------

S_ID NUMBER(2)

S_NAME VARCHAR2(30)

S_MAIL VARCHAR2(30) Y

S_GENDER CHAR(1) Y

S_DID NUMBER(3) Y

------------------------------------

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name1' , 'name1@gmail.com' , 'm' , 60 );

Select * from my_stu_details;


Validating Primary Key

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-00001: unique constraint (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (NULL, 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-01400: cannot insert NULL into (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (2 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

Validating NOT NULL Constraint


Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , NULL , 'name3@gmail.com' , 'F' , 80 );

ORA-01400: cannot insert NULL into ("HR"."MY_STU_DETAILS"."S_NAME")

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , 'Name3' , 'name3@gmail.com' , 'F' , 80 );

Select * from my_stu_details;

Validating Unique Key Constraint

--Duplicate Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , 'name3@gmail.com' , 'F' , 80 );

ORA-00001: unique constraint (HR.MY_STU_MAIL_UK) violated


--Null Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , null , 'M' , 70 );

Select * from my_stu_details;

Validating Check constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'j' , 70 );

ORA-02290: check constraint (HR.MY_STU_GEN_CK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'M' , 70 );

Select * from my_stu_details;

Validating Foreign Key


Select * from Departments;

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 3 );

ORA-02291: integrity constraint (HR.MY_STU_DID_FK) violated - parent key not found

Departments table : parent table

my_stu_details : Child table

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

--------------------------------------------------------

s_id s_name s_mail s_gender s_did

--------------------------------------------------------
1 name1 name1@gmail.com m 60

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 M 70

5 Name5 name5@gmail.com M 70

6 Name6 name6@gmail.com F 90

--------------------------------------------------------

Deleting the Primary key value which is referred by Foreign Key

Select * from Departments;

DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID

------------------------------------------------------------

60 IT 103 1400 <---- Delete

-- don't execute this query

--Delete From Departments

--Where Department_id = 60;


1) ON DELETE SET NULL

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

1 name1 name1@gmail.com m -

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

2) ON DELETE SET CASCADE

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------
Syntax

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE CASCADE

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE SET NULL

Constraint Related Data Dictionary Table information.

To view constraint Information

SELECT c.owner,

c.constraint_name,

c.constraint_type,

c.table_name,

c.r_constraint_name,

c.status

FROM user_constraints c

WHERE c.table_name = 'MY_STU_DETAILS';

------------------------------------------------------------------------------------
owner constraint_name constraint_type table_name r_constraint_name status

------------------------------------------------------------------------------------

HR SYS_C004023 C MY_STU_DETAILS ENABLED

HR MY_STU_GEN_CK C MY_STU_DETAILS ENABLED

HR MY_STU_SID_PK P MY_STU_DETAILS ENABLED

HR MY_STU_MAIL_UK U MY_STU_DETAILS ENABLED

HR MY_STU_DID_FK R MY_STU_DETAILS DEPT_ID_PK ENABLED

------------------------------------------------------------------------------------

To view constraint name with corresponding column name

SELECT * FROM user_cons_columns c

WHERE c.table_name = 'MY_STU_DETAILS';

-------------------------------------------------------------

owner constraint_name table_name column_name position

-------------------------------------------------------------

HR MY_STU_MAIL_UK MY_STU_DETAILS S_MAIL 1

HR MY_STU_SID_PK MY_STU_DETAILS S_ID 1

HR MY_STU_GEN_CK MY_STU_DETAILS S_GENDER

HR SYS_C004023 MY_STU_DETAILS S_NAME

HR MY_STU_DID_FK MY_STU_DETAILS S_DID 1

-------------------------------------------------------------
Creating Composite Primary Key

Creating Primary Key with more than one number of column

ALTER TABLE table_name

ADD CONSTRAINT constraint_name PRIMARY KEY(column1, column_2 , column3);

In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.

creating constraint after the table creation

ALTER TABLE table_name

ADD CONSTRAINT constraint_name CONSTRAINT_TYPE(column_name);

ALTER TABLE table_name

DROP CONSTRAINT constraint_name;

ALTER TABLE table_name

DROP PRIMARY KEY;


To drop related foreign key

ALTER TABLE table_name

DROP PRIMARY KEY CASCADE;

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name;

Disable constraint with related foreign key constraint

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name CASCADE;

ALTER TABLE table_name

ENABLE CONSTRAINT constraint_name;

Interview Questions
What are all the type of constraint available in oracle?

Difference between PRIMARY KEY and UNIQUE key.

Difference between PRIMARY KEY ans FOREIGN KEY.

Difference between UNIQUE key and FOREIGN KEY.

Is it possible to create tow primary key in single table.

Write a syntax to create FOREIGN constraint.

How to create constraint after the table has been created?

How to enable and disable a constraint.

Which data dictionary table contains information about constraints?

Which Data Dictionary table contains information about constraint with corresponding column
name?

What is composite primary key?

Explain ON DELETE CASCADE and ON DELETE SET NULL option.

~Thanks For Reading~

Post your valuable feedback below

Posted 21st December 2014 by Unknown

1 View comments

UnknownMay 22, 2017 at 12:39 AM


good

Reply

DEC

listagg in Oracle 11g

Oracle 11gR2 listagg built-in function allows for many table columns to be displayed within a
single row, a non-first-normal form display

Syntax :

listagg(column_value,'delimiter') WITHIN GROUP(ORDER BY column_name)

--Example 1:

CREATE TABLE test_ins(empid NUMBER,product VARCHAR2(30));

BEGIN

INSERT INTO test_ins VALUES( 101,'pendrive');

INSERT INTO test_ins VALUES( 102,'toy');

INSERT INTO test_ins VALUES( 101,'ipod');

INSERT INTO test_ins VALUES( 102,'hat');

INSERT INTO test_ins VALUES( 103,'cpu');


INSERT INTO test_ins VALUES( 104,'pen');

INSERT INTO test_ins VALUES( 104,'car');

INSERT INTO test_ins VALUES( 104,'mat');

INSERT INTO test_ins VALUES( 105,'tv');

INSERT INTO test_ins VALUES( 106,'laptop');

commit;

END;

SELECT * FROM test_ins;

SELECT empid "Employee",

listagg(product,

',') within

GROUP (ORDER BY empid) "Products"

FROM test_ins

GROUP BY empid;

-->-- Result set --<--


DROP TABLE test_ins;

-->-- Example 2

select department_id "Department id", listagg(first_name,', ') WITHIN GROUP(ORDER BY


employee_id) "Employees"

FROM employees

WHERE department_id IN (10,20,30,60)

GROUP BY department_id;

-->-- Result set --<--

Posted 4th December 2014 by Unknown

0 Add a comment
NOV

Condition and Looping Statement

IF

IF ELSE

Multiple IF ELSE

LOOP

FOR LOOP

WHILE LOOP

create table test_udt(id NUMBER, salary NUMBER);

BEGIN

INSERT INTO test_udt VALUES(001,23000);

INSERT INTO test_udt VALUES(002,43000);

INSERT INTO test_udt VALUES(003,78000);

INSERT INTO test_udt VALUES(004,25000);

INSERT INTO test_udt VALUES(005,26000);

INSERT INTO test_udt VALUES(006,90000);

Commit;
END;

select * from test_udt;

IF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 1;

IF v_salary > 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

END IF;

commit;

END;
/

IF ELSE

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

ELSE

UPDATE test_udt t

SET t.salary = v_salary+20007

WHERE t.id = v_id ;

END IF;

commit;

END;

/
--same example with less number of lines

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

v_salary := v_salary+10005;

ELSE

v_salary := v_salary+20007;

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

/
select * from test_udt;

Multiple IF ELSIF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 3;

IF v_id = 1 THEN

v_salary := 1000;

dbms_output.put_line('1 inside');

ELSIF v_id = 2 THEN

v_salary := 2000;

dbms_output.put_line('2 inside');

ELSIF v_id = 3 THEN

v_salary := 3000;

dbms_output.put_line('3 inside');

ELSIF v_id = 4 THEN


v_salary := 4000;

dbms_output.put_line('4 inside');

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

LOOP

--syntax

LOOP

--statements

--increment

--exit statement

END LOOP;
CREATE TABLE prod_details (pid VARCHAR2(3), pname VARCHAR2(30));

DECLARE

i NUMBER := 1;

x VARCHAR2(3);

BEGIN

LOOP

x := lpad(i,3,'0');

dbms_output.put_line('x value : '|| x);

INSERT INTO prod_details VALUES(i, 'Product '||i);

EXIT WHEN i >900;

i := i+1;

IF MOD(i,100) = 0 THEN

commit;

dbms_output.put_line('commit executed');

END IF;

END LOOP;

END;

SELECT * FROM prod_details ORDER BY 1;

DROP TABLE prod_details;


FOR LOOP

BEGIN

FOR I in 1..5

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

FOR LOOP - Reverse

BEGIN

FOR I in REVERSE 14..50

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

WHILE LOOP

DECLARE

i_val NUMBER:=0;

BEGIN
WHILE (i_val < 11)

LOOP

dbms_output.put_line('The value of I is '||i_val);

i_val := i_val + 1;

END LOOP;

END;

sample output:

The value of I is 0

The value of I is 1

The value of I is 2

The value of I is 3

The value of I is 4

The value of I is 5

The value of I is 6

The value of I is 7

The value of I is 8

The value of I is 9

The value of I is 10

Posted 8th November 2014 by Unknown

0 Add a comment
OCT

21

Bulk Collect

This is used for array fetches

With this you can retrieve multiple rows of data with a single round trip.

This reduces the number of context switches between the pl/sql and sql engines.

You can use bulk collect in both dynamic and static sql.

You can use bulk collect in select, fetch into and returning into clauses.

SQL engine automatically initializes and extends the collections you reference in the bulk
collect clause.

You can fetch into multiple collections with one column each.

You can use the limit clause of bulk collect to restrict the no of rows retrieved.

SELECT * FROM product_details;

-->-- Bulk collect in FETCH INTO --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;


dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Bulk collect in SELECT clause --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

BEGIN

SELECT * BULK COLLECT INTO dta FROM product_details;

FOR i IN dta.FIRST .. dta.LAST LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);


END LOOP;

END;

-->-- LIMIT in Bulk collect --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta LIMIT 30;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

/
-->-- Multiple fetches in INTO clause --<--

SELECT * FROM product_details;

DECLARE

TYPE alldata_typ1 IS TABLE OF product_details.p_id%TYPE;

TYPE alldata_typ2 IS TABLE OF product_details.p_name%TYPE;

dta1 alldata_typ1;

dta2 alldata_typ2;

CURSOR proddt_cur IS

SELECT p_id, p_name FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta1, dta2;

CLOSE proddt_cur;

FOR i IN dta1.FIRST .. dta1.COUNT LOOP

dbms_output.put_line('Department Id : ' || dta1(i));

END LOOP;

FOR i IN dta2.FIRST .. dta2.COUNT LOOP

dbms_output.put_line('Department Name : ' || dta2(i));

END LOOP;
END;

DROP TABLE dep_details;

DROP TABLE product_details;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Ref Cursor

This is unconstrained cursor which will return different types depends upon the user input.

Ref cursors cannot be closed implicitly.

Ref cursor with return type is called strong cursor.

Ref cursor without return type is called weak cursor.

You can declare ref cursor type in package spec as well as body.

You can declare ref cursor types in local subprograms or anonymous blocks.
CREATE OR REPLACE PROCEDURE ref_c_sp(dep_det_c IN OUT SYS_REFCURSOR)

AS

BEGIN

OPEN dep_det_c

FOR

SELECT * FROM dep_details d;

END;

DECLARE

dep_det_c SYS_REFCURSOR;

tab_data dep_details%ROWTYPE;

BEGIN

ref_c_sp(dep_det_c);

LOOP

FETCH dep_det_c INTO tab_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department Name : '|| tab_data.d_name);

END LOOP;

CLOSE dep_det_c;

END;
/*sample output*/

Department Name : Admin

Department Name : HR

Department Name : Sales

Department Name : Marketing

DROP PROCEDURE ref_c_sp;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Cursor

SQL Private work Area where the query get passed and executed.

Types

******

Implicit(SQL)
Explicit

-->-- advanced cursor types --<--

Parametrized Cursor

Ref Cursor

Implicit

********

ORACLE implicitly opens a cursor to process each SQL statement not associated with an
explicitly declared cursor.

PL/SQL lets you refer to the most recent implicit cursor as the SQL” cursor. So, although you
cannot use the OPEN,

FETCH, and CLOSE statements to control an implicit cursor, you can still use cursor attributes to
access information

about the most recently executed SQL statement.

Cursor Stages

**************

OPEN cursor_name

FETCH (with in loop)

CLOSE cursor_name

Explicit

The set of rows returned by a query can consist of zero, one, or multiple rows,
depending on how many rows meet your search criteria. When a query returns multiple rows,

you can explicitly define a cursor to process the rows. You use three commands to control the
cursor

Cursor Attributes

*****************

%FOUND

%NOTFOUND

%ISOPEN

%ROWCOUNT

%BULK_ROWCOUNT --<-- used to handle error while using bulk collection.

%BULK_EXCEPTIONS --<-- used to handle error while using bulk collection.

Cursor Declaration

DECLARE

CURSOR <cursor_name>

IS

<SELECT statement>

BEGIN

--> some stmt

END;

Cursor Loop
Loop

While Loop

For Loop

Cursor Clauses

Return

For update

Where current of

Bulk collect

-->-- creating table

create table product_details

p_id NUMBER,

p_name VARCHAR2(30),

p_order_dt DATE

);

-->-- Inserting data

BEGIN

FOR i IN 1 .. 75 LOOP

INSERT INTO product_details VALUES (i, 'prod_name_' || i, SYSDATE + i);


END LOOP;

commit;

END;

-->-- selecting data

SELECT * FROM product_details;

---------------------------------------------

p_id p_name p_order_dt

---------------------------------------------

1 prod_name_1 10/11/2014 3:48:32 PM

2 prod_name_2 10/12/2014 3:48:32 PM

3 prod_name_3 10/13/2014 3:48:32 PM

4 prod_name_4 10/14/2014 3:48:32 PM

5 prod_name_5 10/15/2014 3:48:32 PM

6 prod_name_6 10/16/2014 3:48:32 PM

7 prod_name_7 10/17/2014 3:48:32 PM

8 prod_name_8 10/18/2014 3:48:32 PM

9 prod_name_9 10/19/2014 3:48:32 PM

10 prod_name_10 10/20/2014 3:48:32 PM

11 prod_name_11 10/21/2014 3:48:32 PM

12 prod_name_12 10/22/2014 3:48:32 PM

13 prod_name_13 10/23/2014 3:48:32 PM


14 prod_name_14 10/24/2014 3:48:32 PM

15 prod_name_15 10/25/2014 3:48:32 PM

16 prod_name_16 10/26/2014 3:48:32 PM

17 prod_name_17 10/27/2014 3:48:32 PM

18 prod_name_18 10/28/2014 3:48:32 PM

19 prod_name_19 10/29/2014 3:48:32 PM

20 prod_name_20 10/30/2014 3:48:32 PM

---------------------------------------------

----------------------------------------------

Implicit Cursor

----------------------------------------------

--will update soon

----------------------------------------------

Explicit Cursor

----------------------------------------------

**********************************************

Processing cursor data by using LOOP

**********************************************

DECLARE
all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND; --<-- if next record not found means control will
come out from the loop

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )


Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

EXIT WHEN prod_detail_cur%FOUND; --<-- if next record found means control will come
out from the loop

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/
Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');


ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor Already closed

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;


BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

-->-- CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )


Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor closed

**********************************************

Processing cursor data by using WHILE LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

OPEN prod_detail_cur;

FETCH prod_detail_cur

INTO all_data;

WHILE prod_detail_cur%FOUND LOOP


dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

FETCH prod_detail_cur

INTO all_data;

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

************************************************************

Processing cursor data by using FOR LOOP - CURSOR FOR LOOP

************************************************************

DECLARE

--cursor declaration

CURSOR prod_detail_cur IS
SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

FOR i IN prod_detail_cur

LOOP

dbms_output.put_line('Product id : ' || i.p_id ||

' Product Name : ' || i.p_name ||

' ( Orderd on : ' || TRIM(i.p_order_dt) || ' )');

END LOOP;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

Parameterized Cursor

*********************

This was used when you are going to use the cursor in more than one place with different
values for the same where clause.
Cursor parameters must be in mode.

Cursor parameters may have default values.

The scope of cursor parameter is within the select statement.

CREATE TABLE dep_details(d_id NUMBER,d_name VARCHAR2(30), location_id NUMBER);

BEGIN

INSRT INTO dep_details VALUES(001,'Admin',1010);

INSRT INTO dep_details VALUES(002,'HR',1010);

INSRT INTO dep_details VALUES(003,'Sales',1020);

INSRT INTO dep_details VALUES(004,'Marketing',1020);

commit;

END;

SELECT * FROM dep_details;

----------------------------

d_id d_name location_id

----------------------------

1 Admin 1010

2 HR 1010

3 Sales 1020

4 Marketing 1020
----------------------------

DECLARE

-->--Declaring parameterized cursor

CURSOR dep_det_c(p_location_id NUMBER) IS

SELECT * FROM dep_details d WHERE d.location_id = p_location_id;

all_data dep_details%ROWTYPE;

BEGIN

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

OPEN dep_det_c(1010);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

-->-- opening same cursor with different input value

OPEN dep_det_c(1020);
LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

END;

/*sample output*/

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 1 Department Name : Admin

Department id : 2 Department Name : HR

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 3 Department Name : Sales

Department id : 4 Department Name : Marketing

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Posted 21st October 2014 by Unknown

0 Add a comment
OCT

21

Handling Exception

Error Handling in oracle

ERROR

Any departure from the expected behavior of the system or program,

which stops the working of the system is an error.

Types : compile time error

Run time error

EXCEPTION

Any error or problem which one can handle and continue to work normally.

Handling Exception

When exception is raised, control passes to the exception section of the block.

i.e. EXCEPTION

WHEN name_of_exception THEN


Types : Pre Defined Exceptions

User Defined Exceptions

Predefined Exception

*********************

Oracle has predefined several exceptions that correspond to the most common oracle errors.

------------------------------------------------------------------------

Exception Oracle Error SQL Code Value

------------------------------------------------------------------------

ZERO_DIVIDE ORA-01476 -1476

NO_DATA_FOUND ORA-01403 +100

DUP_VAL_ON_INDEX ORA-00001 -1

TOO_MANY_ROWS ORA-01422 -1422

VALUE_ERROR ORA-06502 -6502

CURSOR_ALREADY_OPEN ORA-06511 -6511

OTHERS

------------------------------------------------------------------------

-->-- ZERO_DIVIDE --<--

Your program attempts to divide a number by zero.


DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN ZERO_DIVIDE THEN

dbms_output.put_line('Divisor is equal to zero');

END;

-->-- NO_DATA_FOUND --<--

Single row SELECT returned no rows or your program referenced a deleted element in a nested
table

or an uninitialized element in an associative array (index-by table).

CREATE TABLE test_tb(id NUMBER PRIMARY KEY);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN NO_DATA_FOUND THEN


dbms_output.put_line('There is no data inside the table');

END;

-->-- DUP_VAL_ON_INDEX --<--

A program attempted to insert duplicate values in a column that is constrained by a unique


index.

INSERT INTO test_tb VALUES (1);

INSERT INTO test_tb VALUES (2);

commit;

BEGIN

INSERT INTO test_tb VALUES (2);

EXCEPTION

WHEN DUP_VAL_ON_INDEX THEN

dbms_output.put_line('Duplicate values are not allowed');

END;

-->-- TOO_MANY_ROWS --<--

Single row SELECT returned multiple rows.


DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN TOO_MANY_ROWS THEN

dbms_output.put_line('Query returning more than one row');

END;

DROP TABLE test_tb;

-->-- VALUE_ERROR --<--

An arithmetic, conversion, truncation, or size constraint error occurred.

DECLARE

num1 NUMBER(2);

BEGIN

num1 := 345;

EXCEPTION

WHEN VALUE_ERROR THEN

dbms_output.put_line('check the size of the variable');

END;
-->-- CURSOR_ALREADY_OPEN --<--

A program attempted to open an already opened cursor.

CREATE TABLE emp(id NUMBER, name VARCHAR2(30));

BEGIN

INSERT INTO emp VALUES(1,'Name1');

INSERT INTO emp VALUES(2,'Name2');

INSERT INTO emp VALUES(3,'Name3');

INSERT INTO emp VALUES(4,'Name4');

COMMIT;

END;

SELECT * FROM emp;

DECLARE

cursor emp_c IS

SELECT * FROM emp;

all_data emp%ROWTYPE;

BEGIN
OPEN emp_c;

OPEN emp_c;

NULL;

CLOSE emp_c;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

END;

DROP TABLE emp;

-->-- OTHERS --<--

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

WHEN OTHERS THEN

dbms_output.put_line('Some other error ' || SQLERRM);

END;
User Defined Exception

**********************

A user-defined exception is an error that is defined by the programmer.

User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,

exceptions have a type EXCEPTION and scope.

DECLARE

v_gender CHAR := '&gender';

gender_ex EXCEPTION;

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE gender_ex;

END IF;

dbms_output.put_line('Gender : '||v_gender);

EXCEPTION

WHEN gender_ex THEN

dbms_output.put_line('Please Enter valid gender');

END;

create table test_insert (id NUMBER, Name VARCHAR2(30));


DECLARE

abort_ex EXCEPTION;

BEGIN

FOR i IN 1..100

LOOP

BEGIN

IF mod(i,10)=0 THEN

RAISE abort_ex;

END IF;

INSERT INTO test_insert VALUES(i, 'Name'||i);

EXCEPTION

WHEN abort_ex THEN

NULL;

END;

END LOOP;

COMMIT;

END;

SELECT * FROM test_insert;

DROP TABLE test_insert;

SQLERRM and SQLCODE


********************

SQLCODE returns the current error code, and SQLERRM returns the current error message
text;

For user-defined exception SQLCODE returns 1 and SQLERRM returns “user-defined


exception”.

SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.

CREATE TABLE test_tb (id NUMBER);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

dbms_output.put_line(v_id);

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('SQLERRM : ' || SQLERRM);

dbms_output.put_line('SQLCODE : ' || SQLCODE);

END;

/*sample output*/

SQLERRM : ORA-01403: no data found

SQLCODE : 100
DROP TABLE test_tb;

PRAGMA EXCEPTION_INIT

*********************

Using this you can associate a named exception with a particular oracle error.

This gives you the ability to trap this error specifically, rather than via an OTHERS handler.

Syntax:

PRAGMA EXCEPTION_INIT(exception_name, oracle_error_number);

DECLARE

v_result NUMBER;

PRAGMA EXCEPTION_INIT(Invalid, -1476);

BEGIN

SELECT 453 / 0 INTO v_result FROM dual;

dbms_output.put_line('Result : ' || v_result);

EXCEPTION

WHEN INVALID THEN

dbms_output.put_line('Invalid Exception');

END;
RAISE_APPLICATION_ERROR

************************

You can use this built-in function to create your own error messages, which can be more
descriptive than named exceptions.

Error Number :

Oracle Error Range : From -00000 to -19999

User Error Range : From -20000 to -20999

DECLARE

v_gender CHAR := '&gender';

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE_APPLICATION_ERROR(-20003, 'Enter valid gender');

END IF;

dbms_output.put_line('Gender : ' || v_gender);

END;

Posted 21st October 2014 by Unknown


1 View comments

RajmohanMarch 13, 2018 at 6:49 AM

How to get the two table data without using Joins and sub query,union?

Reply

OCT

Package

1. You can groups logical related subprogram (procedures and functions)

2. It consist of two parts

I) specification

II) Body

3. It allows the oracle server to read multiple object in to a memory once

4. You can declare global variable,cursor, user define exeption

5. Overloading

6. we can't create anonyms block inside the package


create table err_log(sno NUMBER, u_name VARCHAR2(30), error_msg CLOB, hap_tm
TIMESTAMP);

select * from err_log;

--stand alone procedure

CREATE OR REPLACE PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id


%TYPE) IS

v_salary employees.salary%TYPE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT salary,

first_name

INTO v_salary,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line('Salary of ' || v_first_name || ' is ' || v_salary);

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES
(1,

USER,

v_error,

systimestamp);

commit;

END emp_sal_sp;

BEGIN

-- Call the procedure

emp_sal_sp(p_employee_id => :p_employee_id);

END;

CREATE OR REPLACE PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id


%TYPE) IS

v_hire_date DATE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT hire_date,

first_name

INTO v_hire_date,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;


dbms_output.put_line(v_first_name || ' hired on ' || to_char(v_hire_date,'month ddth,
yyyy'));

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_hdt_sp;

BEGIN

-- Call the procedure

emp_hdt_sp(p_employee_id => :p_employee_id);

END;

create or replace function sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER

IS

v_c NUMBER;
BEGIN

v_c := p_a + p_b;

RETURN v_c;

END;

--Specification Part

CREATE OR REPLACE PACKAGE emp_pkg

IS

PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id%TYPE);

PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id%TYPE);

FUNCTION sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER;

END emp_pkg ;

--Body Part

CREATE OR REPLACE PACKAGE BODY emp_pkg

IS
PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id%TYPE) IS

v_salary employees.salary%TYPE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT salary,

first_name

INTO v_salary,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line('Salary of ' || v_first_name || ' is ' || v_salary);

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_sal_sp;
PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id%TYPE) IS

v_hire_date DATE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT hire_date,

first_name

INTO v_hire_date,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line(v_first_name || ' hired on ' || to_char(v_hire_date,'month ddth,


yyyy'));

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_hdt_sp;
FUNCTION sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER

IS

v_c NUMBER;

BEGIN

v_c := p_a + p_b;

RETURN v_c;

END;

END emp_pkg;

A package specification can exist without a package body, but

a package body can't exist without a package specification.

--Executing procedure inside the package

BEGIN

emp_pkg.emp_sal_sp(120);

END;

--Executing function inside the package


SELECT emp_pkg.sum_fn(23,567) FROM dual;

-- You can declare global variable,cursor, user define exeption

create or replace package all_detail

as

PROCEDURE emp2sal (a IN NUMBER);

PROCEDURE emp2exep (a IN NUMBER);

FUNCTION add2num (a IN NUMBER, b IN NUMBER)

RETURN NUMBER;

c NUMBER(8); --global declaration

abort_ex EXCEPTION; --global exception declaration

CURSOR emp_rec --global cursor declaration

IS

SELECT first_name, salary, hire_date, department_id

FROM employees;

End all_detail;

create or replace package body all_detail


as

PROCEDURE emp2sal (a IN NUMBER)

AS

BEGIN

SELECT salary

INTO c

FROM Employees

WHERE Employee_id = a;

Dbms_output.put_line('Salary of Employee ' || a || ' is ' || c);

EXCEPTION

WHEN no_data_found THEN

Dbms_output.put_line('Please enter valid id');

END emp2sal;

PROCEDURE emp2exep (a IN NUMBER)

AS

BEGIN

SELECT Round(Months_between(sysdate,hire_date)/12)

INTO c

FROM Employees
WHERE Employee_id = a;

Dbms_output.put_line( c || ' Years');

EXCEPTION

WHEN no_data_found THEN

Dbms_output.put_line('Please enter valid id');

END emp2exep;

FUNCTION add2num (a IN NUMBER, b IN NUMBER)

RETURN NUMBER

AS

BEGIN

c := a+b;

RETURN C;

END;

End all_detail;

/*Declaring a Bodiless Package */

CREATE OR REPLACE PACKAGE global_constant

IS
mile_2_kilo CONSTANT NUMBER := 1.6093;

kilo_2_mile CONSTANT NUMBER := 0.6214;

yard_2_meter CONSTANT NUMBER := 0.9144;

meter_2_yard CONSTANT NUMBER := 1.0936;

END global_constant;

BEGIN

DBMS_OUTPUT.PUT_LINE('20 miles = ' || 20*global_constant.mile_2_kilo||' km');

END;

/*Forward Declaration in package */

DECLARE

PROCEDURE P2; -- forward declaration

PROCEDURE P3;

PROCEDURE P1 IS

BEGIN

dbms_output.put_line('From procedure p1');

p2;

END P1;

PROCEDURE P2 IS
BEGIN

dbms_output.put_line('From procedure p2');

p3;

END P2;

PROCEDURE P3 IS

BEGIN

dbms_output.put_line('From procedure p3');

END P3;

BEGIN

p1;

END;

sample output:

From procedure p1

From procedure p2

From procedure p3

Drop package package_name;

Drop package body package_name;


SELECT text FROM user_source u

WHERE u.name = 'EMP_PKG';

Interview Questions:

What is package?

Advantage of package

Is it possible to create package body with out package specification?

what is package overloading?

what is forward declaration in package?

which data dictionary table contain source code of package?

How to declare global variable, exception and cursor?

How to execute procedure and function inside the package?

Posted 4th October 2014 by Unknown

0 Add a comment

OCT

%TYPE and %ROWTYPE


--%type is used to fetch the data type of the particular column

create table product_details

p_id NUMBER(3),

p_nm VARCHAR2(30),

p_qty NUMBER(8),

order_dt DATE

);

BEGIN

INSERT INTO product_details VALUES(100,'Name0',400,'23-Mar-13');

INSERT INTO product_details VALUES(101,'Name1',600,'26-Apr-13');

INSERT INTO product_details VALUES(102,'Name2',800,'27-Jan-12');

INSERT INTO product_details VALUES(103,'Name3',300,'23-Jul-11');

INSERT INTO product_details VALUES(104,'Name4',200,'22-Aug-11');

INSERT INTO product_details VALUES(105,'Name5',500,'25-Oct-12');

commit;

END;

SELECT * FROM product_details;


------------------------------------

P_ID P_NM P_QTY ORDER_DT

------------------------------------

100 Name0 400 03/23/2013

101 Name1 600 04/26/2013

102 Name2 800 01/27/2012

103 Name3 300 07/23/2011

104 Name4 200 08/22/2011

105 Name5 500 10/25/2012

------------------------------------

DECLARE

v_name VARCHAR2(4);

BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 100;

dbms_output.put_line('Product Name : ' || v_name);

--error numeric or value error

END;
DECLARE

v_name VARCHAR2(5);

BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 100;

dbms_output.put_line('Product Name : ' || v_name);

END;

ALTER TABLE product_details

MODIFY p_nm VARCHAR2(15);

INSERT INTO product_details

VALUES

(106,

'name6',

700,

'26-Dec-12');

commit;
106 name6 700 12/26/2012

DECLARE

v_name VARCHAR2(5);

BEGIN

SELECT p_nm INTO v_name

FROM product_details

WHERE p_id = 106;

dbms_output.put_line('Product Name : ' || v_name);

--error

END;

DECLARE

v_name product_details.p_nm%TYPE;

BEGIN

SELECT p_nm

INTO v_name

FROM product_details
WHERE p_id = 106;

dbms_output.put_line('Product Name : ' || v_name);

END;

DROP TABLE product_details;

DECLARE

dep_id departments.department_id%TYPE;

dep_name departments.department_name%TYPE;

dep_man_id departments.manager_id%TYPE;

dep_loc_id departments.location_id%TYPE;

BEGIN

SELECT department_id,

department_name,

manager_id,

location_id

INTO dep_id,

dep_name,

dep_man_id,
dep_loc_id

FROM departments

WHERE department_id = 10;

dbms_output.put_line('Department_id : ' || dep_id);

dbms_output.put_line('Department_name : ' || dep_name);

dbms_output.put_line('Manager_id : ' || dep_man_id);

dbms_output.put_line('Location_id : ' || dep_loc_id);

END;

--%rowtype is used to fetch the data type of all the column

--Insted of using %type if we use %rowtype means we can reduce the no of variables that we
declare

DECLARE

dep_detail departments%ROWTYPE;

BEGIN

SELECT *

INTO dep_detail

FROM departments
WHERE department_id = 10;

dbms_output.put_line('Department_id : ' || dep_detail.department_id);

dbms_output.put_line('Department_name : ' || dep_detail.department_name);

dbms_output.put_line('Manager_id : ' || dep_detail.manager_id);

dbms_output.put_line('Location_id : ' || dep_detail.location_id);

END;

DROP TABLE dept_details;

CREATE TABLE dept_details

dept_id number(3) ,

dept_name varchar2(30),

dept_manager_name varchar2(30)

);

insert into dept_details values(10,'dept1','manager_name1');

insert into dept_details values(20,'dept2','manager_name2');

SELECT * FROM dept_details;


-------------------------------------------------------

| DEPT_ID | DEPT_NAME | DEPT_MANAGER_NAME |

+------------+-----------------------+-----------------

| 10 | dept1 | manager_name1 |

| 20 | dept2 | manager_name2 |

------------+-----------------------+------------------

DECLARE

all_data dept_details%ROWTYPE;

BEGIN

all_data.dept_id := 100;

all_data.dept_name := 'Admin';

all_data.dept_manager_name := 'John';

UPDATE dept_details

SET ROW = all_data

WHERE dept_id = 10;

dbms_output.put_line(SQL%ROWCOUNT || ' Row(s) get updated');

END;

/
1 Row(s) get updated

select * from dept_details;

---------------------------------------------------

| DEPT_ID | DEPT_NAME | DEPT_MANAGER_NAME|

---------------------------------------------------

| 100 | Admin | John |

| 20 | dept2 | manager_name2 |

---------------------------------------------------

Interview Question :

1. What is the use of %TYPE?

2. What is the use of %ROWTYPE?

3. Difference between %TYPE and %ROWTYPE?

Posted 2nd October 2014 by Unknown


0 Add a comment

SEP

29

BULK Exceptions

/************************************************************************

* Handling Exceptions in Bulk Operations *

* Documented on 29-SEP-14 04.35.35.980894 PM +05:30 *

* Document By : Murugappan Annamalai *

* Reference : http://www.dba-oracle.com/plsql/t_plsql_exceptions.htm *

************************************************************************/

CREATE TABLE bulk_tb (ran_num NUMBER NOT NULL);

--inserting data using bulk collect

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();


BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

commit;

END;

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

200

TRUNCATE TABLE bulk_tb;

sample2.sql --without exception part


DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

commit;

END;

/*

Error Message :

ORA-01400: cannot insert NULL into ("HR"."bulk_tb"."ran_num")


ORA-06512: at line 15

*/

sample2.sql --with exception part

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

BEGIN

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

COMMIT;
EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('Error while inserting bulk record '||SQLERRM);

END;

END;

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

99

SQL%BULK_EXCEPTIONS(i).ERROR_INDEX

Holds the iteration (not the subscript) of the original FORALL statement that raised the
exception.

In sparsely populated collections,

the exception row must be found by looping through the original collection the correct
number of times.

SQL%BULK_EXCEPTIONS(i).ERROR_CODE
Holds the exceptions error code.

The total number of exceptions can be returned using the collections COUNT method,

which returns zero if no exceptions were raised. The save_exceptions.sql script,

a modified version of the handled_exception.sql script, demonstrates this functionality.

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

v_ex_count NUMBER(4);

abort_ex EXCEPTION;

PRAGMA EXCEPTION_INIT(abort_ex, -24381);

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

v_dat(150) := NULL;

/* will cause error while inserting data into bulk_tb


because of not null constraint */

EXECUTE IMMEDIATE 'TRUNCATE TABLE bulk_tb';

BEGIN

FORALL i IN v_dat.FIRST..v_dat.LAST SAVE EXCEPTIONS

INSERT INTO bulk_tb VALUES(v_dat(i));

COMMIT;

EXCEPTION

WHEN abort_ex THEN

v_ex_count := SQL%BULK_EXCEPTIONS.COUNT;

FOR i IN 1..v_ex_count LOOP

dbms_output.put_line('Error: ' || i ||' Array Index: ' || SQL


%BULK_EXCEPTIONS(i).error_index ||

' Message: ' || SQLERRM(SQL%BULK_EXCEPTIONS(i).ERROR_CODE));

END LOOP;

END;

END;

/*

Sample output:

Error: 1 Array Index: 100 Message: -1400: non-ORACLE exception

Error: 2 Array Index: 150 Message: -1400: non-ORACLE exception


*/

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

198

SAVE EXCEPTIONS clause being removed, in the above script now traps a different error number.

The output from this script is listed below.

/*

Sample output:

Error: 1 Array Index: 100 Message: -1400: non-ORACLE exception

*/

SELECT COUNT(*) FROM bulk_tb;


COUNT(*)

-------

99

SELECT COUNT(*) FROM bulk_tb;

DROP TABLE bulk_tb;

Posted 29th September 2014 by Unknown

0 Add a comment

SEP

29

Cursor - FOR UPDATE

/************************************************************************

* FOR UPDATE clause in oracle *

* Document By : Murugappan Annamalai *

************************************************************************/
create table prod_details(p_id VARCHAR2(30), P_name VARCHAR2(30));

BEGIN

--Inserting data into prod_details table

FOR i IN 1..50 LOOP

INSERT INTO prod_details VALUES(i,'pname'||i);

END LOOP;

commit;

END;

SELECT * FROM prod_details;

DECLARE

CURSOR PROD_DTLS_C IS

SELECT * FROM PROD_DETAILS T1 FOR UPDATE OF P_ID;

V_PID PROD_DETAILS.P_ID%TYPE;

V_PRDNAME PROD_DETAILS.P_NAME%TYPE;
BEGIN

OPEN PROD_DTLS_C;

LOOP

FETCH PROD_DTLS_C INTO V_PID, V_PRDNAME;

IF PROD_DTLS_C%NOTFOUND THEN

EXIT;

ELSE

UPDATE PROD_DETAILS P

SET P.P_ID = LPAD(P_ID, 10, 0)

WHERE CURRENT OF PROD_DTLS_C;

END IF;

END LOOP;

CLOSE PROD_DTLS_C;

COMMIT;

END;

select * from PROD_DETAILS;

TRUNCATE TABLE prod_details;


BEGIN

--Inserting data into prod_details table

FOR i IN 1..50 LOOP

INSERT INTO prod_details VALUES(i,'pname'||i);

END LOOP;

commit;

END;

DECLARE

CURSOR PROD_DTLS_C IS

SELECT * FROM PROD_DETAILS T1 FOR UPDATE OF P_ID;

V_PID PROD_DETAILS.P_ID%TYPE;

V_PRDNAME PROD_DETAILS.P_NAME%TYPE;

BEGIN

OPEN PROD_DTLS_C;

LOOP

FETCH PROD_DTLS_C INTO V_PID, V_PRDNAME;


IF PROD_DTLS_C%NOTFOUND THEN

EXIT;

ELSE

UPDATE PROD_DETAILS P

SET P.P_ID = LPAD(P_ID, 10, 0)

WHERE CURRENT OF PROD_DTLS_C;

END IF;

COMMIT;

END LOOP;

CLOSE PROD_DTLS_C;

--COMMIT;

END;

select * from PROD_DETAILS;

Posted 29th September 2014 by Unknown

0 Add a comment

MAY

28

Escape Sequence in Oracle


Escape special characters when writing SQL queries

--to include single '

SELECT 'Steven's salary is more than 50k INR' AS "SAL_DETAILS"

FROM Dual;

ORA-01756 : quoted string not properly terminated

SELECT 'Steven''s salary is more than 50k INR' AS "SAL_DETAILS"

FROM Dual;

SAL_DETAILS

---------------------------------------

Steven's salary is more than 50k INR

--to include double '

SELECT 'You can print double quot ('''') in oracle' "Info"


FROM Dual;

Info

---------------------------------------

You can print double quot ('') in oracle

SELECT q'[some test ' some test ' some text ']' AS "In 10g"

FROM dual;

In 10g

------------------------------------

some test ' some test ' some text '

--Escape wild card characters ( _ and % )

The LIKE keyword allows for string searches.

The '_' wild card character is used to match exactly one character

While '%' is used to match zero or more occurrences of any characters.

These characters can be escaped in SQL as follows.

WITH mail_ids AS

(
SELECT 'an.murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an_murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an%murugappan@gmail.com' mail FROM Dual

SELECT * FROM mail_ids

WHERE mail LIKE '__$_%' ESCAPE '$';

mail

----------------------------------

an_murugappan@gmail.com

WITH mail_ids AS

SELECT 'an.murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an_murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an%murugappan@gmail.com' mail FROM Dual

SELECT * FROM mail_ids

WHERE mail LIKE '__/%%' ESCAPE '/';


mail

----------------------------------

an%murugappan@gmail.com

Escape ampersand (&) characters in SQL*Plus

SQL> select '&a' FROM dual;

'23'

----

23

SQL> SET ESCAPE '\'

SQL> select '\&a' FROM dual;

'&A'

----

&a

SQL> SET SCAN OFF;

SQL> select '&a' FROM dual;


'&A'

----

&a

SQL> SET SCAN ON;

SQL> select '&a' FROM dual;

'45'

----

45

Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Data Manipulation Language

Data Manipulation Language (DML) statements are used for managing data within schema
objects. Some examples:
INSERT - insert data into a table

UPDATE - updates existing data within a table

DELETE - deletes all records from a table, the space for the records remain

MERGE - UPSERT operation (insert or update)

CREATE TABLE prod_details

prod_id NUMBER(4) ,

prod_name VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

Deliver_dt DATE DEFAULT SYSDATE+3 ,

comments VARCHAR2(300)

);

SELECT * FROM prod_details;

no_data_found

INSERT

INSERT INTO prod_details(prod_id,prod_name,order_dt,deliver_dt,comments)

VALUES(100,'Apple iphone 5s','21-May-14','24-May-14','Color : Black');


SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

---------------------------------------------------------------------------

--Inserting records with out mentioning column name

INSERT INTO prod_details

VALUES(101,'Samsung Galaxy III','20-Aug-14','23-Aug-14','Color : White');

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

---------------------------------------------------------------------------

--Inserting selective number of values

INSERT INTO prod_details


VALUES(103,'Moto X','11-May-14','13-May-14');

ORA-00947 : not enough values

--While inserting selective number of values mentioning column name is compulsory.

INSERT INTO prod_details (prod_id,prod_name,order_dt,deliver_dt)

VALUES(103,'Moto X','11-May-14','13-May-14');

SELECT * FROM prod_details;

--------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

--------------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

--------------------------------------------------------------------------------

--Inserting NULL value.

--If you want to insert NULL value you can ignore that column at the time of inserting

--or we can use NULL keyword to insert NULL.

INSERT INTO prod_details


VALUES(104,'Moto G','19-May-14','22-May-14',NULL);

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Noto G 5/19/2014 5/22/2014

---------------------------------------------------------------------------

--if you are not providing values for order_dt and deliver_dt column default value can be taken.

INSERT INTO prod_details(prod_id,prod_name,comments)

VALUES(105,'Nokia Lumis 720p','Color : Red');

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

----------------------------------------------------------------------------
100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Moto G 5/19/2014 5/22/2014

105 Nokia Lumis 720p 5/26/2014 5/29/2014 Color : Red

---------------------------------------------------------------------------

--Inserting data by using sub query

CREATE TABLE test_tab (id NUMBER, Name VARCHAR2(30));

INSERT INTO test_tab VALUES(1,'Name1');

INSERT INTO test_tab VALUES(2,'Name2');

INSERT INTO test_tab VALUES(3,'Name3');

SELECT COUNT(*) FROM test_tab;

COUNT(*)

-------

--creating table by using sub query (with out data)


CREATE TABLE ins_chk

SELECT * FROM test_tab

WHERE id = 900;

SELECT COUNT(*) FROM ins_chk;

COUNT(*)

-------

--Inserting data by using sub query

--copying data from test_tab to ins_chk

INSERT INTO ins_chk (SELECT * FROM test_tab);

3 rows inserted in 0.047 seconds.

SELECT COUNT(*) FROM ins_chk;

COUNT(*)

-------
3

DROP TABLE test_tab;

DROP TABLE ins_chk;

UPDATE

Syntax :

UPDATE table_name

SET column1_name = column1_value,

column2_name = column2_value,

column2_name = column3_value,

columnn_name = columnn_value

WHERE condition(s);

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

----------------------------------------------------------------------
100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Moto G 5/19/2014 5/22/2014

105 Nokia Lumis 720p 5/26/2014 5/29/2014 Color : Red

---------------------------------------------------------------------------

UPDATE prod_details ps

SET ps.prod_name = 'iphone 5s'

WHERE ps.prod_id = 100;

1 row updated in 0.031 seconds

SELECT *

FROM prod_details ps

WHERE ps.prod_id = 100;

--------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

--------------------------------------------------------------------

100 iphone 5s 5/21/2014 5/24/2014 Color : Black

--------------------------------------------------------------------

--update statement with out condition

--If you try to execute update statement without condition it'll update all the records inside the
table.
UPDATE prod_details ps

SET ps.comments = 'None';

5 row updated in 0.031 seconds

SELECT *

FROM prod_details ps;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 None

101 Samsung Galaxy III 8/20/2014 8/23/2014 None

103 Moto X 5/11/2014 5/24/2014 None

104 Moto G 5/19/2014 5/22/2014 None

105 Nokia Lumis 720p 5/26/2014 5/29/2014 None

----------------------------------------------------------------------

--if your update text contain ' means you can use following metnod (use '')

UPDATE prod_details ps

SET ps.comments = 'Some product''s are not available'

WHERE ps.prod_id = 100;


1 row updated in 0.031 seconds

SELECT *

FROM prod_details ps

WHERE ps.prod_id = 100;

------------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

------------------------------------------------------------------------------------

100 iphone 5s 5/21/2014 5/24/2014 Some product's are not available

------------------------------------------------------------------------------------

DELETE

Syntax:

DELETE FROM table_name

WHERE condition(s);

DELETE FROM prod_details

WHERE prod_id IN (104, 105);


2 row(S) deleted in 0.032 seconds

SELECT *

FROM prod_details ps;

---------------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Some product's are not available

101 Samsung Galaxy III 8/20/2014 8/23/2014 None

103 Moto X 5/11/2014 5/24/2014 None

---------------------------------------------------------------------------------------

DELETE FROM prod_details;

3 row(s) deleted in 0.062 seconds.

SELECT * FROM prod_details;

no rows selected.

DROP TABLE prod_details;


MERGE = Insert + Update

-- will update soon.

Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Data Define Language

Data Definition Language (DDL) statements are used to define the database structure or schema.

Some examples:

CREATE - to create objects in the database.

ALTER - alters the structure of the database.

ADD

RENAME

MODIFY

DROP

DROP - delete objects from the database


TRUNCATE - remove all records from a table,

including all spaces allocated for the records are removed.

COMMENT - add comments to the data dictionary.

RENAME - rename an object.

Creating Table

--------------------------------------------------------------------------

Data Types Size Default Size Explanation

--------------------------------------------------------------------------

NUMBER(P,S) P: 1 to 38 we can store number between 0-9

S: -84 to 127

VARCHAR2 4000 Bytes we can store 0-9, a-z, A-Z and special characters

CHAR 2000 Bytes 1

DATE 7 Used to store Date

TIMESTAMP Includes year, month, day, hour, minute, and seconds.

LONG 2 GB Only one long column is allowed in a table.

We can't use this column in ORDER BY clause.

CLOB 4 GB Character Large Object

BLOB Binary Larger Object

--------------------------------------------------------------------------

CREATE

ALTER : ADD RENAME MODIFY DROP RENAME


RENAME

DROP

TRUNCATE

--creating table

CREATE TABLE friends_details_tb

Name VARCHAR2(30) ,

Phone NUMBER(10) ,

Gender CHAR ,

dob DATE ,

other_details LONG ,

make_dtm TIMESTAMP

);

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)
DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

-----------------------------

--maximum you can keep 255 columns in a table

ALTER : Colum level operations

ADD RENAME MODIFY DROP

ADD : Used to add a column after the table hase been created

ALTER TABLE friends_details_tb

ADD email VARCHAR2(30);

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)
GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

EMAIL VARCHAR2(30)

-----------------------------

--adding multiple columns by using single ALTER statement

SYNTAX

ALTER TABLE friends_details_tb

ADD (

column_1 Data_type(size),

column_2 Data_type(size),

column_3 Data_type(size),

column_4 Data_type(size)

);

RENAME : Used to Rename a column

ALTER TABLE friends_details_tb


RENAME COLUMN email TO email_id;

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

MODIFY : Used to change the data type or size of the data type.

ALTER TABLE friends_details_tb

MODIFY other_details CLOB;

DESC friends_details_tb;
-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS CLOB

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

--Modifying multiple columns at a time

ALTER TABLE friends_details_tb

MODIFY ( column_name_1 old_datatype(new_size),

column_name_2 new_datatype(old_size),

column_name_3 new_datatype(new_size)

);

DROP : Used to drop the column after the table has been created.

ALTER TABLE friends_details_tb


DROP COLUMN other_details;

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

RENAME : Used to Rename a particular table.

SYNTAX

RENAME old_table_name TO new_table_name;

RENAME friends_details_tb TO fnd_det;

DESCRIBE fnd_det;
-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

TRUNCATE : Used to remove the entire content of the table (not a structure)

SYNTAX

TRUNCATE TABLE table_name;

TRUNCATE TABLE fnd_det;

DROP : Used to drop the tabel (Data + stucture of the table get removed from the database )
DROP TABLE fnd_det;

*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Statements in Oracle

Data Definition Language (DDL)

DDL statements are used to define the database structure or schema. Some examples:

CREATE - to create objects in the database

ALTER - alters the structure of the database

ADD

RENAME

MODIFY

DROP

DROP - delete objects from the database

TRUNCATE - remove all records from a table,

including all spaces allocated for the records are removed


RENAME - rename an object

Data Manipulation Language (DML)

DML statements are used for managing data within schema objects. Some examples:

INSERT - insert data into a table

UPDATE - updates existing data within a table

DELETE - deletes all records from a table, the space for the records remain

MERGE - UPSERT operation (insert or update)

Data Control Language (DCL)

DCL statements. Some examples:

GRANT - gives users access privileges to database

REVOKE - withdraw access privileges given with the GRANT command

Transaction Control (TCL)

TCL statements are used to manage the changes made by DML statements. It allows
statements to be grouped together into logical transactions.
COMMIT - save work done

SAVEPOINT - identify a point in a transaction to which you can later roll back

ROLLBACK - restore database to original since the last COMMIT

Posted 28th May 2014 by Unknown

0 Add a comment

MAY

19

DECODE and CASE statement

CREATE TABLE students (

roll_no NUMBER(4) ,

Name VARCHAR2(30) ,

dept_cd VARCHAR2(20) ,

total_marks NUMBER(3)

);

BEGIN

INSERT INTO students VALUES (2000,'Rahul','CSE',480);


INSERT INTO students VALUES (2001,'Bala','IT', 390);

INSERT INTO students VALUES (2002,'Ramesh','CSE',250);

INSERT INTO students VALUES (2003,'Karthi','EEE',185);

INSERT INTO students VALUES (2004,'Ravi','IT',345);

END;

SELECT * FROM students;

DECODE

Decode is a function. Its a Oracle one.

Works like IF-THEN-ELSE.

You can use DECODE only in SELECT clause.

In DECODE you can include 255 things include Exep, search , result and default value.

Example

SELECT roll_no,

NAME,

dept_cd,

DECODE(dept_cd,

'CSE',

'Computer Science and Engineering',

'IT',

'Information Technology',
'Default Value') AS "DEPARTMENT NAME"

FROM students;

Sample Output

------------------------------------------------------------

ROLL_NO NAME DEPT_CD DEPARTMENT NAME

------------------------------------------------------------

2000 Rahul CSE Computer Science and Engineering

2001 Bala IT Information Technology

2002 Ramesh CSE Computer Science and Engineering

2003 Karthi EEE Default Value

2004 Ravi IT Information Technology

------------------------------------------------------------

CASE

CASE is an expression. Its a ANSI standard.

Compare to DECODE case will be more faster.

Example

SELECT roll_no,

NAME,

dept_cd,

total_marks,
CASE

WHEN total_marks > 500 THEN

'A Grade'

WHEN total_marks > 400 THEN

'B Grade'

WHEN total_marks > 300 THEN

'C Grade'

ELSE

'U Grade'

END AS "GRADE"

FROM students;

-----------------------------------------------

ROLL_NO NAME DEPT_CD TOTAL_MARKS GRADE

-----------------------------------------------

2000 Rahul CSE 480 B Grade

2001 Bala IT 390 C Grade

2002 Ramesh CSE 250 U Grade

2003 Karthi EEE 185 U Grade

2004 Ravi IT 345 C Grade

-----------------------------------------------

Interview Questions:

What is DECODE?
What is CASE?

Difference between CASE and DECODE? Which one is faster?

Posted 19th May 2014 by Unknown

0 Add a comment

MAY

19

Sub Query

Query with in another query

1. Single Row sub query

2. Multi row Sub query

select * from employees;

Want to fetch the person Who are all getting salary more than Neena's salary ?

Neena's Salary : 17000


Select First_name, salary

From Employees

Where salary > 17000;

--change in Neena's salary won't work for the above query.

Select salary From Employees

Where First_name = 'Neena';

Sub Query :

Select First_name, salary

From Employees

Where salary > (

Select salary From Employees

Where First_name = 'Neena'

);

Select * from employees;

Select salary From Employees

Where First_name = 'Alexander';


Sub Query Returns one value it is called as Single row sub query

Sub Query Returns more than one value it is called as Multi row sub query

Single row sub query operators :

> < >= <= = <>

Multiple Row Sub query operators :

IN ALL ANY

Who are all getting salary more than the average salary?

Select

First_name,

Salary

From

Employees

WHERE

Salary > (

SELECT Round(avg(salary),0)
FROM Employees

);

Multiple Row Sub query (In ANY ALL)

Select First_name,Department_id, salary

From Employees

Where salary in(

Select Salary From Employees

Where First_name = 'Alexander'

);

Any : Minimum Value will be taken (3100)

Select First_name,Department_id, salary

From Employees

Where salary > ANY(

Select Salary From Employees

Where First_name = 'Alexander'

);

All : Maximum Value will be taken (9000)

Select First_name,Department_id, salary


From Employees

Where salary > All(

Select Salary From Employees

Where First_name = 'Alexander'

);

We can use sub query in all the classes except Group by and order by class.

Select

From

Where

-----------Group by

having

-----------Order by

SELECT

( Select Count(*) from Employees Where Department_id = 90 )Executive,

( Select Count(*) from Employees Where Department_id = 60 ) IT,

( Select Count(*) from Employees Where Department_id = 10 ) Administration,

( Select Count(*) from Employees Where Department_id = 100) Finance

FROM

Dual;
Select Min(salary) From Employees;

Select Min(salary) from

Select * from Employees

Where Department_id = 60

);

What is INLINE VIEW?

If u use sub query in From it is call it is as INLINE VIEW.

Intermediate result set

Correlated sub query

SELECT employee_number, name

FROM employees Bob

WHERE salary > (

SELECT AVG(salary)

FROM employees

WHERE department = Bob.department

);
Posted 19th May 2014 by Unknown

0 Add a comment

Loading

Dynamic Views theme. Powered by Blogger.

Oracle sql & Pl/sql

search

Home Sql and pl/sql Sql Interview Questions

JUL

20

INLINE view in Oracle with 12c New Features

Named sub Query in FROM clause is call it as INLINE VIEW.

Oracle process a inline view faster than sub query

Inline View in Oracle

--Query to display all the employees who are all getting salary more than their department
average salary

SELECT First_name
, last_name

, salary

, department_id

FROM employees a , ( SELECT b.department_id

, AVG(b.salary) avg_sal

FROM employees b

GROUP BY b.department_id

)b

WHERE a.department_id = b.department_id

AND a.salary > b.avg_salary;

Display all the customer who have placed more number of orders by using INLINE view

CREATE TABLE customer_order_det_tb

( custm_id NUMBER ,

custm_nm VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

ttl_amt NUMBER(7,2)

);

BEGIN

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '11-Jul-15' , 45000.00);

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '14-Jul-15' , 27000.00);

INSERT INTO customer_order_det_tb VALUES(101, 'Raja' , '13-Jul-15' , 17000.00);


INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 34000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 38000.00);

COMMIT;

END;

SELECT c.*

FROM customer_order_det_tb c;

--------------------------------------------

custm_id custm_nm order_dt ttl_amt

--------------------------------------------

100 Murugappan 7/11/2015 45000.00

100 Murugappan 7/14/2015 27000.00

101 Raja 7/13/2015 17000.00

102 Ramesh 7/15/2015 34000.00

102 Ramesh 7/15/2015 38000.00

--------------------------------------------

--Writing a Quer to display all the customer who have placed maximum number of order

--Query #1 for inline view

SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC;

--------------------------------

custm_id custm_nm total_odr

--------------------------------

100 Murugappan 2

102 Ramesh 2

101 Raja 1

--------------------------------

--Query #2 for inline view

SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm;

----------

total_odr

----------

----------

Inline view to find all the customers who have placed maximum number of orders
/****************************************

Syntax

SELECT * FROM <query1> x, <query2> y

WHERE contition;

****************************************/

SELECT query1.* FROM

( SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC

) query1,

( SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm

) query2

WHERE query1.total_odr = query2.total_odr;

-------------------------------

custm_id custm_nm total_odr

-------------------------------

100 Murugappan 2

102 Ramesh 2

-------------------------------
DROP TABLE customer_order_det_tb;

--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT

SELECT first_name, salary

FROM ( SELECT first_name, salary

FROM employees e

WHERE job_id NOT IN ('SALESMAN','PRESIDENT')

ORDER BY salary DESC

WHERE ROWNUM < 4;

New Oracle 12c Inline view Syntax

LATERAL clause for In-line views

Allows for columns in the inline view to be accessed!!

Example :

--in 11g

SELECT * FROM employees e, (


SELECT *

FROM departments d

WHERE e.department_id = d.department_id);

ORA-0090: "E"."DEPARTMENT_ID": Invalid Identifier

--in 12c

SELECT * FROM employees e, LATERAL(

SELECT *

FROM departments d

WHERE e.department_id = d.department_id

);

--in 11g

WITH t

AS

( SELECT LEVEL a

FROM dual

CONNECT BY LEVEL <= 30)

SELECT *

FROM t, (SELECT *

FROM employees

WHERE department_id = t.a


);

ORA-00904: "T"."A": invalid Identifier

--in 12c

WITH t

AS

(SELECT LEVEL a FROM dual CONNECT BY LEVEL <= 30)

SELECT * FROM t,

LATERAL(SELECT *

FROM employees

WHERE department_id = t.a);

Hope you have enjoyed this little article

Feed backs are always Welcome :) (:

Posted 20th July 2015 by Unknown

0 Add a comment

JAN

23

Salary Related Questions in Oracle


--creating table

CREATE TABLE employee_data

eid NUMBER(4),

ename VARCHAR2(30),

depno NUMBER(3),

salary NUMBER(8)

);

BEGIN

--Inserting records

INSERT INTO employee_data VALUES(1000,'Name01',90,30000);

INSERT INTO employee_data VALUES(1001,'Name02',90,6000);

INSERT INTO employee_data VALUES(1002,'Name03',90,23000);

INSERT INTO employee_data VALUES(1003,'Name04',60,35000);

INSERT INTO employee_data VALUES(1004,'Name05',60,60000);

INSERT INTO employee_data VALUES(1005,'Name06',60,30000);

INSERT INTO employee_data VALUES(1006,'Name07',80,36000);

INSERT INTO employee_data VALUES(1007,'Name08',80,29000);

INSERT INTO employee_data VALUES(1008,'Name09',80,37000);


INSERT INTO employee_data VALUES(1009,'Name10',80,41000);

COMMIT;

END;

SELECT * FROM employee_data

ORDER BY salary DESC;

--query to find maximum salary from employee_data table

SELECT MAX(salary) FROM employee_data;

--query to find minimum salary from employee_data table

SELECT MIN(salary) FROM employee_data;

--query to find second maximum salary from employee_data table

SELECT MAX(salary)

FROM employee_data

WHERE salary NOT IN (SELECT MAX(salary)

FROM employee_data);

--query to select 5th maximum salary


SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= 5);

--query to select nth maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= &n);

--query to select all the details of the employee whose getting nth maximum salary

SELECT *

FROM (SELECT emp.*,

rownum rn

FROM (SELECT *
FROM employee_data

ORDER BY salary DESC) emp)

WHERE rn = 9;

--same query using row_numbr( ) function

SELECT *

FROM (SELECT emp.*,

row_number() over(ORDER BY salary) rank

FROM employee_data emp)

WHERE rank = 9;

--same query using rank( ) function

SELECT *

FROM (SELECT emp.*,

rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--same query using dense_rank( ) function

SELECT *

FROM (SELECT emp.*,


dense_rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--query to display display maximum salary in all the department

SELECT e.depno "Department id",

MAX(salary) "Maximum Salary"

FROM employee_data e

GROUP BY e.depno;

--query to display all the employees who are all getting salary more than average salary of the
company

SELECT e.* FROM employee_data e

WHERE salary > (SELECT AVG(salary) FROM employee_data);

--query to display all the employees who are all getting salary more than their department
average salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)


FROM employees

WHERE department_id = OUT.department_id);

--query to display all the employees who are all getting salary more than their manager salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE employee_id = OUT.manager_id);

Documented By : Murugappan Annamalai

Posted on : 23-Jan-15 16:34:00 IST.

Hope you have enjoyed this little article

Feed backs are always welcome :)

Posted 23rd January 2015 by Unknown


7 View comments

JAN

22

Why prefer COALESCE over NVL

Documented By : Nimish Garg

I prefer using "COALESCE" over "NVL" is some of the scenarios. Last week One of my friend
asked me what is the advantage of using "COALESCE" where we can simply use "NVL". I simply
gave him the reply from Oracle Docs i.e. NVL lets you replace null (returned as a blank) with a
string in the results of a query and COALESCE returns the first non-null expr in the expression list.
Oracle Database uses short-circuit evaluation with "COALESCE".

He replied that he knows the difference, he knows that "COALESCE" can take multiple arguments
and so on. He was more interested in understanding "short-circuit evaluation" of "COALESCE"
and the scenarios where I prefer using "COALESCE" over "NVL".

To make him understand I created following function which takes One second in every execution
and simply returns '--null--' and executed 2 very similar queries one with NVL and other with
COALESCE.

SQL> create or replace function f_null return varchar2

2 is

3 begin

4 dbms_lock.sleep(1);

5 return '--null--';

6 end;
7 /

Function created.

Following are the queries which I used to demonstrate that NVL evaluates both arguments even
if the second argument is not used and COALESCE uses short-circuit evaluation i.e. it only
evaluates the arguments only if they are needed.

SQL> select e.empno, e.ename ename, nvl(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING


7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.

Elapsed: 00:00:14.01

SQL> select e.empno, e.ename ename, coalesce(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING


7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.

Elapsed: 00:00:01.01

Here we can see easily that the first query with NVL took 14+ seconds, one second for each
record even if the "f_null" value was used only in one record. On the contrary as mentioned in
Oracle Documentation "COALESCE" uses its "short-circuit evaluation" and "f_null" was called
only once and so second query took only One Second. "COALESCE" is certainly use less resources
than NVL.

Posted 22nd January 2015 by Unknown

0 Add a comment

DEC

21

Constraints

It Enforce Rule On Table


We can create constraint at the time of Creating Table

1. Column Level Declaration

2. Table Level Declaration

1. We can provide own name.

Format : [part_of_project_name-table_name-column_name-constraint_type]

Example : gmind_emp_id_pk _uk _ck _f

2. system name name

Format : sys_cn

Example : SYS_C405323

We can create constraint after the table has been created

Types

Primary Key
Not allowed Null value

Not allowed you to enter duplicate value

Ex : Employee_id, Student_id

Unique Key

allowed Null value

Not allowed you to enter duplicate value

Ex : Contact_no, email

Foreign Key

It will allowed you to enter NULL and Duplicate value.

c1(pk) : 1 2 3

c2(f) : 1 1 2 3 4 Not allowed

Allowed you to enter duplicate value and null value

Not Null

It will not allowed you to enter null value

Check
You can check your own condition

Simple Table for understanding

------------------------------------

Duplicate NULL

------------------------------------

Primary Key X X

Unique Key X Allowed

Foreign Key Allowed Allowed

------------------------------------

creating table with all constraint type

Create table my_stu_details

S_id Number(2),

S_name Varchar2(30) Not Null, --SYS_Cn

s_mail Varchar2(30),

s_gender char(1),

s_did Number(3),
Constraint my_stu_sid_pk PRIMARY KEY (s_id),

constraint my_stu_mail_uk UNIQUE (s_mail) ,

Constraint my_stu_gen_ck CHECK (s_gender IN ('M', 'F', 'm', 'f')),

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

);

DESC my_stu_details;

------------------------------------

Name Type Nullable

------------------------------------

S_ID NUMBER(2)

S_NAME VARCHAR2(30)

S_MAIL VARCHAR2(30) Y

S_GENDER CHAR(1) Y

S_DID NUMBER(3) Y

------------------------------------

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name1' , 'name1@gmail.com' , 'm' , 60 );


Select * from my_stu_details;

Validating Primary Key

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-00001: unique constraint (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (NULL, 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-01400: cannot insert NULL into (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (2 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

Validating NOT NULL Constraint


Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , NULL , 'name3@gmail.com' , 'F' , 80 );

ORA-01400: cannot insert NULL into ("HR"."MY_STU_DETAILS"."S_NAME")

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , 'Name3' , 'name3@gmail.com' , 'F' , 80 );

Select * from my_stu_details;

Validating Unique Key Constraint

--Duplicate Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , 'name3@gmail.com' , 'F' , 80 );

ORA-00001: unique constraint (HR.MY_STU_MAIL_UK) violated


--Null Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , null , 'M' , 70 );

Select * from my_stu_details;

Validating Check constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'j' , 70 );

ORA-02290: check constraint (HR.MY_STU_GEN_CK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'M' , 70 );

Select * from my_stu_details;


Validating Foreign Key

Select * from Departments;

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 3 );

ORA-02291: integrity constraint (HR.MY_STU_DID_FK) violated - parent key not found

Departments table : parent table

my_stu_details : Child table

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

--------------------------------------------------------

s_id s_name s_mail s_gender s_did


--------------------------------------------------------

1 name1 name1@gmail.com m 60

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 M 70

5 Name5 name5@gmail.com M 70

6 Name6 name6@gmail.com F 90

--------------------------------------------------------

Deleting the Primary key value which is referred by Foreign Key

Select * from Departments;

DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID

------------------------------------------------------------

60 IT 103 1400 <---- Delete

-- don't execute this query

--Delete From Departments

--Where Department_id = 60;


1) ON DELETE SET NULL

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

1 name1 name1@gmail.com m -

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

2) ON DELETE SET CASCADE

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------
Syntax

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE CASCADE

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE SET NULL

Constraint Related Data Dictionary Table information.

To view constraint Information

SELECT c.owner,

c.constraint_name,

c.constraint_type,

c.table_name,

c.r_constraint_name,

c.status

FROM user_constraints c

WHERE c.table_name = 'MY_STU_DETAILS';


------------------------------------------------------------------------------------

owner constraint_name constraint_type table_name r_constraint_name status

------------------------------------------------------------------------------------

HR SYS_C004023 C MY_STU_DETAILS ENABLED

HR MY_STU_GEN_CK C MY_STU_DETAILS ENABLED

HR MY_STU_SID_PK P MY_STU_DETAILS ENABLED

HR MY_STU_MAIL_UK U MY_STU_DETAILS ENABLED

HR MY_STU_DID_FK R MY_STU_DETAILS DEPT_ID_PK ENABLED

------------------------------------------------------------------------------------

To view constraint name with corresponding column name

SELECT * FROM user_cons_columns c

WHERE c.table_name = 'MY_STU_DETAILS';

-------------------------------------------------------------

owner constraint_name table_name column_name position

-------------------------------------------------------------

HR MY_STU_MAIL_UK MY_STU_DETAILS S_MAIL 1

HR MY_STU_SID_PK MY_STU_DETAILS S_ID 1

HR MY_STU_GEN_CK MY_STU_DETAILS S_GENDER

HR SYS_C004023 MY_STU_DETAILS S_NAME

HR MY_STU_DID_FK MY_STU_DETAILS S_DID 1


-------------------------------------------------------------

Creating Composite Primary Key

Creating Primary Key with more than one number of column

ALTER TABLE table_name

ADD CONSTRAINT constraint_name PRIMARY KEY(column1, column_2 , column3);

In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.

creating constraint after the table creation

ALTER TABLE table_name

ADD CONSTRAINT constraint_name CONSTRAINT_TYPE(column_name);

ALTER TABLE table_name

DROP CONSTRAINT constraint_name;

ALTER TABLE table_name

DROP PRIMARY KEY;


To drop related foreign key

ALTER TABLE table_name

DROP PRIMARY KEY CASCADE;

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name;

Disable constraint with related foreign key constraint

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name CASCADE;

ALTER TABLE table_name

ENABLE CONSTRAINT constraint_name;

Interview Questions
What are all the type of constraint available in oracle?

Difference between PRIMARY KEY and UNIQUE key.

Difference between PRIMARY KEY ans FOREIGN KEY.

Difference between UNIQUE key and FOREIGN KEY.

Is it possible to create tow primary key in single table.

Write a syntax to create FOREIGN constraint.

How to create constraint after the table has been created?

How to enable and disable a constraint.

Which data dictionary table contains information about constraints?

Which Data Dictionary table contains information about constraint with corresponding column
name?

What is composite primary key?

Explain ON DELETE CASCADE and ON DELETE SET NULL option.

~Thanks For Reading~

Post your valuable feedback below

Posted 21st December 2014 by Unknown

1 View comments
UnknownMay 22, 2017 at 12:39 AM

good

Reply

DEC

listagg in Oracle 11g

Oracle 11gR2 listagg built-in function allows for many table columns to be displayed within a
single row, a non-first-normal form display

Syntax :

listagg(column_value,'delimiter') WITHIN GROUP(ORDER BY column_name)

--Example 1:

CREATE TABLE test_ins(empid NUMBER,product VARCHAR2(30));

BEGIN

INSERT INTO test_ins VALUES( 101,'pendrive');

INSERT INTO test_ins VALUES( 102,'toy');

INSERT INTO test_ins VALUES( 101,'ipod');

INSERT INTO test_ins VALUES( 102,'hat');


INSERT INTO test_ins VALUES( 103,'cpu');

INSERT INTO test_ins VALUES( 104,'pen');

INSERT INTO test_ins VALUES( 104,'car');

INSERT INTO test_ins VALUES( 104,'mat');

INSERT INTO test_ins VALUES( 105,'tv');

INSERT INTO test_ins VALUES( 106,'laptop');

commit;

END;

SELECT * FROM test_ins;

SELECT empid "Employee",

listagg(product,

',') within

GROUP (ORDER BY empid) "Products"

FROM test_ins

GROUP BY empid;

-->-- Result set --<--


DROP TABLE test_ins;

-->-- Example 2

select department_id "Department id", listagg(first_name,', ') WITHIN GROUP(ORDER BY


employee_id) "Employees"

FROM employees

WHERE department_id IN (10,20,30,60)

GROUP BY department_id;

-->-- Result set --<--

Posted 4th December 2014 by Unknown

0 Add a comment
NOV

Condition and Looping Statement

IF

IF ELSE

Multiple IF ELSE

LOOP

FOR LOOP

WHILE LOOP

create table test_udt(id NUMBER, salary NUMBER);

BEGIN

INSERT INTO test_udt VALUES(001,23000);

INSERT INTO test_udt VALUES(002,43000);

INSERT INTO test_udt VALUES(003,78000);

INSERT INTO test_udt VALUES(004,25000);

INSERT INTO test_udt VALUES(005,26000);

INSERT INTO test_udt VALUES(006,90000);


Commit;

END;

select * from test_udt;

IF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 1;

IF v_salary > 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

END IF;

commit;
END;

IF ELSE

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

ELSE

UPDATE test_udt t

SET t.salary = v_salary+20007

WHERE t.id = v_id ;

END IF;

commit;

END;
/

--same example with less number of lines

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

v_salary := v_salary+10005;

ELSE

v_salary := v_salary+20007;

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;
/

select * from test_udt;

Multiple IF ELSIF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 3;

IF v_id = 1 THEN

v_salary := 1000;

dbms_output.put_line('1 inside');

ELSIF v_id = 2 THEN

v_salary := 2000;

dbms_output.put_line('2 inside');

ELSIF v_id = 3 THEN

v_salary := 3000;

dbms_output.put_line('3 inside');
ELSIF v_id = 4 THEN

v_salary := 4000;

dbms_output.put_line('4 inside');

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

LOOP

--syntax

LOOP

--statements

--increment

--exit statement

END LOOP;
CREATE TABLE prod_details (pid VARCHAR2(3), pname VARCHAR2(30));

DECLARE

i NUMBER := 1;

x VARCHAR2(3);

BEGIN

LOOP

x := lpad(i,3,'0');

dbms_output.put_line('x value : '|| x);

INSERT INTO prod_details VALUES(i, 'Product '||i);

EXIT WHEN i >900;

i := i+1;

IF MOD(i,100) = 0 THEN

commit;

dbms_output.put_line('commit executed');

END IF;

END LOOP;

END;

SELECT * FROM prod_details ORDER BY 1;

DROP TABLE prod_details;


FOR LOOP

BEGIN

FOR I in 1..5

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

FOR LOOP - Reverse

BEGIN

FOR I in REVERSE 14..50

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

WHILE LOOP

DECLARE

i_val NUMBER:=0;
BEGIN

WHILE (i_val < 11)

LOOP

dbms_output.put_line('The value of I is '||i_val);

i_val := i_val + 1;

END LOOP;

END;

sample output:

The value of I is 0

The value of I is 1

The value of I is 2

The value of I is 3

The value of I is 4

The value of I is 5

The value of I is 6

The value of I is 7

The value of I is 8

The value of I is 9

The value of I is 10

Posted 8th November 2014 by Unknown


0 Add a comment

OCT

21

Bulk Collect

This is used for array fetches

With this you can retrieve multiple rows of data with a single round trip.

This reduces the number of context switches between the pl/sql and sql engines.

You can use bulk collect in both dynamic and static sql.

You can use bulk collect in select, fetch into and returning into clauses.

SQL engine automatically initializes and extends the collections you reference in the bulk
collect clause.

You can fetch into multiple collections with one column each.

You can use the limit clause of bulk collect to restrict the no of rows retrieved.

SELECT * FROM product_details;

-->-- Bulk collect in FETCH INTO --<--

DECLARE
TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Bulk collect in SELECT clause --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

BEGIN

SELECT * BULK COLLECT INTO dta FROM product_details;

FOR i IN dta.FIRST .. dta.LAST LOOP


dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- LIMIT in Bulk collect --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta LIMIT 30;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

/
-->-- Multiple fetches in INTO clause --<--

SELECT * FROM product_details;

DECLARE

TYPE alldata_typ1 IS TABLE OF product_details.p_id%TYPE;

TYPE alldata_typ2 IS TABLE OF product_details.p_name%TYPE;

dta1 alldata_typ1;

dta2 alldata_typ2;

CURSOR proddt_cur IS

SELECT p_id, p_name FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta1, dta2;

CLOSE proddt_cur;

FOR i IN dta1.FIRST .. dta1.COUNT LOOP

dbms_output.put_line('Department Id : ' || dta1(i));

END LOOP;

FOR i IN dta2.FIRST .. dta2.COUNT LOOP

dbms_output.put_line('Department Name : ' || dta2(i));


END LOOP;

END;

DROP TABLE dep_details;

DROP TABLE product_details;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Ref Cursor

This is unconstrained cursor which will return different types depends upon the user input.

Ref cursors cannot be closed implicitly.

Ref cursor with return type is called strong cursor.

Ref cursor without return type is called weak cursor.

You can declare ref cursor type in package spec as well as body.

You can declare ref cursor types in local subprograms or anonymous blocks.
CREATE OR REPLACE PROCEDURE ref_c_sp(dep_det_c IN OUT SYS_REFCURSOR)

AS

BEGIN

OPEN dep_det_c

FOR

SELECT * FROM dep_details d;

END;

DECLARE

dep_det_c SYS_REFCURSOR;

tab_data dep_details%ROWTYPE;

BEGIN

ref_c_sp(dep_det_c);

LOOP

FETCH dep_det_c INTO tab_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department Name : '|| tab_data.d_name);

END LOOP;

CLOSE dep_det_c;

END;
/*sample output*/

Department Name : Admin

Department Name : HR

Department Name : Sales

Department Name : Marketing

DROP PROCEDURE ref_c_sp;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Cursor

SQL Private work Area where the query get passed and executed.

Types

******
Implicit(SQL)

Explicit

-->-- advanced cursor types --<--

Parametrized Cursor

Ref Cursor

Implicit

********

ORACLE implicitly opens a cursor to process each SQL statement not associated with an
explicitly declared cursor.

PL/SQL lets you refer to the most recent implicit cursor as the SQL” cursor. So, although you
cannot use the OPEN,

FETCH, and CLOSE statements to control an implicit cursor, you can still use cursor attributes to
access information

about the most recently executed SQL statement.

Cursor Stages

**************

OPEN cursor_name

FETCH (with in loop)

CLOSE cursor_name

Explicit
The set of rows returned by a query can consist of zero, one, or multiple rows,

depending on how many rows meet your search criteria. When a query returns multiple rows,

you can explicitly define a cursor to process the rows. You use three commands to control the
cursor

Cursor Attributes

*****************

%FOUND

%NOTFOUND

%ISOPEN

%ROWCOUNT

%BULK_ROWCOUNT --<-- used to handle error while using bulk collection.

%BULK_EXCEPTIONS --<-- used to handle error while using bulk collection.

Cursor Declaration

DECLARE

CURSOR <cursor_name>

IS

<SELECT statement>

BEGIN

--> some stmt

END;

/
Cursor Loop

Loop

While Loop

For Loop

Cursor Clauses

Return

For update

Where current of

Bulk collect

-->-- creating table

create table product_details

p_id NUMBER,

p_name VARCHAR2(30),

p_order_dt DATE

);

-->-- Inserting data

BEGIN

FOR i IN 1 .. 75 LOOP
INSERT INTO product_details VALUES (i, 'prod_name_' || i, SYSDATE + i);

END LOOP;

commit;

END;

-->-- selecting data

SELECT * FROM product_details;

---------------------------------------------

p_id p_name p_order_dt

---------------------------------------------

1 prod_name_1 10/11/2014 3:48:32 PM

2 prod_name_2 10/12/2014 3:48:32 PM

3 prod_name_3 10/13/2014 3:48:32 PM

4 prod_name_4 10/14/2014 3:48:32 PM

5 prod_name_5 10/15/2014 3:48:32 PM

6 prod_name_6 10/16/2014 3:48:32 PM

7 prod_name_7 10/17/2014 3:48:32 PM

8 prod_name_8 10/18/2014 3:48:32 PM

9 prod_name_9 10/19/2014 3:48:32 PM

10 prod_name_10 10/20/2014 3:48:32 PM

11 prod_name_11 10/21/2014 3:48:32 PM

12 prod_name_12 10/22/2014 3:48:32 PM


13 prod_name_13 10/23/2014 3:48:32 PM

14 prod_name_14 10/24/2014 3:48:32 PM

15 prod_name_15 10/25/2014 3:48:32 PM

16 prod_name_16 10/26/2014 3:48:32 PM

17 prod_name_17 10/27/2014 3:48:32 PM

18 prod_name_18 10/28/2014 3:48:32 PM

19 prod_name_19 10/29/2014 3:48:32 PM

20 prod_name_20 10/30/2014 3:48:32 PM

---------------------------------------------

----------------------------------------------

Implicit Cursor

----------------------------------------------

--will update soon

----------------------------------------------

Explicit Cursor

----------------------------------------------

**********************************************

Processing cursor data by using LOOP

**********************************************
DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND; --<-- if next record not found means control will
come out from the loop

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )


Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

EXIT WHEN prod_detail_cur%FOUND; --<-- if next record found means control will come
out from the loop

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/
Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;
dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor Already closed

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details


WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

-->-- CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/
Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor closed

**********************************************

Processing cursor data by using WHILE LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

OPEN prod_detail_cur;

FETCH prod_detail_cur

INTO all_data;

WHILE prod_detail_cur%FOUND LOOP


dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

FETCH prod_detail_cur

INTO all_data;

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

************************************************************

Processing cursor data by using FOR LOOP - CURSOR FOR LOOP

************************************************************

DECLARE

--cursor declaration
CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

FOR i IN prod_detail_cur

LOOP

dbms_output.put_line('Product id : ' || i.p_id ||

' Product Name : ' || i.p_name ||

' ( Orderd on : ' || TRIM(i.p_order_dt) || ' )');

END LOOP;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

Parameterized Cursor

*********************
This was used when you are going to use the cursor in more than one place with different
values for the same where clause.

Cursor parameters must be in mode.

Cursor parameters may have default values.

The scope of cursor parameter is within the select statement.

CREATE TABLE dep_details(d_id NUMBER,d_name VARCHAR2(30), location_id NUMBER);

BEGIN

INSRT INTO dep_details VALUES(001,'Admin',1010);

INSRT INTO dep_details VALUES(002,'HR',1010);

INSRT INTO dep_details VALUES(003,'Sales',1020);

INSRT INTO dep_details VALUES(004,'Marketing',1020);

commit;

END;

SELECT * FROM dep_details;

----------------------------

d_id d_name location_id

----------------------------

1 Admin 1010

2 HR 1010

3 Sales 1020
4 Marketing 1020

----------------------------

DECLARE

-->--Declaring parameterized cursor

CURSOR dep_det_c(p_location_id NUMBER) IS

SELECT * FROM dep_details d WHERE d.location_id = p_location_id;

all_data dep_details%ROWTYPE;

BEGIN

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

OPEN dep_det_c(1010);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

-->-- opening same cursor with different input value


OPEN dep_det_c(1020);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

END;

/*sample output*/

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 1 Department Name : Admin

Department id : 2 Department Name : HR

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 3 Department Name : Sales

Department id : 4 Department Name : Marketing

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Posted 21st October 2014 by Unknown


0 Add a comment

OCT

21

Handling Exception

Error Handling in oracle

ERROR

Any departure from the expected behavior of the system or program,

which stops the working of the system is an error.

Types : compile time error

Run time error

EXCEPTION

Any error or problem which one can handle and continue to work normally.

Handling Exception

When exception is raised, control passes to the exception section of the block.

i.e. EXCEPTION

WHEN name_of_exception THEN


Types : Pre Defined Exceptions

User Defined Exceptions

Predefined Exception

*********************

Oracle has predefined several exceptions that correspond to the most common oracle errors.

------------------------------------------------------------------------

Exception Oracle Error SQL Code Value

------------------------------------------------------------------------

ZERO_DIVIDE ORA-01476 -1476

NO_DATA_FOUND ORA-01403 +100

DUP_VAL_ON_INDEX ORA-00001 -1

TOO_MANY_ROWS ORA-01422 -1422

VALUE_ERROR ORA-06502 -6502

CURSOR_ALREADY_OPEN ORA-06511 -6511

OTHERS

------------------------------------------------------------------------

-->-- ZERO_DIVIDE --<--


Your program attempts to divide a number by zero.

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN ZERO_DIVIDE THEN

dbms_output.put_line('Divisor is equal to zero');

END;

-->-- NO_DATA_FOUND --<--

Single row SELECT returned no rows or your program referenced a deleted element in a nested
table

or an uninitialized element in an associative array (index-by table).

CREATE TABLE test_tb(id NUMBER PRIMARY KEY);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION
WHEN NO_DATA_FOUND THEN

dbms_output.put_line('There is no data inside the table');

END;

-->-- DUP_VAL_ON_INDEX --<--

A program attempted to insert duplicate values in a column that is constrained by a unique


index.

INSERT INTO test_tb VALUES (1);

INSERT INTO test_tb VALUES (2);

commit;

BEGIN

INSERT INTO test_tb VALUES (2);

EXCEPTION

WHEN DUP_VAL_ON_INDEX THEN

dbms_output.put_line('Duplicate values are not allowed');

END;

-->-- TOO_MANY_ROWS --<--


Single row SELECT returned multiple rows.

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN TOO_MANY_ROWS THEN

dbms_output.put_line('Query returning more than one row');

END;

DROP TABLE test_tb;

-->-- VALUE_ERROR --<--

An arithmetic, conversion, truncation, or size constraint error occurred.

DECLARE

num1 NUMBER(2);

BEGIN

num1 := 345;

EXCEPTION

WHEN VALUE_ERROR THEN

dbms_output.put_line('check the size of the variable');


END;

-->-- CURSOR_ALREADY_OPEN --<--

A program attempted to open an already opened cursor.

CREATE TABLE emp(id NUMBER, name VARCHAR2(30));

BEGIN

INSERT INTO emp VALUES(1,'Name1');

INSERT INTO emp VALUES(2,'Name2');

INSERT INTO emp VALUES(3,'Name3');

INSERT INTO emp VALUES(4,'Name4');

COMMIT;

END;

SELECT * FROM emp;

DECLARE

cursor emp_c IS

SELECT * FROM emp;

all_data emp%ROWTYPE;
BEGIN

OPEN emp_c;

OPEN emp_c;

NULL;

CLOSE emp_c;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

END;

DROP TABLE emp;

-->-- OTHERS --<--

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

WHEN OTHERS THEN

dbms_output.put_line('Some other error ' || SQLERRM);

END;
User Defined Exception

**********************

A user-defined exception is an error that is defined by the programmer.

User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,

exceptions have a type EXCEPTION and scope.

DECLARE

v_gender CHAR := '&gender';

gender_ex EXCEPTION;

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE gender_ex;

END IF;

dbms_output.put_line('Gender : '||v_gender);

EXCEPTION

WHEN gender_ex THEN

dbms_output.put_line('Please Enter valid gender');

END;
create table test_insert (id NUMBER, Name VARCHAR2(30));

DECLARE

abort_ex EXCEPTION;

BEGIN

FOR i IN 1..100

LOOP

BEGIN

IF mod(i,10)=0 THEN

RAISE abort_ex;

END IF;

INSERT INTO test_insert VALUES(i, 'Name'||i);

EXCEPTION

WHEN abort_ex THEN

NULL;

END;

END LOOP;

COMMIT;

END;

SELECT * FROM test_insert;

DROP TABLE test_insert;


SQLERRM and SQLCODE

********************

SQLCODE returns the current error code, and SQLERRM returns the current error message
text;

For user-defined exception SQLCODE returns 1 and SQLERRM returns “user-defined


exception”.

SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.

CREATE TABLE test_tb (id NUMBER);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

dbms_output.put_line(v_id);

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('SQLERRM : ' || SQLERRM);

dbms_output.put_line('SQLCODE : ' || SQLCODE);

END;

/*sample output*/

SQLERRM : ORA-01403: no data found


SQLCODE : 100

DROP TABLE test_tb;

PRAGMA EXCEPTION_INIT

*********************

Using this you can associate a named exception with a particular oracle error.

This gives you the ability to trap this error specifically, rather than via an OTHERS handler.

Syntax:

PRAGMA EXCEPTION_INIT(exception_name, oracle_error_number);

DECLARE

v_result NUMBER;

PRAGMA EXCEPTION_INIT(Invalid, -1476);

BEGIN

SELECT 453 / 0 INTO v_result FROM dual;

dbms_output.put_line('Result : ' || v_result);

EXCEPTION

WHEN INVALID THEN

dbms_output.put_line('Invalid Exception');

END;
RAISE_APPLICATION_ERROR

************************

You can use this built-in function to create your own error messages, which can be more
descriptive than named exceptions.

Error Number :

Oracle Error Range : From -00000 to -19999

User Error Range : From -20000 to -20999

DECLARE

v_gender CHAR := '&gender';

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE_APPLICATION_ERROR(-20003, 'Enter valid gender');

END IF;

dbms_output.put_line('Gender : ' || v_gender);

END;
Posted 21st October 2014 by Unknown

1 View comments

RajmohanMarch 13, 2018 at 6:49 AM

How to get the two table data without using Joins and sub query,union?

Reply

OCT

Package

1. You can groups logical related subprogram (procedures and functions)

2. It consist of two parts

I) specification

II) Body

3. It allows the oracle server to read multiple object in to a memory once

4. You can declare global variable,cursor, user define exeption

5. Overloading

6. we can't create anonyms block inside the package


create table err_log(sno NUMBER, u_name VARCHAR2(30), error_msg CLOB, hap_tm
TIMESTAMP);

select * from err_log;

--stand alone procedure

CREATE OR REPLACE PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id


%TYPE) IS

v_salary employees.salary%TYPE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT salary,

first_name

INTO v_salary,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line('Salary of ' || v_first_name || ' is ' || v_salary);

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log


VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_sal_sp;

BEGIN

-- Call the procedure

emp_sal_sp(p_employee_id => :p_employee_id);

END;

CREATE OR REPLACE PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id


%TYPE) IS

v_hire_date DATE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT hire_date,

first_name

INTO v_hire_date,

v_first_name

FROM employees
WHERE employee_id = p_employee_id;

dbms_output.put_line(v_first_name || ' hired on ' || to_char(v_hire_date,'month ddth,


yyyy'));

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_hdt_sp;

BEGIN

-- Call the procedure

emp_hdt_sp(p_employee_id => :p_employee_id);

END;

create or replace function sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER

IS
v_c NUMBER;

BEGIN

v_c := p_a + p_b;

RETURN v_c;

END;

--Specification Part

CREATE OR REPLACE PACKAGE emp_pkg

IS

PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id%TYPE);

PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id%TYPE);

FUNCTION sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER;

END emp_pkg ;

--Body Part

CREATE OR REPLACE PACKAGE BODY emp_pkg


IS

PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id%TYPE) IS

v_salary employees.salary%TYPE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT salary,

first_name

INTO v_salary,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line('Salary of ' || v_first_name || ' is ' || v_salary);

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_sal_sp;
PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id%TYPE) IS

v_hire_date DATE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT hire_date,

first_name

INTO v_hire_date,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line(v_first_name || ' hired on ' || to_char(v_hire_date,'month ddth,


yyyy'));

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_hdt_sp;
FUNCTION sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER

IS

v_c NUMBER;

BEGIN

v_c := p_a + p_b;

RETURN v_c;

END;

END emp_pkg;

A package specification can exist without a package body, but

a package body can't exist without a package specification.

--Executing procedure inside the package

BEGIN

emp_pkg.emp_sal_sp(120);

END;

--Executing function inside the package


SELECT emp_pkg.sum_fn(23,567) FROM dual;

-- You can declare global variable,cursor, user define exeption

create or replace package all_detail

as

PROCEDURE emp2sal (a IN NUMBER);

PROCEDURE emp2exep (a IN NUMBER);

FUNCTION add2num (a IN NUMBER, b IN NUMBER)

RETURN NUMBER;

c NUMBER(8); --global declaration

abort_ex EXCEPTION; --global exception declaration

CURSOR emp_rec --global cursor declaration

IS

SELECT first_name, salary, hire_date, department_id

FROM employees;

End all_detail;
create or replace package body all_detail

as

PROCEDURE emp2sal (a IN NUMBER)

AS

BEGIN

SELECT salary

INTO c

FROM Employees

WHERE Employee_id = a;

Dbms_output.put_line('Salary of Employee ' || a || ' is ' || c);

EXCEPTION

WHEN no_data_found THEN

Dbms_output.put_line('Please enter valid id');

END emp2sal;

PROCEDURE emp2exep (a IN NUMBER)

AS

BEGIN

SELECT Round(Months_between(sysdate,hire_date)/12)

INTO c
FROM Employees

WHERE Employee_id = a;

Dbms_output.put_line( c || ' Years');

EXCEPTION

WHEN no_data_found THEN

Dbms_output.put_line('Please enter valid id');

END emp2exep;

FUNCTION add2num (a IN NUMBER, b IN NUMBER)

RETURN NUMBER

AS

BEGIN

c := a+b;

RETURN C;

END;

End all_detail;

/*Declaring a Bodiless Package */

CREATE OR REPLACE PACKAGE global_constant


IS

mile_2_kilo CONSTANT NUMBER := 1.6093;

kilo_2_mile CONSTANT NUMBER := 0.6214;

yard_2_meter CONSTANT NUMBER := 0.9144;

meter_2_yard CONSTANT NUMBER := 1.0936;

END global_constant;

BEGIN

DBMS_OUTPUT.PUT_LINE('20 miles = ' || 20*global_constant.mile_2_kilo||' km');

END;

/*Forward Declaration in package */

DECLARE

PROCEDURE P2; -- forward declaration

PROCEDURE P3;

PROCEDURE P1 IS

BEGIN

dbms_output.put_line('From procedure p1');

p2;

END P1;
PROCEDURE P2 IS

BEGIN

dbms_output.put_line('From procedure p2');

p3;

END P2;

PROCEDURE P3 IS

BEGIN

dbms_output.put_line('From procedure p3');

END P3;

BEGIN

p1;

END;

sample output:

From procedure p1

From procedure p2

From procedure p3

Drop package package_name;

Drop package body package_name;


SELECT text FROM user_source u

WHERE u.name = 'EMP_PKG';

Interview Questions:

What is package?

Advantage of package

Is it possible to create package body with out package specification?

what is package overloading?

what is forward declaration in package?

which data dictionary table contain source code of package?

How to declare global variable, exception and cursor?

How to execute procedure and function inside the package?

Posted 4th October 2014 by Unknown

0 Add a comment

OCT

%TYPE and %ROWTYPE


--%type is used to fetch the data type of the particular column

create table product_details

p_id NUMBER(3),

p_nm VARCHAR2(30),

p_qty NUMBER(8),

order_dt DATE

);

BEGIN

INSERT INTO product_details VALUES(100,'Name0',400,'23-Mar-13');

INSERT INTO product_details VALUES(101,'Name1',600,'26-Apr-13');

INSERT INTO product_details VALUES(102,'Name2',800,'27-Jan-12');

INSERT INTO product_details VALUES(103,'Name3',300,'23-Jul-11');

INSERT INTO product_details VALUES(104,'Name4',200,'22-Aug-11');

INSERT INTO product_details VALUES(105,'Name5',500,'25-Oct-12');

commit;

END;

/
SELECT * FROM product_details;

------------------------------------

P_ID P_NM P_QTY ORDER_DT

------------------------------------

100 Name0 400 03/23/2013

101 Name1 600 04/26/2013

102 Name2 800 01/27/2012

103 Name3 300 07/23/2011

104 Name4 200 08/22/2011

105 Name5 500 10/25/2012

------------------------------------

DECLARE

v_name VARCHAR2(4);

BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 100;

dbms_output.put_line('Product Name : ' || v_name);

--error numeric or value error

END;
DECLARE

v_name VARCHAR2(5);

BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 100;

dbms_output.put_line('Product Name : ' || v_name);

END;

ALTER TABLE product_details

MODIFY p_nm VARCHAR2(15);

INSERT INTO product_details

VALUES

(106,

'name6',

700,

'26-Dec-12');
commit;

106 name6 700 12/26/2012

DECLARE

v_name VARCHAR2(5);

BEGIN

SELECT p_nm INTO v_name

FROM product_details

WHERE p_id = 106;

dbms_output.put_line('Product Name : ' || v_name);

--error

END;

DECLARE

v_name product_details.p_nm%TYPE;

BEGIN

SELECT p_nm

INTO v_name
FROM product_details

WHERE p_id = 106;

dbms_output.put_line('Product Name : ' || v_name);

END;

DROP TABLE product_details;

DECLARE

dep_id departments.department_id%TYPE;

dep_name departments.department_name%TYPE;

dep_man_id departments.manager_id%TYPE;

dep_loc_id departments.location_id%TYPE;

BEGIN

SELECT department_id,

department_name,

manager_id,

location_id

INTO dep_id,

dep_name,
dep_man_id,

dep_loc_id

FROM departments

WHERE department_id = 10;

dbms_output.put_line('Department_id : ' || dep_id);

dbms_output.put_line('Department_name : ' || dep_name);

dbms_output.put_line('Manager_id : ' || dep_man_id);

dbms_output.put_line('Location_id : ' || dep_loc_id);

END;

--%rowtype is used to fetch the data type of all the column

--Insted of using %type if we use %rowtype means we can reduce the no of variables that we
declare

DECLARE

dep_detail departments%ROWTYPE;

BEGIN

SELECT *

INTO dep_detail
FROM departments

WHERE department_id = 10;

dbms_output.put_line('Department_id : ' || dep_detail.department_id);

dbms_output.put_line('Department_name : ' || dep_detail.department_name);

dbms_output.put_line('Manager_id : ' || dep_detail.manager_id);

dbms_output.put_line('Location_id : ' || dep_detail.location_id);

END;

DROP TABLE dept_details;

CREATE TABLE dept_details

dept_id number(3) ,

dept_name varchar2(30),

dept_manager_name varchar2(30)

);

insert into dept_details values(10,'dept1','manager_name1');

insert into dept_details values(20,'dept2','manager_name2');


SELECT * FROM dept_details;

-------------------------------------------------------

| DEPT_ID | DEPT_NAME | DEPT_MANAGER_NAME |

+------------+-----------------------+-----------------

| 10 | dept1 | manager_name1 |

| 20 | dept2 | manager_name2 |

------------+-----------------------+------------------

DECLARE

all_data dept_details%ROWTYPE;

BEGIN

all_data.dept_id := 100;

all_data.dept_name := 'Admin';

all_data.dept_manager_name := 'John';

UPDATE dept_details

SET ROW = all_data

WHERE dept_id = 10;

dbms_output.put_line(SQL%ROWCOUNT || ' Row(s) get updated');

END;
/

1 Row(s) get updated

select * from dept_details;

---------------------------------------------------

| DEPT_ID | DEPT_NAME | DEPT_MANAGER_NAME|

---------------------------------------------------

| 100 | Admin | John |

| 20 | dept2 | manager_name2 |

---------------------------------------------------

Interview Question :

1. What is the use of %TYPE?

2. What is the use of %ROWTYPE?

3. Difference between %TYPE and %ROWTYPE?

Posted 2nd October 2014 by Unknown


0 Add a comment

SEP

29

BULK Exceptions

/************************************************************************

* Handling Exceptions in Bulk Operations *

* Documented on 29-SEP-14 04.35.35.980894 PM +05:30 *

* Document By : Murugappan Annamalai *

* Reference : http://www.dba-oracle.com/plsql/t_plsql_exceptions.htm *

************************************************************************/

CREATE TABLE bulk_tb (ran_num NUMBER NOT NULL);

--inserting data using bulk collect

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;


v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

commit;

END;

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

200

TRUNCATE TABLE bulk_tb;

sample2.sql --without exception part


DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

commit;

END;

/*

Error Message :
ORA-01400: cannot insert NULL into ("HR"."bulk_tb"."ran_num")

ORA-06512: at line 15

*/

sample2.sql --with exception part

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

BEGIN

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));


COMMIT;

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('Error while inserting bulk record '||SQLERRM);

END;

END;

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

99

SQL%BULK_EXCEPTIONS(i).ERROR_INDEX

Holds the iteration (not the subscript) of the original FORALL statement that raised the
exception.

In sparsely populated collections,

the exception row must be found by looping through the original collection the correct
number of times.
SQL%BULK_EXCEPTIONS(i).ERROR_CODE

Holds the exceptions error code.

The total number of exceptions can be returned using the collections COUNT method,

which returns zero if no exceptions were raised. The save_exceptions.sql script,

a modified version of the handled_exception.sql script, demonstrates this functionality.

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

v_ex_count NUMBER(4);

abort_ex EXCEPTION;

PRAGMA EXCEPTION_INIT(abort_ex, -24381);

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

v_dat(150) := NULL;
/* will cause error while inserting data into bulk_tb

because of not null constraint */

EXECUTE IMMEDIATE 'TRUNCATE TABLE bulk_tb';

BEGIN

FORALL i IN v_dat.FIRST..v_dat.LAST SAVE EXCEPTIONS

INSERT INTO bulk_tb VALUES(v_dat(i));

COMMIT;

EXCEPTION

WHEN abort_ex THEN

v_ex_count := SQL%BULK_EXCEPTIONS.COUNT;

FOR i IN 1..v_ex_count LOOP

dbms_output.put_line('Error: ' || i ||' Array Index: ' || SQL


%BULK_EXCEPTIONS(i).error_index ||

' Message: ' || SQLERRM(SQL%BULK_EXCEPTIONS(i).ERROR_CODE));

END LOOP;

END;

END;

/*

Sample output:

Error: 1 Array Index: 100 Message: -1400: non-ORACLE exception


Error: 2 Array Index: 150 Message: -1400: non-ORACLE exception

*/

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

198

SAVE EXCEPTIONS clause being removed, in the above script now traps a different error number.

The output from this script is listed below.

/*

Sample output:

Error: 1 Array Index: 100 Message: -1400: non-ORACLE exception

*/

SELECT COUNT(*) FROM bulk_tb;


COUNT(*)

-------

99

SELECT COUNT(*) FROM bulk_tb;

DROP TABLE bulk_tb;

Posted 29th September 2014 by Unknown

0 Add a comment

SEP

29

Cursor - FOR UPDATE

/************************************************************************

* FOR UPDATE clause in oracle *

* Document By : Murugappan Annamalai *

************************************************************************/
create table prod_details(p_id VARCHAR2(30), P_name VARCHAR2(30));

BEGIN

--Inserting data into prod_details table

FOR i IN 1..50 LOOP

INSERT INTO prod_details VALUES(i,'pname'||i);

END LOOP;

commit;

END;

SELECT * FROM prod_details;

DECLARE

CURSOR PROD_DTLS_C IS

SELECT * FROM PROD_DETAILS T1 FOR UPDATE OF P_ID;

V_PID PROD_DETAILS.P_ID%TYPE;

V_PRDNAME PROD_DETAILS.P_NAME%TYPE;
BEGIN

OPEN PROD_DTLS_C;

LOOP

FETCH PROD_DTLS_C INTO V_PID, V_PRDNAME;

IF PROD_DTLS_C%NOTFOUND THEN

EXIT;

ELSE

UPDATE PROD_DETAILS P

SET P.P_ID = LPAD(P_ID, 10, 0)

WHERE CURRENT OF PROD_DTLS_C;

END IF;

END LOOP;

CLOSE PROD_DTLS_C;

COMMIT;

END;

select * from PROD_DETAILS;

TRUNCATE TABLE prod_details;


BEGIN

--Inserting data into prod_details table

FOR i IN 1..50 LOOP

INSERT INTO prod_details VALUES(i,'pname'||i);

END LOOP;

commit;

END;

DECLARE

CURSOR PROD_DTLS_C IS

SELECT * FROM PROD_DETAILS T1 FOR UPDATE OF P_ID;

V_PID PROD_DETAILS.P_ID%TYPE;

V_PRDNAME PROD_DETAILS.P_NAME%TYPE;

BEGIN

OPEN PROD_DTLS_C;

LOOP

FETCH PROD_DTLS_C INTO V_PID, V_PRDNAME;


IF PROD_DTLS_C%NOTFOUND THEN

EXIT;

ELSE

UPDATE PROD_DETAILS P

SET P.P_ID = LPAD(P_ID, 10, 0)

WHERE CURRENT OF PROD_DTLS_C;

END IF;

COMMIT;

END LOOP;

CLOSE PROD_DTLS_C;

--COMMIT;

END;

select * from PROD_DETAILS;

Posted 29th September 2014 by Unknown

0 Add a comment

MAY

28

Escape Sequence in Oracle


Escape special characters when writing SQL queries

--to include single '

SELECT 'Steven's salary is more than 50k INR' AS "SAL_DETAILS"

FROM Dual;

ORA-01756 : quoted string not properly terminated

SELECT 'Steven''s salary is more than 50k INR' AS "SAL_DETAILS"

FROM Dual;

SAL_DETAILS

---------------------------------------

Steven's salary is more than 50k INR

--to include double '


SELECT 'You can print double quot ('''') in oracle' "Info"

FROM Dual;

Info

---------------------------------------

You can print double quot ('') in oracle

SELECT q'[some test ' some test ' some text ']' AS "In 10g"

FROM dual;

In 10g

------------------------------------

some test ' some test ' some text '

--Escape wild card characters ( _ and % )

The LIKE keyword allows for string searches.

The '_' wild card character is used to match exactly one character

While '%' is used to match zero or more occurrences of any characters.

These characters can be escaped in SQL as follows.

WITH mail_ids AS
(

SELECT 'an.murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an_murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an%murugappan@gmail.com' mail FROM Dual

SELECT * FROM mail_ids

WHERE mail LIKE '__$_%' ESCAPE '$';

mail

----------------------------------

an_murugappan@gmail.com

WITH mail_ids AS

SELECT 'an.murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an_murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an%murugappan@gmail.com' mail FROM Dual

SELECT * FROM mail_ids


WHERE mail LIKE '__/%%' ESCAPE '/';

mail

----------------------------------

an%murugappan@gmail.com

Escape ampersand (&) characters in SQL*Plus

SQL> select '&a' FROM dual;

'23'

----

23

SQL> SET ESCAPE '\'

SQL> select '\&a' FROM dual;

'&A'

----

&a

SQL> SET SCAN OFF;

SQL> select '&a' FROM dual;


'&A'

----

&a

SQL> SET SCAN ON;

SQL> select '&a' FROM dual;

'45'

----

45

Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Data Manipulation Language

Data Manipulation Language (DML) statements are used for managing data within schema
objects. Some examples:
INSERT - insert data into a table

UPDATE - updates existing data within a table

DELETE - deletes all records from a table, the space for the records remain

MERGE - UPSERT operation (insert or update)

CREATE TABLE prod_details

prod_id NUMBER(4) ,

prod_name VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

Deliver_dt DATE DEFAULT SYSDATE+3 ,

comments VARCHAR2(300)

);

SELECT * FROM prod_details;

no_data_found

INSERT

INSERT INTO prod_details(prod_id,prod_name,order_dt,deliver_dt,comments)

VALUES(100,'Apple iphone 5s','21-May-14','24-May-14','Color : Black');


SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

---------------------------------------------------------------------------

--Inserting records with out mentioning column name

INSERT INTO prod_details

VALUES(101,'Samsung Galaxy III','20-Aug-14','23-Aug-14','Color : White');

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

---------------------------------------------------------------------------

--Inserting selective number of values


INSERT INTO prod_details

VALUES(103,'Moto X','11-May-14','13-May-14');

ORA-00947 : not enough values

--While inserting selective number of values mentioning column name is compulsory.

INSERT INTO prod_details (prod_id,prod_name,order_dt,deliver_dt)

VALUES(103,'Moto X','11-May-14','13-May-14');

SELECT * FROM prod_details;

--------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

--------------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

--------------------------------------------------------------------------------

--Inserting NULL value.

--If you want to insert NULL value you can ignore that column at the time of inserting

--or we can use NULL keyword to insert NULL.


INSERT INTO prod_details

VALUES(104,'Moto G','19-May-14','22-May-14',NULL);

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Noto G 5/19/2014 5/22/2014

---------------------------------------------------------------------------

--if you are not providing values for order_dt and deliver_dt column default value can be taken.

INSERT INTO prod_details(prod_id,prod_name,comments)

VALUES(105,'Nokia Lumis 720p','Color : Red');

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS


----------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Moto G 5/19/2014 5/22/2014

105 Nokia Lumis 720p 5/26/2014 5/29/2014 Color : Red

---------------------------------------------------------------------------

--Inserting data by using sub query

CREATE TABLE test_tab (id NUMBER, Name VARCHAR2(30));

INSERT INTO test_tab VALUES(1,'Name1');

INSERT INTO test_tab VALUES(2,'Name2');

INSERT INTO test_tab VALUES(3,'Name3');

SELECT COUNT(*) FROM test_tab;

COUNT(*)

-------

--creating table by using sub query (with out data)


CREATE TABLE ins_chk

SELECT * FROM test_tab

WHERE id = 900;

SELECT COUNT(*) FROM ins_chk;

COUNT(*)

-------

--Inserting data by using sub query

--copying data from test_tab to ins_chk

INSERT INTO ins_chk (SELECT * FROM test_tab);

3 rows inserted in 0.047 seconds.

SELECT COUNT(*) FROM ins_chk;

COUNT(*)
-------

DROP TABLE test_tab;

DROP TABLE ins_chk;

UPDATE

Syntax :

UPDATE table_name

SET column1_name = column1_value,

column2_name = column2_value,

column2_name = column3_value,

columnn_name = columnn_value

WHERE condition(s);

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS


----------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Moto G 5/19/2014 5/22/2014

105 Nokia Lumis 720p 5/26/2014 5/29/2014 Color : Red

---------------------------------------------------------------------------

UPDATE prod_details ps

SET ps.prod_name = 'iphone 5s'

WHERE ps.prod_id = 100;

1 row updated in 0.031 seconds

SELECT *

FROM prod_details ps

WHERE ps.prod_id = 100;

--------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

--------------------------------------------------------------------

100 iphone 5s 5/21/2014 5/24/2014 Color : Black

--------------------------------------------------------------------

--update statement with out condition


--If you try to execute update statement without condition it'll update all the records inside the
table.

UPDATE prod_details ps

SET ps.comments = 'None';

5 row updated in 0.031 seconds

SELECT *

FROM prod_details ps;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 None

101 Samsung Galaxy III 8/20/2014 8/23/2014 None

103 Moto X 5/11/2014 5/24/2014 None

104 Moto G 5/19/2014 5/22/2014 None

105 Nokia Lumis 720p 5/26/2014 5/29/2014 None

----------------------------------------------------------------------

--if your update text contain ' means you can use following metnod (use '')

UPDATE prod_details ps

SET ps.comments = 'Some product''s are not available'


WHERE ps.prod_id = 100;

1 row updated in 0.031 seconds

SELECT *

FROM prod_details ps

WHERE ps.prod_id = 100;

------------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

------------------------------------------------------------------------------------

100 iphone 5s 5/21/2014 5/24/2014 Some product's are not available

------------------------------------------------------------------------------------

DELETE

Syntax:

DELETE FROM table_name

WHERE condition(s);

DELETE FROM prod_details

WHERE prod_id IN (104, 105);


2 row(S) deleted in 0.032 seconds

SELECT *

FROM prod_details ps;

---------------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Some product's are not available

101 Samsung Galaxy III 8/20/2014 8/23/2014 None

103 Moto X 5/11/2014 5/24/2014 None

---------------------------------------------------------------------------------------

DELETE FROM prod_details;

3 row(s) deleted in 0.062 seconds.

SELECT * FROM prod_details;

no rows selected.

DROP TABLE prod_details;


MERGE = Insert + Update

-- will update soon.

Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Data Define Language

Data Definition Language (DDL) statements are used to define the database structure or schema.

Some examples:

CREATE - to create objects in the database.

ALTER - alters the structure of the database.

ADD

RENAME

MODIFY
DROP

DROP - delete objects from the database

TRUNCATE - remove all records from a table,

including all spaces allocated for the records are removed.

COMMENT - add comments to the data dictionary.

RENAME - rename an object.

Creating Table

--------------------------------------------------------------------------

Data Types Size Default Size Explanation

--------------------------------------------------------------------------

NUMBER(P,S) P: 1 to 38 we can store number between 0-9

S: -84 to 127

VARCHAR2 4000 Bytes we can store 0-9, a-z, A-Z and special characters

CHAR 2000 Bytes 1

DATE 7 Used to store Date

TIMESTAMP Includes year, month, day, hour, minute, and seconds.

LONG 2 GB Only one long column is allowed in a table.

We can't use this column in ORDER BY clause.

CLOB 4 GB Character Large Object

BLOB Binary Larger Object

--------------------------------------------------------------------------
CREATE

ALTER : ADD RENAME MODIFY DROP RENAME

RENAME

DROP

TRUNCATE

--creating table

CREATE TABLE friends_details_tb

Name VARCHAR2(30) ,

Phone NUMBER(10) ,

Gender CHAR ,

dob DATE ,

other_details LONG ,

make_dtm TIMESTAMP

);

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)
PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

-----------------------------

--maximum you can keep 255 columns in a table

ALTER : Colum level operations

ADD RENAME MODIFY DROP

ADD : Used to add a column after the table hase been created

ALTER TABLE friends_details_tb

ADD email VARCHAR2(30);

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------
NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

EMAIL VARCHAR2(30)

-----------------------------

--adding multiple columns by using single ALTER statement

SYNTAX

ALTER TABLE friends_details_tb

ADD (

column_1 Data_type(size),

column_2 Data_type(size),

column_3 Data_type(size),

column_4 Data_type(size)

);

RENAME : Used to Rename a column


ALTER TABLE friends_details_tb

RENAME COLUMN email TO email_id;

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

MODIFY : Used to change the data type or size of the data type.

ALTER TABLE friends_details_tb

MODIFY other_details CLOB;


DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS CLOB

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

--Modifying multiple columns at a time

ALTER TABLE friends_details_tb

MODIFY ( column_name_1 old_datatype(new_size),

column_name_2 new_datatype(old_size),

column_name_3 new_datatype(new_size)

);

DROP : Used to drop the column after the table has been created.
ALTER TABLE friends_details_tb

DROP COLUMN other_details;

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

RENAME : Used to Rename a particular table.

SYNTAX

RENAME old_table_name TO new_table_name;

RENAME friends_details_tb TO fnd_det;


DESCRIBE fnd_det;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

TRUNCATE : Used to remove the entire content of the table (not a structure)

SYNTAX

TRUNCATE TABLE table_name;

TRUNCATE TABLE fnd_det;


DROP : Used to drop the tabel (Data + stucture of the table get removed from the database )

DROP TABLE fnd_det;

*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Statements in Oracle

Data Definition Language (DDL)

DDL statements are used to define the database structure or schema. Some examples:

CREATE - to create objects in the database

ALTER - alters the structure of the database

ADD

RENAME

MODIFY

DROP

DROP - delete objects from the database


TRUNCATE - remove all records from a table,

including all spaces allocated for the records are removed

RENAME - rename an object

Data Manipulation Language (DML)

DML statements are used for managing data within schema objects. Some examples:

INSERT - insert data into a table

UPDATE - updates existing data within a table

DELETE - deletes all records from a table, the space for the records remain

MERGE - UPSERT operation (insert or update)

Data Control Language (DCL)

DCL statements. Some examples:

GRANT - gives users access privileges to database

REVOKE - withdraw access privileges given with the GRANT command

Transaction Control (TCL)


TCL statements are used to manage the changes made by DML statements. It allows
statements to be grouped together into logical transactions.

COMMIT - save work done

SAVEPOINT - identify a point in a transaction to which you can later roll back

ROLLBACK - restore database to original since the last COMMIT

Posted 28th May 2014 by Unknown

0 Add a comment

MAY

19

DECODE and CASE statement

CREATE TABLE students (

roll_no NUMBER(4) ,

Name VARCHAR2(30) ,

dept_cd VARCHAR2(20) ,

total_marks NUMBER(3)

);
BEGIN

INSERT INTO students VALUES (2000,'Rahul','CSE',480);

INSERT INTO students VALUES (2001,'Bala','IT', 390);

INSERT INTO students VALUES (2002,'Ramesh','CSE',250);

INSERT INTO students VALUES (2003,'Karthi','EEE',185);

INSERT INTO students VALUES (2004,'Ravi','IT',345);

END;

SELECT * FROM students;

DECODE

Decode is a function. Its a Oracle one.

Works like IF-THEN-ELSE.

You can use DECODE only in SELECT clause.

In DECODE you can include 255 things include Exep, search , result and default value.

Example

SELECT roll_no,

NAME,

dept_cd,

DECODE(dept_cd,

'CSE',

'Computer Science and Engineering',


'IT',

'Information Technology',

'Default Value') AS "DEPARTMENT NAME"

FROM students;

Sample Output

------------------------------------------------------------

ROLL_NO NAME DEPT_CD DEPARTMENT NAME

------------------------------------------------------------

2000 Rahul CSE Computer Science and Engineering

2001 Bala IT Information Technology

2002 Ramesh CSE Computer Science and Engineering

2003 Karthi EEE Default Value

2004 Ravi IT Information Technology

------------------------------------------------------------

CASE

CASE is an expression. Its a ANSI standard.

Compare to DECODE case will be more faster.

Example

SELECT roll_no,

NAME,
dept_cd,

total_marks,

CASE

WHEN total_marks > 500 THEN

'A Grade'

WHEN total_marks > 400 THEN

'B Grade'

WHEN total_marks > 300 THEN

'C Grade'

ELSE

'U Grade'

END AS "GRADE"

FROM students;

-----------------------------------------------

ROLL_NO NAME DEPT_CD TOTAL_MARKS GRADE

-----------------------------------------------

2000 Rahul CSE 480 B Grade

2001 Bala IT 390 C Grade

2002 Ramesh CSE 250 U Grade

2003 Karthi EEE 185 U Grade

2004 Ravi IT 345 C Grade

-----------------------------------------------

Interview Questions:
What is DECODE?

What is CASE?

Difference between CASE and DECODE? Which one is faster?

Posted 19th May 2014 by Unknown

0 Add a comment

MAY

19

Sub Query

Query with in another query

1. Single Row sub query

2. Multi row Sub query

select * from employees;

Want to fetch the person Who are all getting salary more than Neena's salary ?

Neena's Salary : 17000


Select First_name, salary

From Employees

Where salary > 17000;

--change in Neena's salary won't work for the above query.

Select salary From Employees

Where First_name = 'Neena';

Sub Query :

Select First_name, salary

From Employees

Where salary > (

Select salary From Employees

Where First_name = 'Neena'

);

Select * from employees;


Select salary From Employees

Where First_name = 'Alexander';

Sub Query Returns one value it is called as Single row sub query

Sub Query Returns more than one value it is called as Multi row sub query

Single row sub query operators :

> < >= <= = <>

Multiple Row Sub query operators :

IN ALL ANY

Who are all getting salary more than the average salary?

Select

First_name,

Salary

From

Employees

WHERE
Salary > (

SELECT Round(avg(salary),0)

FROM Employees

);

Multiple Row Sub query (In ANY ALL)

Select First_name,Department_id, salary

From Employees

Where salary in(

Select Salary From Employees

Where First_name = 'Alexander'

);

Any : Minimum Value will be taken (3100)

Select First_name,Department_id, salary

From Employees

Where salary > ANY(

Select Salary From Employees

Where First_name = 'Alexander'

);
All : Maximum Value will be taken (9000)

Select First_name,Department_id, salary

From Employees

Where salary > All(

Select Salary From Employees

Where First_name = 'Alexander'

);

We can use sub query in all the classes except Group by and order by class.

Select

From

Where

-----------Group by

having

-----------Order by

SELECT

( Select Count(*) from Employees Where Department_id = 90 )Executive,

( Select Count(*) from Employees Where Department_id = 60 ) IT,

( Select Count(*) from Employees Where Department_id = 10 ) Administration,

( Select Count(*) from Employees Where Department_id = 100) Finance

FROM
Dual;

Select Min(salary) From Employees;

Select Min(salary) from

Select * from Employees

Where Department_id = 60

);

What is INLINE VIEW?

If u use sub query in From it is call it is as INLINE VIEW.

Intermediate result set

Correlated sub query

SELECT employee_number, name

FROM employees Bob

WHERE salary > (

SELECT AVG(salary)

FROM employees

WHERE department = Bob.department

);
Posted 19th May 2014 by Unknown

0 Add a comment

Loading

Dynamic Views theme. Powered by Blogger.

Oracle sql & Pl/sql

search

Home Sql and pl/sql Sql Interview Questions

JUL

20

INLINE view in Oracle with 12c New Features

Named sub Query in FROM clause is call it as INLINE VIEW.

Oracle process a inline view faster than sub query

Inline View in Oracle

--Query to display all the employees who are all getting salary more than their department
average salary
SELECT First_name

, last_name

, salary

, department_id

FROM employees a , ( SELECT b.department_id

, AVG(b.salary) avg_sal

FROM employees b

GROUP BY b.department_id

)b

WHERE a.department_id = b.department_id

AND a.salary > b.avg_salary;

Display all the customer who have placed more number of orders by using INLINE view

CREATE TABLE customer_order_det_tb

( custm_id NUMBER ,

custm_nm VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

ttl_amt NUMBER(7,2)

);

BEGIN

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '11-Jul-15' , 45000.00);


INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '14-Jul-15' , 27000.00);

INSERT INTO customer_order_det_tb VALUES(101, 'Raja' , '13-Jul-15' , 17000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 34000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 38000.00);

COMMIT;

END;

SELECT c.*

FROM customer_order_det_tb c;

--------------------------------------------

custm_id custm_nm order_dt ttl_amt

--------------------------------------------

100 Murugappan 7/11/2015 45000.00

100 Murugappan 7/14/2015 27000.00

101 Raja 7/13/2015 17000.00

102 Ramesh 7/15/2015 34000.00

102 Ramesh 7/15/2015 38000.00

--------------------------------------------

--Writing a Quer to display all the customer who have placed maximum number of order

--Query #1 for inline view


SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC;

--------------------------------

custm_id custm_nm total_odr

--------------------------------

100 Murugappan 2

102 Ramesh 2

101 Raja 1

--------------------------------

--Query #2 for inline view

SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm;

----------

total_odr

----------

----------
Inline view to find all the customers who have placed maximum number of orders

/****************************************

Syntax

SELECT * FROM <query1> x, <query2> y

WHERE contition;

****************************************/

SELECT query1.* FROM

( SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC

) query1,

( SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm

) query2

WHERE query1.total_odr = query2.total_odr;

-------------------------------

custm_id custm_nm total_odr

-------------------------------

100 Murugappan 2
102 Ramesh 2

-------------------------------

DROP TABLE customer_order_det_tb;

--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT

SELECT first_name, salary

FROM ( SELECT first_name, salary

FROM employees e

WHERE job_id NOT IN ('SALESMAN','PRESIDENT')

ORDER BY salary DESC

WHERE ROWNUM < 4;

New Oracle 12c Inline view Syntax

LATERAL clause for In-line views

Allows for columns in the inline view to be accessed!!

Example :
--in 11g

SELECT * FROM employees e, (

SELECT *

FROM departments d

WHERE e.department_id = d.department_id);

ORA-0090: "E"."DEPARTMENT_ID": Invalid Identifier

--in 12c

SELECT * FROM employees e, LATERAL(

SELECT *

FROM departments d

WHERE e.department_id = d.department_id

);

--in 11g

WITH t

AS

( SELECT LEVEL a

FROM dual

CONNECT BY LEVEL <= 30)

SELECT *

FROM t, (SELECT *
FROM employees

WHERE department_id = t.a

);

ORA-00904: "T"."A": invalid Identifier

--in 12c

WITH t

AS

(SELECT LEVEL a FROM dual CONNECT BY LEVEL <= 30)

SELECT * FROM t,

LATERAL(SELECT *

FROM employees

WHERE department_id = t.a);

Hope you have enjoyed this little article

Feed backs are always Welcome :) (:

Posted 20th July 2015 by Unknown

0 Add a comment

JAN

23

Salary Related Questions in Oracle


--creating table

CREATE TABLE employee_data

eid NUMBER(4),

ename VARCHAR2(30),

depno NUMBER(3),

salary NUMBER(8)

);

BEGIN

--Inserting records

INSERT INTO employee_data VALUES(1000,'Name01',90,30000);

INSERT INTO employee_data VALUES(1001,'Name02',90,6000);

INSERT INTO employee_data VALUES(1002,'Name03',90,23000);

INSERT INTO employee_data VALUES(1003,'Name04',60,35000);

INSERT INTO employee_data VALUES(1004,'Name05',60,60000);

INSERT INTO employee_data VALUES(1005,'Name06',60,30000);

INSERT INTO employee_data VALUES(1006,'Name07',80,36000);


INSERT INTO employee_data VALUES(1007,'Name08',80,29000);

INSERT INTO employee_data VALUES(1008,'Name09',80,37000);

INSERT INTO employee_data VALUES(1009,'Name10',80,41000);

COMMIT;

END;

SELECT * FROM employee_data

ORDER BY salary DESC;

--query to find maximum salary from employee_data table

SELECT MAX(salary) FROM employee_data;

--query to find minimum salary from employee_data table

SELECT MIN(salary) FROM employee_data;

--query to find second maximum salary from employee_data table

SELECT MAX(salary)

FROM employee_data

WHERE salary NOT IN (SELECT MAX(salary)

FROM employee_data);
--query to select 5th maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= 5);

--query to select nth maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= &n);

--query to select all the details of the employee whose getting nth maximum salary

SELECT *

FROM (SELECT emp.*,


rownum rn

FROM (SELECT *

FROM employee_data

ORDER BY salary DESC) emp)

WHERE rn = 9;

--same query using row_numbr( ) function

SELECT *

FROM (SELECT emp.*,

row_number() over(ORDER BY salary) rank

FROM employee_data emp)

WHERE rank = 9;

--same query using rank( ) function

SELECT *

FROM (SELECT emp.*,

rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--same query using dense_rank( ) function


SELECT *

FROM (SELECT emp.*,

dense_rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--query to display display maximum salary in all the department

SELECT e.depno "Department id",

MAX(salary) "Maximum Salary"

FROM employee_data e

GROUP BY e.depno;

--query to display all the employees who are all getting salary more than average salary of the
company

SELECT e.* FROM employee_data e

WHERE salary > (SELECT AVG(salary) FROM employee_data);

--query to display all the employees who are all getting salary more than their department
average salary

SELECT employee_id,

first_name,

salary
FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE department_id = OUT.department_id);

--query to display all the employees who are all getting salary more than their manager salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE employee_id = OUT.manager_id);

Documented By : Murugappan Annamalai

Posted on : 23-Jan-15 16:34:00 IST.

Hope you have enjoyed this little article

Feed backs are always welcome :)


Posted 23rd January 2015 by Unknown

7 View comments

JAN

22

Why prefer COALESCE over NVL

Documented By : Nimish Garg

I prefer using "COALESCE" over "NVL" is some of the scenarios. Last week One of my friend
asked me what is the advantage of using "COALESCE" where we can simply use "NVL". I simply
gave him the reply from Oracle Docs i.e. NVL lets you replace null (returned as a blank) with a
string in the results of a query and COALESCE returns the first non-null expr in the expression list.
Oracle Database uses short-circuit evaluation with "COALESCE".

He replied that he knows the difference, he knows that "COALESCE" can take multiple arguments
and so on. He was more interested in understanding "short-circuit evaluation" of "COALESCE"
and the scenarios where I prefer using "COALESCE" over "NVL".

To make him understand I created following function which takes One second in every execution
and simply returns '--null--' and executed 2 very similar queries one with NVL and other with
COALESCE.

SQL> create or replace function f_null return varchar2

2 is

3 begin

4 dbms_lock.sleep(1);
5 return '--null--';

6 end;

7 /

Function created.

Following are the queries which I used to demonstrate that NVL evaluates both arguments even
if the second argument is not used and COALESCE uses short-circuit evaluation i.e. it only
evaluates the arguments only if they are needed.

SQL> select e.empno, e.ename ename, nvl(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT


7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.

Elapsed: 00:00:14.01

SQL> select e.empno, e.ename ename, coalesce(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT


7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.

Elapsed: 00:00:01.01

Here we can see easily that the first query with NVL took 14+ seconds, one second for each
record even if the "f_null" value was used only in one record. On the contrary as mentioned in
Oracle Documentation "COALESCE" uses its "short-circuit evaluation" and "f_null" was called
only once and so second query took only One Second. "COALESCE" is certainly use less resources
than NVL.

Posted 22nd January 2015 by Unknown

0 Add a comment

DEC

21

Constraints

It Enforce Rule On Table


We can create constraint at the time of Creating Table

1. Column Level Declaration

2. Table Level Declaration

1. We can provide own name.

Format : [part_of_project_name-table_name-column_name-constraint_type]

Example : gmind_emp_id_pk _uk _ck _f

2. system name name

Format : sys_cn

Example : SYS_C405323

We can create constraint after the table has been created

Types
Primary Key

Not allowed Null value

Not allowed you to enter duplicate value

Ex : Employee_id, Student_id

Unique Key

allowed Null value

Not allowed you to enter duplicate value

Ex : Contact_no, email

Foreign Key

It will allowed you to enter NULL and Duplicate value.

c1(pk) : 1 2 3

c2(f) : 1 1 2 3 4 Not allowed

Allowed you to enter duplicate value and null value

Not Null

It will not allowed you to enter null value


Check

You can check your own condition

Simple Table for understanding

------------------------------------

Duplicate NULL

------------------------------------

Primary Key X X

Unique Key X Allowed

Foreign Key Allowed Allowed

------------------------------------

creating table with all constraint type

Create table my_stu_details

S_id Number(2),

S_name Varchar2(30) Not Null, --SYS_Cn

s_mail Varchar2(30),
s_gender char(1),

s_did Number(3),

Constraint my_stu_sid_pk PRIMARY KEY (s_id),

constraint my_stu_mail_uk UNIQUE (s_mail) ,

Constraint my_stu_gen_ck CHECK (s_gender IN ('M', 'F', 'm', 'f')),

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

);

DESC my_stu_details;

------------------------------------

Name Type Nullable

------------------------------------

S_ID NUMBER(2)

S_NAME VARCHAR2(30)

S_MAIL VARCHAR2(30) Y

S_GENDER CHAR(1) Y

S_DID NUMBER(3) Y

------------------------------------

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name1' , 'name1@gmail.com' , 'm' , 60 );


Select * from my_stu_details;

Validating Primary Key

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-00001: unique constraint (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (NULL, 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-01400: cannot insert NULL into (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (2 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

Select * from my_stu_details;


Validating NOT NULL Constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , NULL , 'name3@gmail.com' , 'F' , 80 );

ORA-01400: cannot insert NULL into ("HR"."MY_STU_DETAILS"."S_NAME")

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , 'Name3' , 'name3@gmail.com' , 'F' , 80 );

Select * from my_stu_details;

Validating Unique Key Constraint

--Duplicate Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , 'name3@gmail.com' , 'F' , 80 );


ORA-00001: unique constraint (HR.MY_STU_MAIL_UK) violated

--Null Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , null , 'M' , 70 );

Select * from my_stu_details;

Validating Check constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'j' , 70 );

ORA-02290: check constraint (HR.MY_STU_GEN_CK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'M' , 70 );

Select * from my_stu_details;


Validating Foreign Key

Select * from Departments;

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 3 );

ORA-02291: integrity constraint (HR.MY_STU_DID_FK) violated - parent key not found

Departments table : parent table

my_stu_details : Child table

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 90 );

Select * from my_stu_details;


--------------------------------------------------------

s_id s_name s_mail s_gender s_did

--------------------------------------------------------

1 name1 name1@gmail.com m 60

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 M 70

5 Name5 name5@gmail.com M 70

6 Name6 name6@gmail.com F 90

--------------------------------------------------------

Deleting the Primary key value which is referred by Foreign Key

Select * from Departments;

DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID

------------------------------------------------------------

60 IT 103 1400 <---- Delete

-- don't execute this query


--Delete From Departments

--Where Department_id = 60;

1) ON DELETE SET NULL

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

1 name1 name1@gmail.com m -

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

2) ON DELETE SET CASCADE

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70
5 Name5 name5@gmail.com M 70

-------------------------------------------------

Syntax

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE CASCADE

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE SET NULL

Constraint Related Data Dictionary Table information.

To view constraint Information

SELECT c.owner,

c.constraint_name,

c.constraint_type,

c.table_name,

c.r_constraint_name,

c.status

FROM user_constraints c

WHERE c.table_name = 'MY_STU_DETAILS';


------------------------------------------------------------------------------------

owner constraint_name constraint_type table_name r_constraint_name status

------------------------------------------------------------------------------------

HR SYS_C004023 C MY_STU_DETAILS ENABLED

HR MY_STU_GEN_CK C MY_STU_DETAILS ENABLED

HR MY_STU_SID_PK P MY_STU_DETAILS ENABLED

HR MY_STU_MAIL_UK U MY_STU_DETAILS ENABLED

HR MY_STU_DID_FK R MY_STU_DETAILS DEPT_ID_PK ENABLED

------------------------------------------------------------------------------------

To view constraint name with corresponding column name

SELECT * FROM user_cons_columns c

WHERE c.table_name = 'MY_STU_DETAILS';

-------------------------------------------------------------

owner constraint_name table_name column_name position

-------------------------------------------------------------

HR MY_STU_MAIL_UK MY_STU_DETAILS S_MAIL 1

HR MY_STU_SID_PK MY_STU_DETAILS S_ID 1

HR MY_STU_GEN_CK MY_STU_DETAILS S_GENDER


HR SYS_C004023 MY_STU_DETAILS S_NAME

HR MY_STU_DID_FK MY_STU_DETAILS S_DID 1

-------------------------------------------------------------

Creating Composite Primary Key

Creating Primary Key with more than one number of column

ALTER TABLE table_name

ADD CONSTRAINT constraint_name PRIMARY KEY(column1, column_2 , column3);

In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.

creating constraint after the table creation

ALTER TABLE table_name

ADD CONSTRAINT constraint_name CONSTRAINT_TYPE(column_name);

ALTER TABLE table_name

DROP CONSTRAINT constraint_name;


ALTER TABLE table_name

DROP PRIMARY KEY;

To drop related foreign key

ALTER TABLE table_name

DROP PRIMARY KEY CASCADE;

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name;

Disable constraint with related foreign key constraint

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name CASCADE;

ALTER TABLE table_name

ENABLE CONSTRAINT constraint_name;


Interview Questions

What are all the type of constraint available in oracle?

Difference between PRIMARY KEY and UNIQUE key.

Difference between PRIMARY KEY ans FOREIGN KEY.

Difference between UNIQUE key and FOREIGN KEY.

Is it possible to create tow primary key in single table.

Write a syntax to create FOREIGN constraint.

How to create constraint after the table has been created?

How to enable and disable a constraint.

Which data dictionary table contains information about constraints?

Which Data Dictionary table contains information about constraint with corresponding column
name?

What is composite primary key?

Explain ON DELETE CASCADE and ON DELETE SET NULL option.

~Thanks For Reading~

Post your valuable feedback below

Posted 21st December 2014 by Unknown


1 View comments

UnknownMay 22, 2017 at 12:39 AM

good

Reply

DEC

listagg in Oracle 11g

Oracle 11gR2 listagg built-in function allows for many table columns to be displayed within a
single row, a non-first-normal form display

Syntax :

listagg(column_value,'delimiter') WITHIN GROUP(ORDER BY column_name)

--Example 1:

CREATE TABLE test_ins(empid NUMBER,product VARCHAR2(30));

BEGIN

INSERT INTO test_ins VALUES( 101,'pendrive');

INSERT INTO test_ins VALUES( 102,'toy');


INSERT INTO test_ins VALUES( 101,'ipod');

INSERT INTO test_ins VALUES( 102,'hat');

INSERT INTO test_ins VALUES( 103,'cpu');

INSERT INTO test_ins VALUES( 104,'pen');

INSERT INTO test_ins VALUES( 104,'car');

INSERT INTO test_ins VALUES( 104,'mat');

INSERT INTO test_ins VALUES( 105,'tv');

INSERT INTO test_ins VALUES( 106,'laptop');

commit;

END;

SELECT * FROM test_ins;

SELECT empid "Employee",

listagg(product,

',') within

GROUP (ORDER BY empid) "Products"

FROM test_ins

GROUP BY empid;

-->-- Result set --<--


DROP TABLE test_ins;

-->-- Example 2

select department_id "Department id", listagg(first_name,', ') WITHIN GROUP(ORDER BY


employee_id) "Employees"

FROM employees

WHERE department_id IN (10,20,30,60)

GROUP BY department_id;

-->-- Result set --<--

Posted 4th December 2014 by Unknown


0 Add a comment

NOV

Condition and Looping Statement

IF

IF ELSE

Multiple IF ELSE

LOOP

FOR LOOP

WHILE LOOP

create table test_udt(id NUMBER, salary NUMBER);

BEGIN

INSERT INTO test_udt VALUES(001,23000);

INSERT INTO test_udt VALUES(002,43000);

INSERT INTO test_udt VALUES(003,78000);

INSERT INTO test_udt VALUES(004,25000);


INSERT INTO test_udt VALUES(005,26000);

INSERT INTO test_udt VALUES(006,90000);

Commit;

END;

select * from test_udt;

IF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 1;

IF v_salary > 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

END IF;
commit;

END;

IF ELSE

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

ELSE

UPDATE test_udt t

SET t.salary = v_salary+20007

WHERE t.id = v_id ;

END IF;
commit;

END;

--same example with less number of lines

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

v_salary := v_salary+10005;

ELSE

v_salary := v_salary+20007;

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;


commit;

END;

select * from test_udt;

Multiple IF ELSIF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 3;

IF v_id = 1 THEN

v_salary := 1000;

dbms_output.put_line('1 inside');

ELSIF v_id = 2 THEN

v_salary := 2000;

dbms_output.put_line('2 inside');

ELSIF v_id = 3 THEN


v_salary := 3000;

dbms_output.put_line('3 inside');

ELSIF v_id = 4 THEN

v_salary := 4000;

dbms_output.put_line('4 inside');

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

LOOP

--syntax

LOOP

--statements

--increment

--exit statement
END LOOP;

CREATE TABLE prod_details (pid VARCHAR2(3), pname VARCHAR2(30));

DECLARE

i NUMBER := 1;

x VARCHAR2(3);

BEGIN

LOOP

x := lpad(i,3,'0');

dbms_output.put_line('x value : '|| x);

INSERT INTO prod_details VALUES(i, 'Product '||i);

EXIT WHEN i >900;

i := i+1;

IF MOD(i,100) = 0 THEN

commit;

dbms_output.put_line('commit executed');

END IF;

END LOOP;

END;

SELECT * FROM prod_details ORDER BY 1;


DROP TABLE prod_details;

FOR LOOP

BEGIN

FOR I in 1..5

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

FOR LOOP - Reverse

BEGIN

FOR I in REVERSE 14..50

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

WHILE LOOP
DECLARE

i_val NUMBER:=0;

BEGIN

WHILE (i_val < 11)

LOOP

dbms_output.put_line('The value of I is '||i_val);

i_val := i_val + 1;

END LOOP;

END;

sample output:

The value of I is 0

The value of I is 1

The value of I is 2

The value of I is 3

The value of I is 4

The value of I is 5

The value of I is 6

The value of I is 7

The value of I is 8

The value of I is 9

The value of I is 10
Posted 8th November 2014 by Unknown

0 Add a comment

OCT

21

Bulk Collect

This is used for array fetches

With this you can retrieve multiple rows of data with a single round trip.

This reduces the number of context switches between the pl/sql and sql engines.

You can use bulk collect in both dynamic and static sql.

You can use bulk collect in select, fetch into and returning into clauses.

SQL engine automatically initializes and extends the collections you reference in the bulk
collect clause.

You can fetch into multiple collections with one column each.

You can use the limit clause of bulk collect to restrict the no of rows retrieved.

SELECT * FROM product_details;

-->-- Bulk collect in FETCH INTO --<--


DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Bulk collect in SELECT clause --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

BEGIN
SELECT * BULK COLLECT INTO dta FROM product_details;

FOR i IN dta.FIRST .. dta.LAST LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- LIMIT in Bulk collect --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta LIMIT 30;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;
/

-->-- Multiple fetches in INTO clause --<--

SELECT * FROM product_details;

DECLARE

TYPE alldata_typ1 IS TABLE OF product_details.p_id%TYPE;

TYPE alldata_typ2 IS TABLE OF product_details.p_name%TYPE;

dta1 alldata_typ1;

dta2 alldata_typ2;

CURSOR proddt_cur IS

SELECT p_id, p_name FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta1, dta2;

CLOSE proddt_cur;

FOR i IN dta1.FIRST .. dta1.COUNT LOOP

dbms_output.put_line('Department Id : ' || dta1(i));

END LOOP;
FOR i IN dta2.FIRST .. dta2.COUNT LOOP

dbms_output.put_line('Department Name : ' || dta2(i));

END LOOP;

END;

DROP TABLE dep_details;

DROP TABLE product_details;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Ref Cursor

This is unconstrained cursor which will return different types depends upon the user input.

Ref cursors cannot be closed implicitly.

Ref cursor with return type is called strong cursor.

Ref cursor without return type is called weak cursor.

You can declare ref cursor type in package spec as well as body.
You can declare ref cursor types in local subprograms or anonymous blocks.

CREATE OR REPLACE PROCEDURE ref_c_sp(dep_det_c IN OUT SYS_REFCURSOR)

AS

BEGIN

OPEN dep_det_c

FOR

SELECT * FROM dep_details d;

END;

DECLARE

dep_det_c SYS_REFCURSOR;

tab_data dep_details%ROWTYPE;

BEGIN

ref_c_sp(dep_det_c);

LOOP

FETCH dep_det_c INTO tab_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department Name : '|| tab_data.d_name);

END LOOP;

CLOSE dep_det_c;
END;

/*sample output*/

Department Name : Admin

Department Name : HR

Department Name : Sales

Department Name : Marketing

DROP PROCEDURE ref_c_sp;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Cursor

SQL Private work Area where the query get passed and executed.
Types

******

Implicit(SQL)

Explicit

-->-- advanced cursor types --<--

Parametrized Cursor

Ref Cursor

Implicit

********

ORACLE implicitly opens a cursor to process each SQL statement not associated with an
explicitly declared cursor.

PL/SQL lets you refer to the most recent implicit cursor as the SQL” cursor. So, although you
cannot use the OPEN,

FETCH, and CLOSE statements to control an implicit cursor, you can still use cursor attributes to
access information

about the most recently executed SQL statement.

Cursor Stages

**************

OPEN cursor_name

FETCH (with in loop)

CLOSE cursor_name
Explicit

The set of rows returned by a query can consist of zero, one, or multiple rows,

depending on how many rows meet your search criteria. When a query returns multiple rows,

you can explicitly define a cursor to process the rows. You use three commands to control the
cursor

Cursor Attributes

*****************

%FOUND

%NOTFOUND

%ISOPEN

%ROWCOUNT

%BULK_ROWCOUNT --<-- used to handle error while using bulk collection.

%BULK_EXCEPTIONS --<-- used to handle error while using bulk collection.

Cursor Declaration

DECLARE

CURSOR <cursor_name>

IS

<SELECT statement>

BEGIN

--> some stmt

END;
/

Cursor Loop

Loop

While Loop

For Loop

Cursor Clauses

Return

For update

Where current of

Bulk collect

-->-- creating table

create table product_details

p_id NUMBER,

p_name VARCHAR2(30),

p_order_dt DATE

);

-->-- Inserting data


BEGIN

FOR i IN 1 .. 75 LOOP

INSERT INTO product_details VALUES (i, 'prod_name_' || i, SYSDATE + i);

END LOOP;

commit;

END;

-->-- selecting data

SELECT * FROM product_details;

---------------------------------------------

p_id p_name p_order_dt

---------------------------------------------

1 prod_name_1 10/11/2014 3:48:32 PM

2 prod_name_2 10/12/2014 3:48:32 PM

3 prod_name_3 10/13/2014 3:48:32 PM

4 prod_name_4 10/14/2014 3:48:32 PM

5 prod_name_5 10/15/2014 3:48:32 PM

6 prod_name_6 10/16/2014 3:48:32 PM

7 prod_name_7 10/17/2014 3:48:32 PM

8 prod_name_8 10/18/2014 3:48:32 PM

9 prod_name_9 10/19/2014 3:48:32 PM

10 prod_name_10 10/20/2014 3:48:32 PM


11 prod_name_11 10/21/2014 3:48:32 PM

12 prod_name_12 10/22/2014 3:48:32 PM

13 prod_name_13 10/23/2014 3:48:32 PM

14 prod_name_14 10/24/2014 3:48:32 PM

15 prod_name_15 10/25/2014 3:48:32 PM

16 prod_name_16 10/26/2014 3:48:32 PM

17 prod_name_17 10/27/2014 3:48:32 PM

18 prod_name_18 10/28/2014 3:48:32 PM

19 prod_name_19 10/29/2014 3:48:32 PM

20 prod_name_20 10/30/2014 3:48:32 PM

---------------------------------------------

----------------------------------------------

Implicit Cursor

----------------------------------------------

--will update soon

----------------------------------------------

Explicit Cursor

----------------------------------------------

**********************************************

Processing cursor data by using LOOP


**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND; --<-- if next record not found means control will
come out from the loop

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )


Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

EXIT WHEN prod_detail_cur%FOUND; --<-- if next record found means control will come
out from the loop

END LOOP;

CLOSE prod_detail_cur;

END;
/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;
IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor Already closed

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration
CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

-->-- CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;
/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor closed

**********************************************

Processing cursor data by using WHILE LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

OPEN prod_detail_cur;

FETCH prod_detail_cur
INTO all_data;

WHILE prod_detail_cur%FOUND LOOP

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

FETCH prod_detail_cur

INTO all_data;

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

************************************************************

Processing cursor data by using FOR LOOP - CURSOR FOR LOOP

************************************************************
DECLARE

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

FOR i IN prod_detail_cur

LOOP

dbms_output.put_line('Product id : ' || i.p_id ||

' Product Name : ' || i.p_name ||

' ( Orderd on : ' || TRIM(i.p_order_dt) || ' )');

END LOOP;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

Parameterized Cursor
*********************

This was used when you are going to use the cursor in more than one place with different
values for the same where clause.

Cursor parameters must be in mode.

Cursor parameters may have default values.

The scope of cursor parameter is within the select statement.

CREATE TABLE dep_details(d_id NUMBER,d_name VARCHAR2(30), location_id NUMBER);

BEGIN

INSRT INTO dep_details VALUES(001,'Admin',1010);

INSRT INTO dep_details VALUES(002,'HR',1010);

INSRT INTO dep_details VALUES(003,'Sales',1020);

INSRT INTO dep_details VALUES(004,'Marketing',1020);

commit;

END;

SELECT * FROM dep_details;

----------------------------

d_id d_name location_id

----------------------------

1 Admin 1010
2 HR 1010

3 Sales 1020

4 Marketing 1020

----------------------------

DECLARE

-->--Declaring parameterized cursor

CURSOR dep_det_c(p_location_id NUMBER) IS

SELECT * FROM dep_details d WHERE d.location_id = p_location_id;

all_data dep_details%ROWTYPE;

BEGIN

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

OPEN dep_det_c(1010);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
-->-- opening same cursor with different input value

OPEN dep_det_c(1020);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

END;

/*sample output*/

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 1 Department Name : Admin

Department id : 2 Department Name : HR

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 3 Department Name : Sales

Department id : 4 Department Name : Marketing

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Handling Exception

Error Handling in oracle

ERROR

Any departure from the expected behavior of the system or program,

which stops the working of the system is an error.

Types : compile time error

Run time error

EXCEPTION

Any error or problem which one can handle and continue to work normally.

Handling Exception

When exception is raised, control passes to the exception section of the block.
i.e. EXCEPTION

WHEN name_of_exception THEN

Types : Pre Defined Exceptions

User Defined Exceptions

Predefined Exception

*********************

Oracle has predefined several exceptions that correspond to the most common oracle errors.

------------------------------------------------------------------------

Exception Oracle Error SQL Code Value

------------------------------------------------------------------------

ZERO_DIVIDE ORA-01476 -1476

NO_DATA_FOUND ORA-01403 +100

DUP_VAL_ON_INDEX ORA-00001 -1

TOO_MANY_ROWS ORA-01422 -1422

VALUE_ERROR ORA-06502 -6502

CURSOR_ALREADY_OPEN ORA-06511 -6511

OTHERS

------------------------------------------------------------------------
-->-- ZERO_DIVIDE --<--

Your program attempts to divide a number by zero.

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN ZERO_DIVIDE THEN

dbms_output.put_line('Divisor is equal to zero');

END;

-->-- NO_DATA_FOUND --<--

Single row SELECT returned no rows or your program referenced a deleted element in a nested
table

or an uninitialized element in an associative array (index-by table).

CREATE TABLE test_tb(id NUMBER PRIMARY KEY);

DECLARE

v_id NUMBER;

BEGIN
SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN NO_DATA_FOUND THEN

dbms_output.put_line('There is no data inside the table');

END;

-->-- DUP_VAL_ON_INDEX --<--

A program attempted to insert duplicate values in a column that is constrained by a unique


index.

INSERT INTO test_tb VALUES (1);

INSERT INTO test_tb VALUES (2);

commit;

BEGIN

INSERT INTO test_tb VALUES (2);

EXCEPTION

WHEN DUP_VAL_ON_INDEX THEN

dbms_output.put_line('Duplicate values are not allowed');

END;
-->-- TOO_MANY_ROWS --<--

Single row SELECT returned multiple rows.

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN TOO_MANY_ROWS THEN

dbms_output.put_line('Query returning more than one row');

END;

DROP TABLE test_tb;

-->-- VALUE_ERROR --<--

An arithmetic, conversion, truncation, or size constraint error occurred.

DECLARE

num1 NUMBER(2);

BEGIN

num1 := 345;

EXCEPTION
WHEN VALUE_ERROR THEN

dbms_output.put_line('check the size of the variable');

END;

-->-- CURSOR_ALREADY_OPEN --<--

A program attempted to open an already opened cursor.

CREATE TABLE emp(id NUMBER, name VARCHAR2(30));

BEGIN

INSERT INTO emp VALUES(1,'Name1');

INSERT INTO emp VALUES(2,'Name2');

INSERT INTO emp VALUES(3,'Name3');

INSERT INTO emp VALUES(4,'Name4');

COMMIT;

END;

SELECT * FROM emp;

DECLARE

cursor emp_c IS
SELECT * FROM emp;

all_data emp%ROWTYPE;

BEGIN

OPEN emp_c;

OPEN emp_c;

NULL;

CLOSE emp_c;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

END;

DROP TABLE emp;

-->-- OTHERS --<--

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

WHEN OTHERS THEN


dbms_output.put_line('Some other error ' || SQLERRM);

END;

User Defined Exception

**********************

A user-defined exception is an error that is defined by the programmer.

User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,

exceptions have a type EXCEPTION and scope.

DECLARE

v_gender CHAR := '&gender';

gender_ex EXCEPTION;

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE gender_ex;

END IF;

dbms_output.put_line('Gender : '||v_gender);

EXCEPTION

WHEN gender_ex THEN

dbms_output.put_line('Please Enter valid gender');

END;
create table test_insert (id NUMBER, Name VARCHAR2(30));

DECLARE

abort_ex EXCEPTION;

BEGIN

FOR i IN 1..100

LOOP

BEGIN

IF mod(i,10)=0 THEN

RAISE abort_ex;

END IF;

INSERT INTO test_insert VALUES(i, 'Name'||i);

EXCEPTION

WHEN abort_ex THEN

NULL;

END;

END LOOP;

COMMIT;

END;

SELECT * FROM test_insert;

DROP TABLE test_insert;


SQLERRM and SQLCODE

********************

SQLCODE returns the current error code, and SQLERRM returns the current error message
text;

For user-defined exception SQLCODE returns 1 and SQLERRM returns “user-defined


exception”.

SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.

CREATE TABLE test_tb (id NUMBER);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

dbms_output.put_line(v_id);

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('SQLERRM : ' || SQLERRM);

dbms_output.put_line('SQLCODE : ' || SQLCODE);

END;

/*sample output*/
SQLERRM : ORA-01403: no data found

SQLCODE : 100

DROP TABLE test_tb;

PRAGMA EXCEPTION_INIT

*********************

Using this you can associate a named exception with a particular oracle error.

This gives you the ability to trap this error specifically, rather than via an OTHERS handler.

Syntax:

PRAGMA EXCEPTION_INIT(exception_name, oracle_error_number);

DECLARE

v_result NUMBER;

PRAGMA EXCEPTION_INIT(Invalid, -1476);

BEGIN

SELECT 453 / 0 INTO v_result FROM dual;

dbms_output.put_line('Result : ' || v_result);

EXCEPTION

WHEN INVALID THEN


dbms_output.put_line('Invalid Exception');

END;

RAISE_APPLICATION_ERROR

************************

You can use this built-in function to create your own error messages, which can be more
descriptive than named exceptions.

Error Number :

Oracle Error Range : From -00000 to -19999

User Error Range : From -20000 to -20999

DECLARE

v_gender CHAR := '&gender';

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE_APPLICATION_ERROR(-20003, 'Enter valid gender');

END IF;

dbms_output.put_line('Gender : ' || v_gender);

END;
Posted 21st October 2014 by Unknown

1 View comments

RajmohanMarch 13, 2018 at 6:49 AM

How to get the two table data without using Joins and sub query,union?

Reply

OCT

Package

1. You can groups logical related subprogram (procedures and functions)

2. It consist of two parts

I) specification

II) Body

3. It allows the oracle server to read multiple object in to a memory once

4. You can declare global variable,cursor, user define exeption

5. Overloading

6. we can't create anonyms block inside the package


create table err_log(sno NUMBER, u_name VARCHAR2(30), error_msg CLOB, hap_tm
TIMESTAMP);

select * from err_log;

--stand alone procedure

CREATE OR REPLACE PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id


%TYPE) IS

v_salary employees.salary%TYPE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT salary,

first_name

INTO v_salary,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line('Salary of ' || v_first_name || ' is ' || v_salary);

EXCEPTION

WHEN OTHERS THEN


v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_sal_sp;

BEGIN

-- Call the procedure

emp_sal_sp(p_employee_id => :p_employee_id);

END;

CREATE OR REPLACE PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id


%TYPE) IS

v_hire_date DATE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT hire_date,

first_name

INTO v_hire_date,
v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line(v_first_name || ' hired on ' || to_char(v_hire_date,'month ddth,


yyyy'));

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_hdt_sp;

BEGIN

-- Call the procedure

emp_hdt_sp(p_employee_id => :p_employee_id);

END;

create or replace function sum_fn (p_a IN NUMBER, p_b IN NUMBER)


RETURN NUMBER

IS

v_c NUMBER;

BEGIN

v_c := p_a + p_b;

RETURN v_c;

END;

--Specification Part

CREATE OR REPLACE PACKAGE emp_pkg

IS

PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id%TYPE);

PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id%TYPE);

FUNCTION sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER;

END emp_pkg ;

--Body Part
CREATE OR REPLACE PACKAGE BODY emp_pkg

IS

PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id%TYPE) IS

v_salary employees.salary%TYPE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT salary,

first_name

INTO v_salary,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line('Salary of ' || v_first_name || ' is ' || v_salary);

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);
commit;

END emp_sal_sp;

PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id%TYPE) IS

v_hire_date DATE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT hire_date,

first_name

INTO v_hire_date,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line(v_first_name || ' hired on ' || to_char(v_hire_date,'month ddth,


yyyy'));

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);
commit;

END emp_hdt_sp;

FUNCTION sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER

IS

v_c NUMBER;

BEGIN

v_c := p_a + p_b;

RETURN v_c;

END;

END emp_pkg;

A package specification can exist without a package body, but

a package body can't exist without a package specification.

--Executing procedure inside the package

BEGIN

emp_pkg.emp_sal_sp(120);

END;
--Executing function inside the package

SELECT emp_pkg.sum_fn(23,567) FROM dual;

-- You can declare global variable,cursor, user define exeption

create or replace package all_detail

as

PROCEDURE emp2sal (a IN NUMBER);

PROCEDURE emp2exep (a IN NUMBER);

FUNCTION add2num (a IN NUMBER, b IN NUMBER)

RETURN NUMBER;

c NUMBER(8); --global declaration

abort_ex EXCEPTION; --global exception declaration

CURSOR emp_rec --global cursor declaration

IS

SELECT first_name, salary, hire_date, department_id

FROM employees;

End all_detail;
create or replace package body all_detail

as

PROCEDURE emp2sal (a IN NUMBER)

AS

BEGIN

SELECT salary

INTO c

FROM Employees

WHERE Employee_id = a;

Dbms_output.put_line('Salary of Employee ' || a || ' is ' || c);

EXCEPTION

WHEN no_data_found THEN

Dbms_output.put_line('Please enter valid id');

END emp2sal;

PROCEDURE emp2exep (a IN NUMBER)

AS

BEGIN
SELECT Round(Months_between(sysdate,hire_date)/12)

INTO c

FROM Employees

WHERE Employee_id = a;

Dbms_output.put_line( c || ' Years');

EXCEPTION

WHEN no_data_found THEN

Dbms_output.put_line('Please enter valid id');

END emp2exep;

FUNCTION add2num (a IN NUMBER, b IN NUMBER)

RETURN NUMBER

AS

BEGIN

c := a+b;

RETURN C;

END;

End all_detail;

/*Declaring a Bodiless Package */


CREATE OR REPLACE PACKAGE global_constant

IS

mile_2_kilo CONSTANT NUMBER := 1.6093;

kilo_2_mile CONSTANT NUMBER := 0.6214;

yard_2_meter CONSTANT NUMBER := 0.9144;

meter_2_yard CONSTANT NUMBER := 1.0936;

END global_constant;

BEGIN

DBMS_OUTPUT.PUT_LINE('20 miles = ' || 20*global_constant.mile_2_kilo||' km');

END;

/*Forward Declaration in package */

DECLARE

PROCEDURE P2; -- forward declaration

PROCEDURE P3;

PROCEDURE P1 IS

BEGIN

dbms_output.put_line('From procedure p1');

p2;
END P1;

PROCEDURE P2 IS

BEGIN

dbms_output.put_line('From procedure p2');

p3;

END P2;

PROCEDURE P3 IS

BEGIN

dbms_output.put_line('From procedure p3');

END P3;

BEGIN

p1;

END;

sample output:

From procedure p1

From procedure p2

From procedure p3

Drop package package_name;


Drop package body package_name;

SELECT text FROM user_source u

WHERE u.name = 'EMP_PKG';

Interview Questions:

What is package?

Advantage of package

Is it possible to create package body with out package specification?

what is package overloading?

what is forward declaration in package?

which data dictionary table contain source code of package?

How to declare global variable, exception and cursor?

How to execute procedure and function inside the package?

Posted 4th October 2014 by Unknown

0 Add a comment

OCT
2

%TYPE and %ROWTYPE

--%type is used to fetch the data type of the particular column

create table product_details

p_id NUMBER(3),

p_nm VARCHAR2(30),

p_qty NUMBER(8),

order_dt DATE

);

BEGIN

INSERT INTO product_details VALUES(100,'Name0',400,'23-Mar-13');

INSERT INTO product_details VALUES(101,'Name1',600,'26-Apr-13');

INSERT INTO product_details VALUES(102,'Name2',800,'27-Jan-12');

INSERT INTO product_details VALUES(103,'Name3',300,'23-Jul-11');

INSERT INTO product_details VALUES(104,'Name4',200,'22-Aug-11');

INSERT INTO product_details VALUES(105,'Name5',500,'25-Oct-12');

commit;

END;
/

SELECT * FROM product_details;

------------------------------------

P_ID P_NM P_QTY ORDER_DT

------------------------------------

100 Name0 400 03/23/2013

101 Name1 600 04/26/2013

102 Name2 800 01/27/2012

103 Name3 300 07/23/2011

104 Name4 200 08/22/2011

105 Name5 500 10/25/2012

------------------------------------

DECLARE

v_name VARCHAR2(4);

BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 100;

dbms_output.put_line('Product Name : ' || v_name);


--error numeric or value error

END;

DECLARE

v_name VARCHAR2(5);

BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 100;

dbms_output.put_line('Product Name : ' || v_name);

END;

ALTER TABLE product_details

MODIFY p_nm VARCHAR2(15);

INSERT INTO product_details

VALUES

(106,

'name6',

700,
'26-Dec-12');

commit;

106 name6 700 12/26/2012

DECLARE

v_name VARCHAR2(5);

BEGIN

SELECT p_nm INTO v_name

FROM product_details

WHERE p_id = 106;

dbms_output.put_line('Product Name : ' || v_name);

--error

END;

DECLARE

v_name product_details.p_nm%TYPE;

BEGIN
SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 106;

dbms_output.put_line('Product Name : ' || v_name);

END;

DROP TABLE product_details;

DECLARE

dep_id departments.department_id%TYPE;

dep_name departments.department_name%TYPE;

dep_man_id departments.manager_id%TYPE;

dep_loc_id departments.location_id%TYPE;

BEGIN

SELECT department_id,

department_name,

manager_id,

location_id
INTO dep_id,

dep_name,

dep_man_id,

dep_loc_id

FROM departments

WHERE department_id = 10;

dbms_output.put_line('Department_id : ' || dep_id);

dbms_output.put_line('Department_name : ' || dep_name);

dbms_output.put_line('Manager_id : ' || dep_man_id);

dbms_output.put_line('Location_id : ' || dep_loc_id);

END;

--%rowtype is used to fetch the data type of all the column

--Insted of using %type if we use %rowtype means we can reduce the no of variables that we
declare

DECLARE

dep_detail departments%ROWTYPE;

BEGIN
SELECT *

INTO dep_detail

FROM departments

WHERE department_id = 10;

dbms_output.put_line('Department_id : ' || dep_detail.department_id);

dbms_output.put_line('Department_name : ' || dep_detail.department_name);

dbms_output.put_line('Manager_id : ' || dep_detail.manager_id);

dbms_output.put_line('Location_id : ' || dep_detail.location_id);

END;

DROP TABLE dept_details;

CREATE TABLE dept_details

dept_id number(3) ,

dept_name varchar2(30),

dept_manager_name varchar2(30)

);

insert into dept_details values(10,'dept1','manager_name1');


insert into dept_details values(20,'dept2','manager_name2');

SELECT * FROM dept_details;

-------------------------------------------------------

| DEPT_ID | DEPT_NAME | DEPT_MANAGER_NAME |

+------------+-----------------------+-----------------

| 10 | dept1 | manager_name1 |

| 20 | dept2 | manager_name2 |

------------+-----------------------+------------------

DECLARE

all_data dept_details%ROWTYPE;

BEGIN

all_data.dept_id := 100;

all_data.dept_name := 'Admin';

all_data.dept_manager_name := 'John';

UPDATE dept_details

SET ROW = all_data

WHERE dept_id = 10;

dbms_output.put_line(SQL%ROWCOUNT || ' Row(s) get updated');


END;

1 Row(s) get updated

select * from dept_details;

---------------------------------------------------

| DEPT_ID | DEPT_NAME | DEPT_MANAGER_NAME|

---------------------------------------------------

| 100 | Admin | John |

| 20 | dept2 | manager_name2 |

---------------------------------------------------

Interview Question :

1. What is the use of %TYPE?

2. What is the use of %ROWTYPE?

3. Difference between %TYPE and %ROWTYPE?


Posted 2nd October 2014 by Unknown

0 Add a comment

SEP

29

BULK Exceptions

/************************************************************************

* Handling Exceptions in Bulk Operations *

* Documented on 29-SEP-14 04.35.35.980894 PM +05:30 *

* Document By : Murugappan Annamalai *

* Reference : http://www.dba-oracle.com/plsql/t_plsql_exceptions.htm *

************************************************************************/

CREATE TABLE bulk_tb (ran_num NUMBER NOT NULL);

--inserting data using bulk collect


DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

commit;

END;

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

200

TRUNCATE TABLE bulk_tb;


sample2.sql --without exception part

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

commit;

END;
/*

Error Message :

ORA-01400: cannot insert NULL into ("HR"."bulk_tb"."ran_num")

ORA-06512: at line 15

*/

sample2.sql --with exception part

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

BEGIN
FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

COMMIT;

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('Error while inserting bulk record '||SQLERRM);

END;

END;

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

99

SQL%BULK_EXCEPTIONS(i).ERROR_INDEX

Holds the iteration (not the subscript) of the original FORALL statement that raised the
exception.

In sparsely populated collections,

the exception row must be found by looping through the original collection the correct
number of times.

SQL%BULK_EXCEPTIONS(i).ERROR_CODE

Holds the exceptions error code.

The total number of exceptions can be returned using the collections COUNT method,

which returns zero if no exceptions were raised. The save_exceptions.sql script,

a modified version of the handled_exception.sql script, demonstrates this functionality.

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

v_ex_count NUMBER(4);

abort_ex EXCEPTION;

PRAGMA EXCEPTION_INIT(abort_ex, -24381);

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;
v_dat(100) := NULL;

v_dat(150) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

EXECUTE IMMEDIATE 'TRUNCATE TABLE bulk_tb';

BEGIN

FORALL i IN v_dat.FIRST..v_dat.LAST SAVE EXCEPTIONS

INSERT INTO bulk_tb VALUES(v_dat(i));

COMMIT;

EXCEPTION

WHEN abort_ex THEN

v_ex_count := SQL%BULK_EXCEPTIONS.COUNT;

FOR i IN 1..v_ex_count LOOP

dbms_output.put_line('Error: ' || i ||' Array Index: ' || SQL


%BULK_EXCEPTIONS(i).error_index ||

' Message: ' || SQLERRM(SQL%BULK_EXCEPTIONS(i).ERROR_CODE));

END LOOP;

END;

END;

/*
Sample output:

Error: 1 Array Index: 100 Message: -1400: non-ORACLE exception

Error: 2 Array Index: 150 Message: -1400: non-ORACLE exception

*/

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

198

SAVE EXCEPTIONS clause being removed, in the above script now traps a different error number.

The output from this script is listed below.

/*

Sample output:

Error: 1 Array Index: 100 Message: -1400: non-ORACLE exception

*/
SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

99

SELECT COUNT(*) FROM bulk_tb;

DROP TABLE bulk_tb;

Posted 29th September 2014 by Unknown

0 Add a comment

SEP

29

Cursor - FOR UPDATE

/************************************************************************

* FOR UPDATE clause in oracle *


* Document By : Murugappan Annamalai *

************************************************************************/

create table prod_details(p_id VARCHAR2(30), P_name VARCHAR2(30));

BEGIN

--Inserting data into prod_details table

FOR i IN 1..50 LOOP

INSERT INTO prod_details VALUES(i,'pname'||i);

END LOOP;

commit;

END;

SELECT * FROM prod_details;

DECLARE

CURSOR PROD_DTLS_C IS

SELECT * FROM PROD_DETAILS T1 FOR UPDATE OF P_ID;


V_PID PROD_DETAILS.P_ID%TYPE;

V_PRDNAME PROD_DETAILS.P_NAME%TYPE;

BEGIN

OPEN PROD_DTLS_C;

LOOP

FETCH PROD_DTLS_C INTO V_PID, V_PRDNAME;

IF PROD_DTLS_C%NOTFOUND THEN

EXIT;

ELSE

UPDATE PROD_DETAILS P

SET P.P_ID = LPAD(P_ID, 10, 0)

WHERE CURRENT OF PROD_DTLS_C;

END IF;

END LOOP;

CLOSE PROD_DTLS_C;

COMMIT;

END;

select * from PROD_DETAILS;


TRUNCATE TABLE prod_details;

BEGIN

--Inserting data into prod_details table

FOR i IN 1..50 LOOP

INSERT INTO prod_details VALUES(i,'pname'||i);

END LOOP;

commit;

END;

DECLARE

CURSOR PROD_DTLS_C IS

SELECT * FROM PROD_DETAILS T1 FOR UPDATE OF P_ID;

V_PID PROD_DETAILS.P_ID%TYPE;

V_PRDNAME PROD_DETAILS.P_NAME%TYPE;

BEGIN

OPEN PROD_DTLS_C;
LOOP

FETCH PROD_DTLS_C INTO V_PID, V_PRDNAME;

IF PROD_DTLS_C%NOTFOUND THEN

EXIT;

ELSE

UPDATE PROD_DETAILS P

SET P.P_ID = LPAD(P_ID, 10, 0)

WHERE CURRENT OF PROD_DTLS_C;

END IF;

COMMIT;

END LOOP;

CLOSE PROD_DTLS_C;

--COMMIT;

END;

select * from PROD_DETAILS;

Posted 29th September 2014 by Unknown

0 Add a comment

MAY
28

Escape Sequence in Oracle

Escape special characters when writing SQL queries

--to include single '

SELECT 'Steven's salary is more than 50k INR' AS "SAL_DETAILS"

FROM Dual;

ORA-01756 : quoted string not properly terminated

SELECT 'Steven''s salary is more than 50k INR' AS "SAL_DETAILS"

FROM Dual;

SAL_DETAILS

---------------------------------------

Steven's salary is more than 50k INR

--to include double '


SELECT 'You can print double quot ('''') in oracle' "Info"

FROM Dual;

Info

---------------------------------------

You can print double quot ('') in oracle

SELECT q'[some test ' some test ' some text ']' AS "In 10g"

FROM dual;

In 10g

------------------------------------

some test ' some test ' some text '

--Escape wild card characters ( _ and % )

The LIKE keyword allows for string searches.

The '_' wild card character is used to match exactly one character

While '%' is used to match zero or more occurrences of any characters.

These characters can be escaped in SQL as follows.


WITH mail_ids AS

SELECT 'an.murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an_murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an%murugappan@gmail.com' mail FROM Dual

SELECT * FROM mail_ids

WHERE mail LIKE '__$_%' ESCAPE '$';

mail

----------------------------------

an_murugappan@gmail.com

WITH mail_ids AS

SELECT 'an.murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an_murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an%murugappan@gmail.com' mail FROM Dual


)

SELECT * FROM mail_ids

WHERE mail LIKE '__/%%' ESCAPE '/';

mail

----------------------------------

an%murugappan@gmail.com

Escape ampersand (&) characters in SQL*Plus

SQL> select '&a' FROM dual;

'23'

----

23

SQL> SET ESCAPE '\'

SQL> select '\&a' FROM dual;

'&A'

----

&a
SQL> SET SCAN OFF;

SQL> select '&a' FROM dual;

'&A'

----

&a

SQL> SET SCAN ON;

SQL> select '&a' FROM dual;

'45'

----

45

Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Data Manipulation Language


Data Manipulation Language (DML) statements are used for managing data within schema
objects. Some examples:

INSERT - insert data into a table

UPDATE - updates existing data within a table

DELETE - deletes all records from a table, the space for the records remain

MERGE - UPSERT operation (insert or update)

CREATE TABLE prod_details

prod_id NUMBER(4) ,

prod_name VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

Deliver_dt DATE DEFAULT SYSDATE+3 ,

comments VARCHAR2(300)

);

SELECT * FROM prod_details;

no_data_found

INSERT
INSERT INTO prod_details(prod_id,prod_name,order_dt,deliver_dt,comments)

VALUES(100,'Apple iphone 5s','21-May-14','24-May-14','Color : Black');

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

---------------------------------------------------------------------------

--Inserting records with out mentioning column name

INSERT INTO prod_details

VALUES(101,'Samsung Galaxy III','20-Aug-14','23-Aug-14','Color : White');

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

---------------------------------------------------------------------------
--Inserting selective number of values

INSERT INTO prod_details

VALUES(103,'Moto X','11-May-14','13-May-14');

ORA-00947 : not enough values

--While inserting selective number of values mentioning column name is compulsory.

INSERT INTO prod_details (prod_id,prod_name,order_dt,deliver_dt)

VALUES(103,'Moto X','11-May-14','13-May-14');

SELECT * FROM prod_details;

--------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

--------------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

--------------------------------------------------------------------------------

--Inserting NULL value.

--If you want to insert NULL value you can ignore that column at the time of inserting
--or we can use NULL keyword to insert NULL.

INSERT INTO prod_details

VALUES(104,'Moto G','19-May-14','22-May-14',NULL);

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Noto G 5/19/2014 5/22/2014

---------------------------------------------------------------------------

--if you are not providing values for order_dt and deliver_dt column default value can be taken.

INSERT INTO prod_details(prod_id,prod_name,comments)

VALUES(105,'Nokia Lumis 720p','Color : Red');

SELECT * FROM prod_details;


---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

----------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Moto G 5/19/2014 5/22/2014

105 Nokia Lumis 720p 5/26/2014 5/29/2014 Color : Red

---------------------------------------------------------------------------

--Inserting data by using sub query

CREATE TABLE test_tab (id NUMBER, Name VARCHAR2(30));

INSERT INTO test_tab VALUES(1,'Name1');

INSERT INTO test_tab VALUES(2,'Name2');

INSERT INTO test_tab VALUES(3,'Name3');

SELECT COUNT(*) FROM test_tab;

COUNT(*)

-------

3
--creating table by using sub query (with out data)

CREATE TABLE ins_chk

SELECT * FROM test_tab

WHERE id = 900;

SELECT COUNT(*) FROM ins_chk;

COUNT(*)

-------

--Inserting data by using sub query

--copying data from test_tab to ins_chk

INSERT INTO ins_chk (SELECT * FROM test_tab);

3 rows inserted in 0.047 seconds.

SELECT COUNT(*) FROM ins_chk;


COUNT(*)

-------

DROP TABLE test_tab;

DROP TABLE ins_chk;

UPDATE

Syntax :

UPDATE table_name

SET column1_name = column1_value,

column2_name = column2_value,

column2_name = column3_value,

columnn_name = columnn_value

WHERE condition(s);

SELECT * FROM prod_details;


---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

----------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Moto G 5/19/2014 5/22/2014

105 Nokia Lumis 720p 5/26/2014 5/29/2014 Color : Red

---------------------------------------------------------------------------

UPDATE prod_details ps

SET ps.prod_name = 'iphone 5s'

WHERE ps.prod_id = 100;

1 row updated in 0.031 seconds

SELECT *

FROM prod_details ps

WHERE ps.prod_id = 100;

--------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

--------------------------------------------------------------------

100 iphone 5s 5/21/2014 5/24/2014 Color : Black

--------------------------------------------------------------------
--update statement with out condition

--If you try to execute update statement without condition it'll update all the records inside the
table.

UPDATE prod_details ps

SET ps.comments = 'None';

5 row updated in 0.031 seconds

SELECT *

FROM prod_details ps;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 None

101 Samsung Galaxy III 8/20/2014 8/23/2014 None

103 Moto X 5/11/2014 5/24/2014 None

104 Moto G 5/19/2014 5/22/2014 None

105 Nokia Lumis 720p 5/26/2014 5/29/2014 None

----------------------------------------------------------------------

--if your update text contain ' means you can use following metnod (use '')
UPDATE prod_details ps

SET ps.comments = 'Some product''s are not available'

WHERE ps.prod_id = 100;

1 row updated in 0.031 seconds

SELECT *

FROM prod_details ps

WHERE ps.prod_id = 100;

------------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

------------------------------------------------------------------------------------

100 iphone 5s 5/21/2014 5/24/2014 Some product's are not available

------------------------------------------------------------------------------------

DELETE

Syntax:

DELETE FROM table_name

WHERE condition(s);
DELETE FROM prod_details

WHERE prod_id IN (104, 105);

2 row(S) deleted in 0.032 seconds

SELECT *

FROM prod_details ps;

---------------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Some product's are not available

101 Samsung Galaxy III 8/20/2014 8/23/2014 None

103 Moto X 5/11/2014 5/24/2014 None

---------------------------------------------------------------------------------------

DELETE FROM prod_details;

3 row(s) deleted in 0.062 seconds.

SELECT * FROM prod_details;

no rows selected.
DROP TABLE prod_details;

MERGE = Insert + Update

-- will update soon.

Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Data Define Language

Data Definition Language (DDL) statements are used to define the database structure or schema.

Some examples:

CREATE - to create objects in the database.

ALTER - alters the structure of the database.

ADD
RENAME

MODIFY

DROP

DROP - delete objects from the database

TRUNCATE - remove all records from a table,

including all spaces allocated for the records are removed.

COMMENT - add comments to the data dictionary.

RENAME - rename an object.

Creating Table

--------------------------------------------------------------------------

Data Types Size Default Size Explanation

--------------------------------------------------------------------------

NUMBER(P,S) P: 1 to 38 we can store number between 0-9

S: -84 to 127

VARCHAR2 4000 Bytes we can store 0-9, a-z, A-Z and special characters

CHAR 2000 Bytes 1

DATE 7 Used to store Date

TIMESTAMP Includes year, month, day, hour, minute, and seconds.

LONG 2 GB Only one long column is allowed in a table.

We can't use this column in ORDER BY clause.

CLOB 4 GB Character Large Object

BLOB Binary Larger Object


--------------------------------------------------------------------------

CREATE

ALTER : ADD RENAME MODIFY DROP RENAME

RENAME

DROP

TRUNCATE

--creating table

CREATE TABLE friends_details_tb

Name VARCHAR2(30) ,

Phone NUMBER(10) ,

Gender CHAR ,

dob DATE ,

other_details LONG ,

make_dtm TIMESTAMP

);

DESC friends_details_tb;

-----------------------------

NAME TYPE
-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

-----------------------------

--maximum you can keep 255 columns in a table

ALTER : Colum level operations

ADD RENAME MODIFY DROP

ADD : Used to add a column after the table hase been created

ALTER TABLE friends_details_tb

ADD email VARCHAR2(30);

DESC friends_details_tb;

-----------------------------
NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

EMAIL VARCHAR2(30)

-----------------------------

--adding multiple columns by using single ALTER statement

SYNTAX

ALTER TABLE friends_details_tb

ADD (

column_1 Data_type(size),

column_2 Data_type(size),

column_3 Data_type(size),

column_4 Data_type(size)

);
RENAME : Used to Rename a column

ALTER TABLE friends_details_tb

RENAME COLUMN email TO email_id;

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

MODIFY : Used to change the data type or size of the data type.

ALTER TABLE friends_details_tb


MODIFY other_details CLOB;

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS CLOB

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

--Modifying multiple columns at a time

ALTER TABLE friends_details_tb

MODIFY ( column_name_1 old_datatype(new_size),

column_name_2 new_datatype(old_size),

column_name_3 new_datatype(new_size)

);
DROP : Used to drop the column after the table has been created.

ALTER TABLE friends_details_tb

DROP COLUMN other_details;

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

RENAME : Used to Rename a particular table.

SYNTAX

RENAME old_table_name TO new_table_name;


RENAME friends_details_tb TO fnd_det;

DESCRIBE fnd_det;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

TRUNCATE : Used to remove the entire content of the table (not a structure)

SYNTAX

TRUNCATE TABLE table_name;

TRUNCATE TABLE fnd_det;


DROP : Used to drop the tabel (Data + stucture of the table get removed from the database )

DROP TABLE fnd_det;

*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Statements in Oracle

Data Definition Language (DDL)

DDL statements are used to define the database structure or schema. Some examples:

CREATE - to create objects in the database

ALTER - alters the structure of the database

ADD

RENAME
MODIFY

DROP

DROP - delete objects from the database

TRUNCATE - remove all records from a table,

including all spaces allocated for the records are removed

RENAME - rename an object

Data Manipulation Language (DML)

DML statements are used for managing data within schema objects. Some examples:

INSERT - insert data into a table

UPDATE - updates existing data within a table

DELETE - deletes all records from a table, the space for the records remain

MERGE - UPSERT operation (insert or update)

Data Control Language (DCL)

DCL statements. Some examples:

GRANT - gives users access privileges to database

REVOKE - withdraw access privileges given with the GRANT command


Transaction Control (TCL)

TCL statements are used to manage the changes made by DML statements. It allows
statements to be grouped together into logical transactions.

COMMIT - save work done

SAVEPOINT - identify a point in a transaction to which you can later roll back

ROLLBACK - restore database to original since the last COMMIT

Posted 28th May 2014 by Unknown

0 Add a comment

MAY

19

DECODE and CASE statement

CREATE TABLE students (

roll_no NUMBER(4) ,

Name VARCHAR2(30) ,

dept_cd VARCHAR2(20) ,
total_marks NUMBER(3)

);

BEGIN

INSERT INTO students VALUES (2000,'Rahul','CSE',480);

INSERT INTO students VALUES (2001,'Bala','IT', 390);

INSERT INTO students VALUES (2002,'Ramesh','CSE',250);

INSERT INTO students VALUES (2003,'Karthi','EEE',185);

INSERT INTO students VALUES (2004,'Ravi','IT',345);

END;

SELECT * FROM students;

DECODE

Decode is a function. Its a Oracle one.

Works like IF-THEN-ELSE.

You can use DECODE only in SELECT clause.

In DECODE you can include 255 things include Exep, search , result and default value.

Example

SELECT roll_no,

NAME,

dept_cd,
DECODE(dept_cd,

'CSE',

'Computer Science and Engineering',

'IT',

'Information Technology',

'Default Value') AS "DEPARTMENT NAME"

FROM students;

Sample Output

------------------------------------------------------------

ROLL_NO NAME DEPT_CD DEPARTMENT NAME

------------------------------------------------------------

2000 Rahul CSE Computer Science and Engineering

2001 Bala IT Information Technology

2002 Ramesh CSE Computer Science and Engineering

2003 Karthi EEE Default Value

2004 Ravi IT Information Technology

------------------------------------------------------------

CASE

CASE is an expression. Its a ANSI standard.

Compare to DECODE case will be more faster.

Example
SELECT roll_no,

NAME,

dept_cd,

total_marks,

CASE

WHEN total_marks > 500 THEN

'A Grade'

WHEN total_marks > 400 THEN

'B Grade'

WHEN total_marks > 300 THEN

'C Grade'

ELSE

'U Grade'

END AS "GRADE"

FROM students;

-----------------------------------------------

ROLL_NO NAME DEPT_CD TOTAL_MARKS GRADE

-----------------------------------------------

2000 Rahul CSE 480 B Grade

2001 Bala IT 390 C Grade

2002 Ramesh CSE 250 U Grade

2003 Karthi EEE 185 U Grade

2004 Ravi IT 345 C Grade


-----------------------------------------------

Interview Questions:

What is DECODE?

What is CASE?

Difference between CASE and DECODE? Which one is faster?

Posted 19th May 2014 by Unknown

0 Add a comment

MAY

19

Sub Query

Query with in another query

1. Single Row sub query

2. Multi row Sub query

select * from employees;


Want to fetch the person Who are all getting salary more than Neena's salary ?

Neena's Salary : 17000

Select First_name, salary

From Employees

Where salary > 17000;

--change in Neena's salary won't work for the above query.

Select salary From Employees

Where First_name = 'Neena';

Sub Query :

Select First_name, salary

From Employees

Where salary > (

Select salary From Employees

Where First_name = 'Neena'

);
Select * from employees;

Select salary From Employees

Where First_name = 'Alexander';

Sub Query Returns one value it is called as Single row sub query

Sub Query Returns more than one value it is called as Multi row sub query

Single row sub query operators :

> < >= <= = <>

Multiple Row Sub query operators :

IN ALL ANY

Who are all getting salary more than the average salary?

Select

First_name,

Salary
From

Employees

WHERE

Salary > (

SELECT Round(avg(salary),0)

FROM Employees

);

Multiple Row Sub query (In ANY ALL)

Select First_name,Department_id, salary

From Employees

Where salary in(

Select Salary From Employees

Where First_name = 'Alexander'

);

Any : Minimum Value will be taken (3100)

Select First_name,Department_id, salary

From Employees

Where salary > ANY(

Select Salary From Employees

Where First_name = 'Alexander'


);

All : Maximum Value will be taken (9000)

Select First_name,Department_id, salary

From Employees

Where salary > All(

Select Salary From Employees

Where First_name = 'Alexander'

);

We can use sub query in all the classes except Group by and order by class.

Select

From

Where

-----------Group by

having

-----------Order by

SELECT

( Select Count(*) from Employees Where Department_id = 90 )Executive,

( Select Count(*) from Employees Where Department_id = 60 ) IT,


( Select Count(*) from Employees Where Department_id = 10 ) Administration,

( Select Count(*) from Employees Where Department_id = 100) Finance

FROM

Dual;

Select Min(salary) From Employees;

Select Min(salary) from

Select * from Employees

Where Department_id = 60

);

What is INLINE VIEW?

If u use sub query in From it is call it is as INLINE VIEW.

Intermediate result set

Correlated sub query

SELECT employee_number, name

FROM employees Bob

WHERE salary > (

SELECT AVG(salary)

FROM employees
WHERE department = Bob.department

);

Posted 19th May 2014 by Unknown

0 Add a comment

Loading

Dynamic Views theme. Powered by Blogger.Oracle sql & Pl/sql

search

Home Sql and pl/sql Sql Interview Questions

JUL

20

INLINE view in Oracle with 12c New Features

Named sub Query in FROM clause is call it as INLINE VIEW.

Oracle process a inline view faster than sub query


Inline View in Oracle

--Query to display all the employees who are all getting salary more than their department
average salary

SELECT First_name

, last_name

, salary

, department_id

FROM employees a , ( SELECT b.department_id

, AVG(b.salary) avg_sal

FROM employees b

GROUP BY b.department_id

)b

WHERE a.department_id = b.department_id

AND a.salary > b.avg_salary;

Display all the customer who have placed more number of orders by using INLINE view

CREATE TABLE customer_order_det_tb

( custm_id NUMBER ,

custm_nm VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

ttl_amt NUMBER(7,2)

);
BEGIN

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '11-Jul-15' , 45000.00);

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '14-Jul-15' , 27000.00);

INSERT INTO customer_order_det_tb VALUES(101, 'Raja' , '13-Jul-15' , 17000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 34000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 38000.00);

COMMIT;

END;

SELECT c.*

FROM customer_order_det_tb c;

--------------------------------------------

custm_id custm_nm order_dt ttl_amt

--------------------------------------------

100 Murugappan 7/11/2015 45000.00

100 Murugappan 7/14/2015 27000.00

101 Raja 7/13/2015 17000.00

102 Ramesh 7/15/2015 34000.00

102 Ramesh 7/15/2015 38000.00

--------------------------------------------

--Writing a Quer to display all the customer who have placed maximum number of order
--Query #1 for inline view

SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC;

--------------------------------

custm_id custm_nm total_odr

--------------------------------

100 Murugappan 2

102 Ramesh 2

101 Raja 1

--------------------------------

--Query #2 for inline view

SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm;

----------

total_odr

----------

2
----------

Inline view to find all the customers who have placed maximum number of orders

/****************************************

Syntax

SELECT * FROM <query1> x, <query2> y

WHERE contition;

****************************************/

SELECT query1.* FROM

( SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC

) query1,

( SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm

) query2

WHERE query1.total_odr = query2.total_odr;

-------------------------------

custm_id custm_nm total_odr


-------------------------------

100 Murugappan 2

102 Ramesh 2

-------------------------------

DROP TABLE customer_order_det_tb;

--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT

SELECT first_name, salary

FROM ( SELECT first_name, salary

FROM employees e

WHERE job_id NOT IN ('SALESMAN','PRESIDENT')

ORDER BY salary DESC

WHERE ROWNUM < 4;

New Oracle 12c Inline view Syntax

LATERAL clause for In-line views

Allows for columns in the inline view to be accessed!!


Example :

--in 11g

SELECT * FROM employees e, (

SELECT *

FROM departments d

WHERE e.department_id = d.department_id);

ORA-0090: "E"."DEPARTMENT_ID": Invalid Identifier

--in 12c

SELECT * FROM employees e, LATERAL(

SELECT *

FROM departments d

WHERE e.department_id = d.department_id

);

--in 11g

WITH t

AS

( SELECT LEVEL a

FROM dual

CONNECT BY LEVEL <= 30)


SELECT *

FROM t, (SELECT *

FROM employees

WHERE department_id = t.a

);

ORA-00904: "T"."A": invalid Identifier

--in 12c

WITH t

AS

(SELECT LEVEL a FROM dual CONNECT BY LEVEL <= 30)

SELECT * FROM t,

LATERAL(SELECT *

FROM employees

WHERE department_id = t.a);

Hope you have enjoyed this little article

Feed backs are always Welcome :) (:

Posted 20th July 2015 by Unknown

0 Add a comment

JAN

23
Salary Related Questions in Oracle

--creating table

CREATE TABLE employee_data

eid NUMBER(4),

ename VARCHAR2(30),

depno NUMBER(3),

salary NUMBER(8)

);

BEGIN

--Inserting records

INSERT INTO employee_data VALUES(1000,'Name01',90,30000);

INSERT INTO employee_data VALUES(1001,'Name02',90,6000);

INSERT INTO employee_data VALUES(1002,'Name03',90,23000);

INSERT INTO employee_data VALUES(1003,'Name04',60,35000);

INSERT INTO employee_data VALUES(1004,'Name05',60,60000);


INSERT INTO employee_data VALUES(1005,'Name06',60,30000);

INSERT INTO employee_data VALUES(1006,'Name07',80,36000);

INSERT INTO employee_data VALUES(1007,'Name08',80,29000);

INSERT INTO employee_data VALUES(1008,'Name09',80,37000);

INSERT INTO employee_data VALUES(1009,'Name10',80,41000);

COMMIT;

END;

SELECT * FROM employee_data

ORDER BY salary DESC;

--query to find maximum salary from employee_data table

SELECT MAX(salary) FROM employee_data;

--query to find minimum salary from employee_data table

SELECT MIN(salary) FROM employee_data;

--query to find second maximum salary from employee_data table

SELECT MAX(salary)

FROM employee_data
WHERE salary NOT IN (SELECT MAX(salary)

FROM employee_data);

--query to select 5th maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= 5);

--query to select nth maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= &n);

--query to select all the details of the employee whose getting nth maximum salary
SELECT *

FROM (SELECT emp.*,

rownum rn

FROM (SELECT *

FROM employee_data

ORDER BY salary DESC) emp)

WHERE rn = 9;

--same query using row_numbr( ) function

SELECT *

FROM (SELECT emp.*,

row_number() over(ORDER BY salary) rank

FROM employee_data emp)

WHERE rank = 9;

--same query using rank( ) function

SELECT *

FROM (SELECT emp.*,

rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--same query using dense_rank( ) function


SELECT *

FROM (SELECT emp.*,

dense_rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--query to display display maximum salary in all the department

SELECT e.depno "Department id",

MAX(salary) "Maximum Salary"

FROM employee_data e

GROUP BY e.depno;

--query to display all the employees who are all getting salary more than average salary of the
company

SELECT e.* FROM employee_data e

WHERE salary > (SELECT AVG(salary) FROM employee_data);

--query to display all the employees who are all getting salary more than their department
average salary

SELECT employee_id,
first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE department_id = OUT.department_id);

--query to display all the employees who are all getting salary more than their manager salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE employee_id = OUT.manager_id);

Documented By : Murugappan Annamalai

Posted on : 23-Jan-15 16:34:00 IST.


Hope you have enjoyed this little article

Feed backs are always welcome :)

Posted 23rd January 2015 by Unknown

7 View comments

JAN

22

Why prefer COALESCE over NVL

Documented By : Nimish Garg

I prefer using "COALESCE" over "NVL" is some of the scenarios. Last week One of my friend
asked me what is the advantage of using "COALESCE" where we can simply use "NVL". I simply
gave him the reply from Oracle Docs i.e. NVL lets you replace null (returned as a blank) with a
string in the results of a query and COALESCE returns the first non-null expr in the expression list.
Oracle Database uses short-circuit evaluation with "COALESCE".

He replied that he knows the difference, he knows that "COALESCE" can take multiple arguments
and so on. He was more interested in understanding "short-circuit evaluation" of "COALESCE"
and the scenarios where I prefer using "COALESCE" over "NVL".

To make him understand I created following function which takes One second in every execution
and simply returns '--null--' and executed 2 very similar queries one with NVL and other with
COALESCE.

SQL> create or replace function f_null return varchar2

2 is
3 begin

4 dbms_lock.sleep(1);

5 return '--null--';

6 end;

7 /

Function created.

Following are the queries which I used to demonstrate that NVL evaluates both arguments even
if the second argument is not used and COALESCE uses short-circuit evaluation i.e. it only
evaluates the arguments only if they are needed.

SQL> select e.empno, e.ename ename, nvl(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE


7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.

Elapsed: 00:00:14.01

SQL> select e.empno, e.ename ename, coalesce(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE


7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.

Elapsed: 00:00:01.01

Here we can see easily that the first query with NVL took 14+ seconds, one second for each
record even if the "f_null" value was used only in one record. On the contrary as mentioned in
Oracle Documentation "COALESCE" uses its "short-circuit evaluation" and "f_null" was called
only once and so second query took only One Second. "COALESCE" is certainly use less resources
than NVL.

Posted 22nd January 2015 by Unknown

0 Add a comment

DEC

21

Constraints
It Enforce Rule On Table

We can create constraint at the time of Creating Table

1. Column Level Declaration

2. Table Level Declaration

1. We can provide own name.

Format : [part_of_project_name-table_name-column_name-constraint_type]

Example : gmind_emp_id_pk _uk _ck _f

2. system name name

Format : sys_cn

Example : SYS_C405323

We can create constraint after the table has been created

Types
Primary Key

Not allowed Null value

Not allowed you to enter duplicate value

Ex : Employee_id, Student_id

Unique Key

allowed Null value

Not allowed you to enter duplicate value

Ex : Contact_no, email

Foreign Key

It will allowed you to enter NULL and Duplicate value.

c1(pk) : 1 2 3

c2(f) : 1 1 2 3 4 Not allowed

Allowed you to enter duplicate value and null value

Not Null
It will not allowed you to enter null value

Check

You can check your own condition

Simple Table for understanding

------------------------------------

Duplicate NULL

------------------------------------

Primary Key X X

Unique Key X Allowed

Foreign Key Allowed Allowed

------------------------------------

creating table with all constraint type

Create table my_stu_details

S_id Number(2),
S_name Varchar2(30) Not Null, --SYS_Cn

s_mail Varchar2(30),

s_gender char(1),

s_did Number(3),

Constraint my_stu_sid_pk PRIMARY KEY (s_id),

constraint my_stu_mail_uk UNIQUE (s_mail) ,

Constraint my_stu_gen_ck CHECK (s_gender IN ('M', 'F', 'm', 'f')),

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

);

DESC my_stu_details;

------------------------------------

Name Type Nullable

------------------------------------

S_ID NUMBER(2)

S_NAME VARCHAR2(30)

S_MAIL VARCHAR2(30) Y

S_GENDER CHAR(1) Y

S_DID NUMBER(3) Y

------------------------------------

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)


values (1 , 'name1' , 'name1@gmail.com' , 'm' , 60 );

Select * from my_stu_details;

Validating Primary Key

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-00001: unique constraint (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (NULL, 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-01400: cannot insert NULL into (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (2 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

Select * from my_stu_details;


Validating NOT NULL Constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , NULL , 'name3@gmail.com' , 'F' , 80 );

ORA-01400: cannot insert NULL into ("HR"."MY_STU_DETAILS"."S_NAME")

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , 'Name3' , 'name3@gmail.com' , 'F' , 80 );

Select * from my_stu_details;

Validating Unique Key Constraint

--Duplicate Check
Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , 'name3@gmail.com' , 'F' , 80 );

ORA-00001: unique constraint (HR.MY_STU_MAIL_UK) violated

--Null Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , null , 'M' , 70 );

Select * from my_stu_details;

Validating Check constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'j' , 70 );

ORA-02290: check constraint (HR.MY_STU_GEN_CK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'M' , 70 );


Select * from my_stu_details;

Validating Foreign Key

Select * from Departments;

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 3 );

ORA-02291: integrity constraint (HR.MY_STU_DID_FK) violated - parent key not found

Departments table : parent table

my_stu_details : Child table

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 90 );


Select * from my_stu_details;

--------------------------------------------------------

s_id s_name s_mail s_gender s_did

--------------------------------------------------------

1 name1 name1@gmail.com m 60

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 M 70

5 Name5 name5@gmail.com M 70

6 Name6 name6@gmail.com F 90

--------------------------------------------------------

Deleting the Primary key value which is referred by Foreign Key

Select * from Departments;

DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID

------------------------------------------------------------

60 IT 103 1400 <---- Delete


-- don't execute this query

--Delete From Departments

--Where Department_id = 60;

1) ON DELETE SET NULL

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

1 name1 name1@gmail.com m -

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

2) ON DELETE SET CASCADE

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

2 name2 name2@gmail.com F 90
3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

Syntax

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE CASCADE

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE SET NULL

Constraint Related Data Dictionary Table information.

To view constraint Information

SELECT c.owner,

c.constraint_name,

c.constraint_type,

c.table_name,

c.r_constraint_name,

c.status
FROM user_constraints c

WHERE c.table_name = 'MY_STU_DETAILS';

------------------------------------------------------------------------------------

owner constraint_name constraint_type table_name r_constraint_name status

------------------------------------------------------------------------------------

HR SYS_C004023 C MY_STU_DETAILS ENABLED

HR MY_STU_GEN_CK C MY_STU_DETAILS ENABLED

HR MY_STU_SID_PK P MY_STU_DETAILS ENABLED

HR MY_STU_MAIL_UK U MY_STU_DETAILS ENABLED

HR MY_STU_DID_FK R MY_STU_DETAILS DEPT_ID_PK ENABLED

------------------------------------------------------------------------------------

To view constraint name with corresponding column name

SELECT * FROM user_cons_columns c

WHERE c.table_name = 'MY_STU_DETAILS';

-------------------------------------------------------------

owner constraint_name table_name column_name position

-------------------------------------------------------------

HR MY_STU_MAIL_UK MY_STU_DETAILS S_MAIL 1


HR MY_STU_SID_PK MY_STU_DETAILS S_ID 1

HR MY_STU_GEN_CK MY_STU_DETAILS S_GENDER

HR SYS_C004023 MY_STU_DETAILS S_NAME

HR MY_STU_DID_FK MY_STU_DETAILS S_DID 1

-------------------------------------------------------------

Creating Composite Primary Key

Creating Primary Key with more than one number of column

ALTER TABLE table_name

ADD CONSTRAINT constraint_name PRIMARY KEY(column1, column_2 , column3);

In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.

creating constraint after the table creation

ALTER TABLE table_name

ADD CONSTRAINT constraint_name CONSTRAINT_TYPE(column_name);

ALTER TABLE table_name


DROP CONSTRAINT constraint_name;

ALTER TABLE table_name

DROP PRIMARY KEY;

To drop related foreign key

ALTER TABLE table_name

DROP PRIMARY KEY CASCADE;

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name;

Disable constraint with related foreign key constraint

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name CASCADE;

ALTER TABLE table_name

ENABLE CONSTRAINT constraint_name;


Interview Questions

What are all the type of constraint available in oracle?

Difference between PRIMARY KEY and UNIQUE key.

Difference between PRIMARY KEY ans FOREIGN KEY.

Difference between UNIQUE key and FOREIGN KEY.

Is it possible to create tow primary key in single table.

Write a syntax to create FOREIGN constraint.

How to create constraint after the table has been created?

How to enable and disable a constraint.

Which data dictionary table contains information about constraints?

Which Data Dictionary table contains information about constraint with corresponding column
name?

What is composite primary key?

Explain ON DELETE CASCADE and ON DELETE SET NULL option.

~Thanks For Reading~

Post your valuable feedback below


Posted 21st December 2014 by Unknown

1 View comments

UnknownMay 22, 2017 at 12:39 AM

good

Reply

DEC

listagg in Oracle 11g

Oracle 11gR2 listagg built-in function allows for many table columns to be displayed within a
single row, a non-first-normal form display

Syntax :

listagg(column_value,'delimiter') WITHIN GROUP(ORDER BY column_name)

--Example 1:

CREATE TABLE test_ins(empid NUMBER,product VARCHAR2(30));

BEGIN
INSERT INTO test_ins VALUES( 101,'pendrive');

INSERT INTO test_ins VALUES( 102,'toy');

INSERT INTO test_ins VALUES( 101,'ipod');

INSERT INTO test_ins VALUES( 102,'hat');

INSERT INTO test_ins VALUES( 103,'cpu');

INSERT INTO test_ins VALUES( 104,'pen');

INSERT INTO test_ins VALUES( 104,'car');

INSERT INTO test_ins VALUES( 104,'mat');

INSERT INTO test_ins VALUES( 105,'tv');

INSERT INTO test_ins VALUES( 106,'laptop');

commit;

END;

SELECT * FROM test_ins;

SELECT empid "Employee",

listagg(product,

',') within

GROUP (ORDER BY empid) "Products"

FROM test_ins

GROUP BY empid;

-->-- Result set --<--


DROP TABLE test_ins;

-->-- Example 2

select department_id "Department id", listagg(first_name,', ') WITHIN GROUP(ORDER BY


employee_id) "Employees"

FROM employees

WHERE department_id IN (10,20,30,60)

GROUP BY department_id;

-->-- Result set --<--


Posted 4th December 2014 by Unknown

0 Add a comment

NOV

Condition and Looping Statement

IF

IF ELSE

Multiple IF ELSE

LOOP

FOR LOOP

WHILE LOOP

create table test_udt(id NUMBER, salary NUMBER);

BEGIN

INSERT INTO test_udt VALUES(001,23000);

INSERT INTO test_udt VALUES(002,43000);


INSERT INTO test_udt VALUES(003,78000);

INSERT INTO test_udt VALUES(004,25000);

INSERT INTO test_udt VALUES(005,26000);

INSERT INTO test_udt VALUES(006,90000);

Commit;

END;

select * from test_udt;

IF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 1;

IF v_salary > 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005


WHERE t.id = v_id ;

END IF;

commit;

END;

IF ELSE

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

ELSE

UPDATE test_udt t

SET t.salary = v_salary+20007


WHERE t.id = v_id ;

END IF;

commit;

END;

--same example with less number of lines

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

v_salary := v_salary+10005;

ELSE

v_salary := v_salary+20007;

END IF;

UPDATE test_udt t
SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

Multiple IF ELSIF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 3;

IF v_id = 1 THEN

v_salary := 1000;

dbms_output.put_line('1 inside');

ELSIF v_id = 2 THEN

v_salary := 2000;
dbms_output.put_line('2 inside');

ELSIF v_id = 3 THEN

v_salary := 3000;

dbms_output.put_line('3 inside');

ELSIF v_id = 4 THEN

v_salary := 4000;

dbms_output.put_line('4 inside');

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

LOOP

--syntax

LOOP

--statements
--increment

--exit statement

END LOOP;

CREATE TABLE prod_details (pid VARCHAR2(3), pname VARCHAR2(30));

DECLARE

i NUMBER := 1;

x VARCHAR2(3);

BEGIN

LOOP

x := lpad(i,3,'0');

dbms_output.put_line('x value : '|| x);

INSERT INTO prod_details VALUES(i, 'Product '||i);

EXIT WHEN i >900;

i := i+1;

IF MOD(i,100) = 0 THEN

commit;

dbms_output.put_line('commit executed');

END IF;

END LOOP;

END;
SELECT * FROM prod_details ORDER BY 1;

DROP TABLE prod_details;

FOR LOOP

BEGIN

FOR I in 1..5

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

FOR LOOP - Reverse

BEGIN

FOR I in REVERSE 14..50

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

/
WHILE LOOP

DECLARE

i_val NUMBER:=0;

BEGIN

WHILE (i_val < 11)

LOOP

dbms_output.put_line('The value of I is '||i_val);

i_val := i_val + 1;

END LOOP;

END;

sample output:

The value of I is 0

The value of I is 1

The value of I is 2

The value of I is 3

The value of I is 4

The value of I is 5

The value of I is 6

The value of I is 7

The value of I is 8

The value of I is 9
The value of I is 10

Posted 8th November 2014 by Unknown

0 Add a comment

OCT

21

Bulk Collect

This is used for array fetches

With this you can retrieve multiple rows of data with a single round trip.

This reduces the number of context switches between the pl/sql and sql engines.

You can use bulk collect in both dynamic and static sql.

You can use bulk collect in select, fetch into and returning into clauses.

SQL engine automatically initializes and extends the collections you reference in the bulk
collect clause.

You can fetch into multiple collections with one column each.

You can use the limit clause of bulk collect to restrict the no of rows retrieved.

SELECT * FROM product_details;


-->-- Bulk collect in FETCH INTO --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Bulk collect in SELECT clause --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;


dta alldata_typ;

BEGIN

SELECT * BULK COLLECT INTO dta FROM product_details;

FOR i IN dta.FIRST .. dta.LAST LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- LIMIT in Bulk collect --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta LIMIT 30;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);


END LOOP;

END;

-->-- Multiple fetches in INTO clause --<--

SELECT * FROM product_details;

DECLARE

TYPE alldata_typ1 IS TABLE OF product_details.p_id%TYPE;

TYPE alldata_typ2 IS TABLE OF product_details.p_name%TYPE;

dta1 alldata_typ1;

dta2 alldata_typ2;

CURSOR proddt_cur IS

SELECT p_id, p_name FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta1, dta2;

CLOSE proddt_cur;

FOR i IN dta1.FIRST .. dta1.COUNT LOOP

dbms_output.put_line('Department Id : ' || dta1(i));


END LOOP;

FOR i IN dta2.FIRST .. dta2.COUNT LOOP

dbms_output.put_line('Department Name : ' || dta2(i));

END LOOP;

END;

DROP TABLE dep_details;

DROP TABLE product_details;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Ref Cursor

This is unconstrained cursor which will return different types depends upon the user input.

Ref cursors cannot be closed implicitly.

Ref cursor with return type is called strong cursor.


Ref cursor without return type is called weak cursor.

You can declare ref cursor type in package spec as well as body.

You can declare ref cursor types in local subprograms or anonymous blocks.

CREATE OR REPLACE PROCEDURE ref_c_sp(dep_det_c IN OUT SYS_REFCURSOR)

AS

BEGIN

OPEN dep_det_c

FOR

SELECT * FROM dep_details d;

END;

DECLARE

dep_det_c SYS_REFCURSOR;

tab_data dep_details%ROWTYPE;

BEGIN

ref_c_sp(dep_det_c);

LOOP

FETCH dep_det_c INTO tab_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department Name : '|| tab_data.d_name);


END LOOP;

CLOSE dep_det_c;

END;

/*sample output*/

Department Name : Admin

Department Name : HR

Department Name : Sales

Department Name : Marketing

DROP PROCEDURE ref_c_sp;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Cursor
SQL Private work Area where the query get passed and executed.

Types

******

Implicit(SQL)

Explicit

-->-- advanced cursor types --<--

Parametrized Cursor

Ref Cursor

Implicit

********

ORACLE implicitly opens a cursor to process each SQL statement not associated with an
explicitly declared cursor.

PL/SQL lets you refer to the most recent implicit cursor as the SQL” cursor. So, although you
cannot use the OPEN,

FETCH, and CLOSE statements to control an implicit cursor, you can still use cursor attributes to
access information

about the most recently executed SQL statement.

Cursor Stages

**************

OPEN cursor_name

FETCH (with in loop)


CLOSE cursor_name

Explicit

The set of rows returned by a query can consist of zero, one, or multiple rows,

depending on how many rows meet your search criteria. When a query returns multiple rows,

you can explicitly define a cursor to process the rows. You use three commands to control the
cursor

Cursor Attributes

*****************

%FOUND

%NOTFOUND

%ISOPEN

%ROWCOUNT

%BULK_ROWCOUNT --<-- used to handle error while using bulk collection.

%BULK_EXCEPTIONS --<-- used to handle error while using bulk collection.

Cursor Declaration

DECLARE

CURSOR <cursor_name>

IS

<SELECT statement>

BEGIN
--> some stmt

END;

Cursor Loop

Loop

While Loop

For Loop

Cursor Clauses

Return

For update

Where current of

Bulk collect

-->-- creating table

create table product_details

p_id NUMBER,

p_name VARCHAR2(30),

p_order_dt DATE

);
-->-- Inserting data

BEGIN

FOR i IN 1 .. 75 LOOP

INSERT INTO product_details VALUES (i, 'prod_name_' || i, SYSDATE + i);

END LOOP;

commit;

END;

-->-- selecting data

SELECT * FROM product_details;

---------------------------------------------

p_id p_name p_order_dt

---------------------------------------------

1 prod_name_1 10/11/2014 3:48:32 PM

2 prod_name_2 10/12/2014 3:48:32 PM

3 prod_name_3 10/13/2014 3:48:32 PM

4 prod_name_4 10/14/2014 3:48:32 PM

5 prod_name_5 10/15/2014 3:48:32 PM

6 prod_name_6 10/16/2014 3:48:32 PM

7 prod_name_7 10/17/2014 3:48:32 PM

8 prod_name_8 10/18/2014 3:48:32 PM


9 prod_name_9 10/19/2014 3:48:32 PM

10 prod_name_10 10/20/2014 3:48:32 PM

11 prod_name_11 10/21/2014 3:48:32 PM

12 prod_name_12 10/22/2014 3:48:32 PM

13 prod_name_13 10/23/2014 3:48:32 PM

14 prod_name_14 10/24/2014 3:48:32 PM

15 prod_name_15 10/25/2014 3:48:32 PM

16 prod_name_16 10/26/2014 3:48:32 PM

17 prod_name_17 10/27/2014 3:48:32 PM

18 prod_name_18 10/28/2014 3:48:32 PM

19 prod_name_19 10/29/2014 3:48:32 PM

20 prod_name_20 10/30/2014 3:48:32 PM

---------------------------------------------

----------------------------------------------

Implicit Cursor

----------------------------------------------

--will update soon

----------------------------------------------

Explicit Cursor

----------------------------------------------
**********************************************

Processing cursor data by using LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND; --<-- if next record not found means control will
come out from the loop

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/
Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

EXIT WHEN prod_detail_cur%FOUND; --<-- if next record found means control will come
out from the loop

END LOOP;

CLOSE prod_detail_cur;
END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;
CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor Already closed

DECLARE
all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

-->-- CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;
/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor closed

**********************************************

Processing cursor data by using WHILE LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN
OPEN prod_detail_cur;

FETCH prod_detail_cur

INTO all_data;

WHILE prod_detail_cur%FOUND LOOP

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

FETCH prod_detail_cur

INTO all_data;

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

************************************************************

Processing cursor data by using FOR LOOP - CURSOR FOR LOOP


************************************************************

DECLARE

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

FOR i IN prod_detail_cur

LOOP

dbms_output.put_line('Product id : ' || i.p_id ||

' Product Name : ' || i.p_name ||

' ( Orderd on : ' || TRIM(i.p_order_dt) || ' )');

END LOOP;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )


Parameterized Cursor

*********************

This was used when you are going to use the cursor in more than one place with different
values for the same where clause.

Cursor parameters must be in mode.

Cursor parameters may have default values.

The scope of cursor parameter is within the select statement.

CREATE TABLE dep_details(d_id NUMBER,d_name VARCHAR2(30), location_id NUMBER);

BEGIN

INSRT INTO dep_details VALUES(001,'Admin',1010);

INSRT INTO dep_details VALUES(002,'HR',1010);

INSRT INTO dep_details VALUES(003,'Sales',1020);

INSRT INTO dep_details VALUES(004,'Marketing',1020);

commit;

END;

SELECT * FROM dep_details;

----------------------------

d_id d_name location_id


----------------------------

1 Admin 1010

2 HR 1010

3 Sales 1020

4 Marketing 1020

----------------------------

DECLARE

-->--Declaring parameterized cursor

CURSOR dep_det_c(p_location_id NUMBER) IS

SELECT * FROM dep_details d WHERE d.location_id = p_location_id;

all_data dep_details%ROWTYPE;

BEGIN

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

OPEN dep_det_c(1010);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

-->-- opening same cursor with different input value

OPEN dep_det_c(1020);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

END;

/*sample output*/

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 1 Department Name : Admin

Department id : 2 Department Name : HR

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 3 Department Name : Sales


Department id : 4 Department Name : Marketing

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Handling Exception

Error Handling in oracle

ERROR

Any departure from the expected behavior of the system or program,

which stops the working of the system is an error.

Types : compile time error

Run time error

EXCEPTION

Any error or problem which one can handle and continue to work normally.

Handling Exception
When exception is raised, control passes to the exception section of the block.

i.e. EXCEPTION

WHEN name_of_exception THEN

Types : Pre Defined Exceptions

User Defined Exceptions

Predefined Exception

*********************

Oracle has predefined several exceptions that correspond to the most common oracle errors.

------------------------------------------------------------------------

Exception Oracle Error SQL Code Value

------------------------------------------------------------------------

ZERO_DIVIDE ORA-01476 -1476

NO_DATA_FOUND ORA-01403 +100

DUP_VAL_ON_INDEX ORA-00001 -1

TOO_MANY_ROWS ORA-01422 -1422

VALUE_ERROR ORA-06502 -6502

CURSOR_ALREADY_OPEN ORA-06511 -6511

OTHERS

------------------------------------------------------------------------
-->-- ZERO_DIVIDE --<--

Your program attempts to divide a number by zero.

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN ZERO_DIVIDE THEN

dbms_output.put_line('Divisor is equal to zero');

END;

-->-- NO_DATA_FOUND --<--

Single row SELECT returned no rows or your program referenced a deleted element in a nested
table

or an uninitialized element in an associative array (index-by table).

CREATE TABLE test_tb(id NUMBER PRIMARY KEY);

DECLARE
v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN NO_DATA_FOUND THEN

dbms_output.put_line('There is no data inside the table');

END;

-->-- DUP_VAL_ON_INDEX --<--

A program attempted to insert duplicate values in a column that is constrained by a unique


index.

INSERT INTO test_tb VALUES (1);

INSERT INTO test_tb VALUES (2);

commit;

BEGIN

INSERT INTO test_tb VALUES (2);

EXCEPTION

WHEN DUP_VAL_ON_INDEX THEN

dbms_output.put_line('Duplicate values are not allowed');

END;
-->-- TOO_MANY_ROWS --<--

Single row SELECT returned multiple rows.

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN TOO_MANY_ROWS THEN

dbms_output.put_line('Query returning more than one row');

END;

DROP TABLE test_tb;

-->-- VALUE_ERROR --<--

An arithmetic, conversion, truncation, or size constraint error occurred.

DECLARE

num1 NUMBER(2);

BEGIN
num1 := 345;

EXCEPTION

WHEN VALUE_ERROR THEN

dbms_output.put_line('check the size of the variable');

END;

-->-- CURSOR_ALREADY_OPEN --<--

A program attempted to open an already opened cursor.

CREATE TABLE emp(id NUMBER, name VARCHAR2(30));

BEGIN

INSERT INTO emp VALUES(1,'Name1');

INSERT INTO emp VALUES(2,'Name2');

INSERT INTO emp VALUES(3,'Name3');

INSERT INTO emp VALUES(4,'Name4');

COMMIT;

END;

SELECT * FROM emp;


DECLARE

cursor emp_c IS

SELECT * FROM emp;

all_data emp%ROWTYPE;

BEGIN

OPEN emp_c;

OPEN emp_c;

NULL;

CLOSE emp_c;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

END;

DROP TABLE emp;

-->-- OTHERS --<--

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN


dbms_output.put_line('Cursor already opened');

WHEN OTHERS THEN

dbms_output.put_line('Some other error ' || SQLERRM);

END;

User Defined Exception

**********************

A user-defined exception is an error that is defined by the programmer.

User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,

exceptions have a type EXCEPTION and scope.

DECLARE

v_gender CHAR := '&gender';

gender_ex EXCEPTION;

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE gender_ex;

END IF;

dbms_output.put_line('Gender : '||v_gender);

EXCEPTION

WHEN gender_ex THEN


dbms_output.put_line('Please Enter valid gender');

END;

create table test_insert (id NUMBER, Name VARCHAR2(30));

DECLARE

abort_ex EXCEPTION;

BEGIN

FOR i IN 1..100

LOOP

BEGIN

IF mod(i,10)=0 THEN

RAISE abort_ex;

END IF;

INSERT INTO test_insert VALUES(i, 'Name'||i);

EXCEPTION

WHEN abort_ex THEN

NULL;

END;

END LOOP;

COMMIT;

END;

SELECT * FROM test_insert;


DROP TABLE test_insert;

SQLERRM and SQLCODE

********************

SQLCODE returns the current error code, and SQLERRM returns the current error message
text;

For user-defined exception SQLCODE returns 1 and SQLERRM returns “user-defined


exception”.

SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.

CREATE TABLE test_tb (id NUMBER);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

dbms_output.put_line(v_id);

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('SQLERRM : ' || SQLERRM);

dbms_output.put_line('SQLCODE : ' || SQLCODE);

END;
/*sample output*/

SQLERRM : ORA-01403: no data found

SQLCODE : 100

DROP TABLE test_tb;

PRAGMA EXCEPTION_INIT

*********************

Using this you can associate a named exception with a particular oracle error.

This gives you the ability to trap this error specifically, rather than via an OTHERS handler.

Syntax:

PRAGMA EXCEPTION_INIT(exception_name, oracle_error_number);

DECLARE

v_result NUMBER;

PRAGMA EXCEPTION_INIT(Invalid, -1476);

BEGIN

SELECT 453 / 0 INTO v_result FROM dual;

dbms_output.put_line('Result : ' || v_result);


EXCEPTION

WHEN INVALID THEN

dbms_output.put_line('Invalid Exception');

END;

RAISE_APPLICATION_ERROR

************************

You can use this built-in function to create your own error messages, which can be more
descriptive than named exceptions.

Error Number :

Oracle Error Range : From -00000 to -19999

User Error Range : From -20000 to -20999

DECLARE

v_gender CHAR := '&gender';

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE_APPLICATION_ERROR(-20003, 'Enter valid gender');

END IF;
dbms_output.put_line('Gender : ' || v_gender);

END;

Posted 21st October 2014 by Unknown

1 View comments

RajmohanMarch 13, 2018 at 6:49 AM

How to get the two table data without using Joins and sub query,union?

Reply

OCT

Package

1. You can groups logical related subprogram (procedures and functions)

2. It consist of two parts

I) specification

II) Body

3. It allows the oracle server to read multiple object in to a memory once

4. You can declare global variable,cursor, user define exeption


5. Overloading

6. we can't create anonyms block inside the package

create table err_log(sno NUMBER, u_name VARCHAR2(30), error_msg CLOB, hap_tm


TIMESTAMP);

select * from err_log;

--stand alone procedure

CREATE OR REPLACE PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id


%TYPE) IS

v_salary employees.salary%TYPE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT salary,

first_name

INTO v_salary,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line('Salary of ' || v_first_name || ' is ' || v_salary);


EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_sal_sp;

BEGIN

-- Call the procedure

emp_sal_sp(p_employee_id => :p_employee_id);

END;

CREATE OR REPLACE PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id


%TYPE) IS

v_hire_date DATE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT hire_date,
first_name

INTO v_hire_date,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line(v_first_name || ' hired on ' || to_char(v_hire_date,'month ddth,


yyyy'));

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_hdt_sp;

BEGIN

-- Call the procedure

emp_hdt_sp(p_employee_id => :p_employee_id);

END;
create or replace function sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER

IS

v_c NUMBER;

BEGIN

v_c := p_a + p_b;

RETURN v_c;

END;

--Specification Part

CREATE OR REPLACE PACKAGE emp_pkg

IS

PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id%TYPE);

PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id%TYPE);

FUNCTION sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER;

END emp_pkg ;
--Body Part

CREATE OR REPLACE PACKAGE BODY emp_pkg

IS

PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id%TYPE) IS

v_salary employees.salary%TYPE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT salary,

first_name

INTO v_salary,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line('Salary of ' || v_first_name || ' is ' || v_salary);

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,
v_error,

systimestamp);

commit;

END emp_sal_sp;

PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id%TYPE) IS

v_hire_date DATE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT hire_date,

first_name

INTO v_hire_date,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line(v_first_name || ' hired on ' || to_char(v_hire_date,'month ddth,


yyyy'));

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,
v_error,

systimestamp);

commit;

END emp_hdt_sp;

FUNCTION sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER

IS

v_c NUMBER;

BEGIN

v_c := p_a + p_b;

RETURN v_c;

END;

END emp_pkg;

A package specification can exist without a package body, but

a package body can't exist without a package specification.

--Executing procedure inside the package

BEGIN
emp_pkg.emp_sal_sp(120);

END;

--Executing function inside the package

SELECT emp_pkg.sum_fn(23,567) FROM dual;

-- You can declare global variable,cursor, user define exeption

create or replace package all_detail

as

PROCEDURE emp2sal (a IN NUMBER);

PROCEDURE emp2exep (a IN NUMBER);

FUNCTION add2num (a IN NUMBER, b IN NUMBER)

RETURN NUMBER;

c NUMBER(8); --global declaration

abort_ex EXCEPTION; --global exception declaration

CURSOR emp_rec --global cursor declaration

IS

SELECT first_name, salary, hire_date, department_id

FROM employees;
End all_detail;

create or replace package body all_detail

as

PROCEDURE emp2sal (a IN NUMBER)

AS

BEGIN

SELECT salary

INTO c

FROM Employees

WHERE Employee_id = a;

Dbms_output.put_line('Salary of Employee ' || a || ' is ' || c);

EXCEPTION

WHEN no_data_found THEN

Dbms_output.put_line('Please enter valid id');

END emp2sal;

PROCEDURE emp2exep (a IN NUMBER)

AS
BEGIN

SELECT Round(Months_between(sysdate,hire_date)/12)

INTO c

FROM Employees

WHERE Employee_id = a;

Dbms_output.put_line( c || ' Years');

EXCEPTION

WHEN no_data_found THEN

Dbms_output.put_line('Please enter valid id');

END emp2exep;

FUNCTION add2num (a IN NUMBER, b IN NUMBER)

RETURN NUMBER

AS

BEGIN

c := a+b;

RETURN C;

END;

End all_detail;
/*Declaring a Bodiless Package */

CREATE OR REPLACE PACKAGE global_constant

IS

mile_2_kilo CONSTANT NUMBER := 1.6093;

kilo_2_mile CONSTANT NUMBER := 0.6214;

yard_2_meter CONSTANT NUMBER := 0.9144;

meter_2_yard CONSTANT NUMBER := 1.0936;

END global_constant;

BEGIN

DBMS_OUTPUT.PUT_LINE('20 miles = ' || 20*global_constant.mile_2_kilo||' km');

END;

/*Forward Declaration in package */

DECLARE

PROCEDURE P2; -- forward declaration

PROCEDURE P3;

PROCEDURE P1 IS

BEGIN
dbms_output.put_line('From procedure p1');

p2;

END P1;

PROCEDURE P2 IS

BEGIN

dbms_output.put_line('From procedure p2');

p3;

END P2;

PROCEDURE P3 IS

BEGIN

dbms_output.put_line('From procedure p3');

END P3;

BEGIN

p1;

END;

sample output:

From procedure p1

From procedure p2

From procedure p3
Drop package package_name;

Drop package body package_name;

SELECT text FROM user_source u

WHERE u.name = 'EMP_PKG';

Interview Questions:

What is package?

Advantage of package

Is it possible to create package body with out package specification?

what is package overloading?

what is forward declaration in package?

which data dictionary table contain source code of package?

How to declare global variable, exception and cursor?

How to execute procedure and function inside the package?

Posted 4th October 2014 by Unknown

0 Add a comment
OCT

%TYPE and %ROWTYPE

--%type is used to fetch the data type of the particular column

create table product_details

p_id NUMBER(3),

p_nm VARCHAR2(30),

p_qty NUMBER(8),

order_dt DATE

);

BEGIN

INSERT INTO product_details VALUES(100,'Name0',400,'23-Mar-13');

INSERT INTO product_details VALUES(101,'Name1',600,'26-Apr-13');

INSERT INTO product_details VALUES(102,'Name2',800,'27-Jan-12');

INSERT INTO product_details VALUES(103,'Name3',300,'23-Jul-11');

INSERT INTO product_details VALUES(104,'Name4',200,'22-Aug-11');

INSERT INTO product_details VALUES(105,'Name5',500,'25-Oct-12');


commit;

END;

SELECT * FROM product_details;

------------------------------------

P_ID P_NM P_QTY ORDER_DT

------------------------------------

100 Name0 400 03/23/2013

101 Name1 600 04/26/2013

102 Name2 800 01/27/2012

103 Name3 300 07/23/2011

104 Name4 200 08/22/2011

105 Name5 500 10/25/2012

------------------------------------

DECLARE

v_name VARCHAR2(4);

BEGIN

SELECT p_nm

INTO v_name

FROM product_details
WHERE p_id = 100;

dbms_output.put_line('Product Name : ' || v_name);

--error numeric or value error

END;

DECLARE

v_name VARCHAR2(5);

BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 100;

dbms_output.put_line('Product Name : ' || v_name);

END;

ALTER TABLE product_details

MODIFY p_nm VARCHAR2(15);

INSERT INTO product_details

VALUES

(106,
'name6',

700,

'26-Dec-12');

commit;

106 name6 700 12/26/2012

DECLARE

v_name VARCHAR2(5);

BEGIN

SELECT p_nm INTO v_name

FROM product_details

WHERE p_id = 106;

dbms_output.put_line('Product Name : ' || v_name);

--error

END;

DECLARE
v_name product_details.p_nm%TYPE;

BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 106;

dbms_output.put_line('Product Name : ' || v_name);

END;

DROP TABLE product_details;

DECLARE

dep_id departments.department_id%TYPE;

dep_name departments.department_name%TYPE;

dep_man_id departments.manager_id%TYPE;

dep_loc_id departments.location_id%TYPE;

BEGIN

SELECT department_id,

department_name,
manager_id,

location_id

INTO dep_id,

dep_name,

dep_man_id,

dep_loc_id

FROM departments

WHERE department_id = 10;

dbms_output.put_line('Department_id : ' || dep_id);

dbms_output.put_line('Department_name : ' || dep_name);

dbms_output.put_line('Manager_id : ' || dep_man_id);

dbms_output.put_line('Location_id : ' || dep_loc_id);

END;

--%rowtype is used to fetch the data type of all the column

--Insted of using %type if we use %rowtype means we can reduce the no of variables that we
declare

DECLARE

dep_detail departments%ROWTYPE;
BEGIN

SELECT *

INTO dep_detail

FROM departments

WHERE department_id = 10;

dbms_output.put_line('Department_id : ' || dep_detail.department_id);

dbms_output.put_line('Department_name : ' || dep_detail.department_name);

dbms_output.put_line('Manager_id : ' || dep_detail.manager_id);

dbms_output.put_line('Location_id : ' || dep_detail.location_id);

END;

DROP TABLE dept_details;

CREATE TABLE dept_details

dept_id number(3) ,

dept_name varchar2(30),

dept_manager_name varchar2(30)

);
insert into dept_details values(10,'dept1','manager_name1');

insert into dept_details values(20,'dept2','manager_name2');

SELECT * FROM dept_details;

-------------------------------------------------------

| DEPT_ID | DEPT_NAME | DEPT_MANAGER_NAME |

+------------+-----------------------+-----------------

| 10 | dept1 | manager_name1 |

| 20 | dept2 | manager_name2 |

------------+-----------------------+------------------

DECLARE

all_data dept_details%ROWTYPE;

BEGIN

all_data.dept_id := 100;

all_data.dept_name := 'Admin';

all_data.dept_manager_name := 'John';

UPDATE dept_details

SET ROW = all_data

WHERE dept_id = 10;


dbms_output.put_line(SQL%ROWCOUNT || ' Row(s) get updated');

END;

1 Row(s) get updated

select * from dept_details;

---------------------------------------------------

| DEPT_ID | DEPT_NAME | DEPT_MANAGER_NAME|

---------------------------------------------------

| 100 | Admin | John |

| 20 | dept2 | manager_name2 |

---------------------------------------------------

Interview Question :

1. What is the use of %TYPE?

2. What is the use of %ROWTYPE?

3. Difference between %TYPE and %ROWTYPE?


Posted 2nd October 2014 by Unknown

0 Add a comment

SEP

29

BULK Exceptions

/************************************************************************

* Handling Exceptions in Bulk Operations *

* Documented on 29-SEP-14 04.35.35.980894 PM +05:30 *

* Document By : Murugappan Annamalai *

* Reference : http://www.dba-oracle.com/plsql/t_plsql_exceptions.htm *

************************************************************************/

CREATE TABLE bulk_tb (ran_num NUMBER NOT NULL);

--inserting data using bulk collect


DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

commit;

END;

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

200
TRUNCATE TABLE bulk_tb;

sample2.sql --without exception part

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

commit;

END;
/*

Error Message :

ORA-01400: cannot insert NULL into ("HR"."bulk_tb"."ran_num")

ORA-06512: at line 15

*/

sample2.sql --with exception part

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */


BEGIN

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

COMMIT;

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('Error while inserting bulk record '||SQLERRM);

END;

END;

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

99

SQL%BULK_EXCEPTIONS(i).ERROR_INDEX

Holds the iteration (not the subscript) of the original FORALL statement that raised the
exception.
In sparsely populated collections,

the exception row must be found by looping through the original collection the correct
number of times.

SQL%BULK_EXCEPTIONS(i).ERROR_CODE

Holds the exceptions error code.

The total number of exceptions can be returned using the collections COUNT method,

which returns zero if no exceptions were raised. The save_exceptions.sql script,

a modified version of the handled_exception.sql script, demonstrates this functionality.

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

v_ex_count NUMBER(4);

abort_ex EXCEPTION;

PRAGMA EXCEPTION_INIT(abort_ex, -24381);

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;
v_dat(100) := NULL;

v_dat(150) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

EXECUTE IMMEDIATE 'TRUNCATE TABLE bulk_tb';

BEGIN

FORALL i IN v_dat.FIRST..v_dat.LAST SAVE EXCEPTIONS

INSERT INTO bulk_tb VALUES(v_dat(i));

COMMIT;

EXCEPTION

WHEN abort_ex THEN

v_ex_count := SQL%BULK_EXCEPTIONS.COUNT;

FOR i IN 1..v_ex_count LOOP

dbms_output.put_line('Error: ' || i ||' Array Index: ' || SQL


%BULK_EXCEPTIONS(i).error_index ||

' Message: ' || SQLERRM(SQL%BULK_EXCEPTIONS(i).ERROR_CODE));

END LOOP;

END;

END;
/*

Sample output:

Error: 1 Array Index: 100 Message: -1400: non-ORACLE exception

Error: 2 Array Index: 150 Message: -1400: non-ORACLE exception

*/

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

198

SAVE EXCEPTIONS clause being removed, in the above script now traps a different error number.

The output from this script is listed below.

/*

Sample output:

Error: 1 Array Index: 100 Message: -1400: non-ORACLE exception

*/
SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

99

SELECT COUNT(*) FROM bulk_tb;

DROP TABLE bulk_tb;

Posted 29th September 2014 by Unknown

0 Add a comment

SEP

29

Cursor - FOR UPDATE

/************************************************************************
* FOR UPDATE clause in oracle *

* Document By : Murugappan Annamalai *

************************************************************************/

create table prod_details(p_id VARCHAR2(30), P_name VARCHAR2(30));

BEGIN

--Inserting data into prod_details table

FOR i IN 1..50 LOOP

INSERT INTO prod_details VALUES(i,'pname'||i);

END LOOP;

commit;

END;

SELECT * FROM prod_details;

DECLARE

CURSOR PROD_DTLS_C IS

SELECT * FROM PROD_DETAILS T1 FOR UPDATE OF P_ID;


V_PID PROD_DETAILS.P_ID%TYPE;

V_PRDNAME PROD_DETAILS.P_NAME%TYPE;

BEGIN

OPEN PROD_DTLS_C;

LOOP

FETCH PROD_DTLS_C INTO V_PID, V_PRDNAME;

IF PROD_DTLS_C%NOTFOUND THEN

EXIT;

ELSE

UPDATE PROD_DETAILS P

SET P.P_ID = LPAD(P_ID, 10, 0)

WHERE CURRENT OF PROD_DTLS_C;

END IF;

END LOOP;

CLOSE PROD_DTLS_C;

COMMIT;

END;

select * from PROD_DETAILS;


TRUNCATE TABLE prod_details;

BEGIN

--Inserting data into prod_details table

FOR i IN 1..50 LOOP

INSERT INTO prod_details VALUES(i,'pname'||i);

END LOOP;

commit;

END;

DECLARE

CURSOR PROD_DTLS_C IS

SELECT * FROM PROD_DETAILS T1 FOR UPDATE OF P_ID;

V_PID PROD_DETAILS.P_ID%TYPE;

V_PRDNAME PROD_DETAILS.P_NAME%TYPE;

BEGIN
OPEN PROD_DTLS_C;

LOOP

FETCH PROD_DTLS_C INTO V_PID, V_PRDNAME;

IF PROD_DTLS_C%NOTFOUND THEN

EXIT;

ELSE

UPDATE PROD_DETAILS P

SET P.P_ID = LPAD(P_ID, 10, 0)

WHERE CURRENT OF PROD_DTLS_C;

END IF;

COMMIT;

END LOOP;

CLOSE PROD_DTLS_C;

--COMMIT;

END;

select * from PROD_DETAILS;

Posted 29th September 2014 by Unknown

0 Add a comment
MAY

28

Escape Sequence in Oracle

Escape special characters when writing SQL queries

--to include single '

SELECT 'Steven's salary is more than 50k INR' AS "SAL_DETAILS"

FROM Dual;

ORA-01756 : quoted string not properly terminated

SELECT 'Steven''s salary is more than 50k INR' AS "SAL_DETAILS"

FROM Dual;

SAL_DETAILS

---------------------------------------

Steven's salary is more than 50k INR

--to include double '


SELECT 'You can print double quot ('''') in oracle' "Info"

FROM Dual;

Info

---------------------------------------

You can print double quot ('') in oracle

SELECT q'[some test ' some test ' some text ']' AS "In 10g"

FROM dual;

In 10g

------------------------------------

some test ' some test ' some text '

--Escape wild card characters ( _ and % )

The LIKE keyword allows for string searches.

The '_' wild card character is used to match exactly one character

While '%' is used to match zero or more occurrences of any characters.


These characters can be escaped in SQL as follows.

WITH mail_ids AS

SELECT 'an.murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an_murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an%murugappan@gmail.com' mail FROM Dual

SELECT * FROM mail_ids

WHERE mail LIKE '__$_%' ESCAPE '$';

mail

----------------------------------

an_murugappan@gmail.com

WITH mail_ids AS

SELECT 'an.murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an_murugappan@gmail.com' mail FROM Dual

UNION
SELECT 'an%murugappan@gmail.com' mail FROM Dual

SELECT * FROM mail_ids

WHERE mail LIKE '__/%%' ESCAPE '/';

mail

----------------------------------

an%murugappan@gmail.com

Escape ampersand (&) characters in SQL*Plus

SQL> select '&a' FROM dual;

'23'

----

23

SQL> SET ESCAPE '\'

SQL> select '\&a' FROM dual;

'&A'

----

&a
SQL> SET SCAN OFF;

SQL> select '&a' FROM dual;

'&A'

----

&a

SQL> SET SCAN ON;

SQL> select '&a' FROM dual;

'45'

----

45

Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Data Manipulation Language


Data Manipulation Language (DML) statements are used for managing data within schema
objects. Some examples:

INSERT - insert data into a table

UPDATE - updates existing data within a table

DELETE - deletes all records from a table, the space for the records remain

MERGE - UPSERT operation (insert or update)

CREATE TABLE prod_details

prod_id NUMBER(4) ,

prod_name VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

Deliver_dt DATE DEFAULT SYSDATE+3 ,

comments VARCHAR2(300)

);

SELECT * FROM prod_details;

no_data_found

INSERT
INSERT INTO prod_details(prod_id,prod_name,order_dt,deliver_dt,comments)

VALUES(100,'Apple iphone 5s','21-May-14','24-May-14','Color : Black');

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

---------------------------------------------------------------------------

--Inserting records with out mentioning column name

INSERT INTO prod_details

VALUES(101,'Samsung Galaxy III','20-Aug-14','23-Aug-14','Color : White');

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

---------------------------------------------------------------------------
--Inserting selective number of values

INSERT INTO prod_details

VALUES(103,'Moto X','11-May-14','13-May-14');

ORA-00947 : not enough values

--While inserting selective number of values mentioning column name is compulsory.

INSERT INTO prod_details (prod_id,prod_name,order_dt,deliver_dt)

VALUES(103,'Moto X','11-May-14','13-May-14');

SELECT * FROM prod_details;

--------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

--------------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

--------------------------------------------------------------------------------

--Inserting NULL value.


--If you want to insert NULL value you can ignore that column at the time of inserting

--or we can use NULL keyword to insert NULL.

INSERT INTO prod_details

VALUES(104,'Moto G','19-May-14','22-May-14',NULL);

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Noto G 5/19/2014 5/22/2014

---------------------------------------------------------------------------

--if you are not providing values for order_dt and deliver_dt column default value can be taken.

INSERT INTO prod_details(prod_id,prod_name,comments)

VALUES(105,'Nokia Lumis 720p','Color : Red');

SELECT * FROM prod_details;


---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

----------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Moto G 5/19/2014 5/22/2014

105 Nokia Lumis 720p 5/26/2014 5/29/2014 Color : Red

---------------------------------------------------------------------------

--Inserting data by using sub query

CREATE TABLE test_tab (id NUMBER, Name VARCHAR2(30));

INSERT INTO test_tab VALUES(1,'Name1');

INSERT INTO test_tab VALUES(2,'Name2');

INSERT INTO test_tab VALUES(3,'Name3');

SELECT COUNT(*) FROM test_tab;

COUNT(*)

-------

3
--creating table by using sub query (with out data)

CREATE TABLE ins_chk

SELECT * FROM test_tab

WHERE id = 900;

SELECT COUNT(*) FROM ins_chk;

COUNT(*)

-------

--Inserting data by using sub query

--copying data from test_tab to ins_chk

INSERT INTO ins_chk (SELECT * FROM test_tab);

3 rows inserted in 0.047 seconds.


SELECT COUNT(*) FROM ins_chk;

COUNT(*)

-------

DROP TABLE test_tab;

DROP TABLE ins_chk;

UPDATE

Syntax :

UPDATE table_name

SET column1_name = column1_value,

column2_name = column2_value,

column2_name = column3_value,

columnn_name = columnn_value

WHERE condition(s);

SELECT * FROM prod_details;


---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

----------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Moto G 5/19/2014 5/22/2014

105 Nokia Lumis 720p 5/26/2014 5/29/2014 Color : Red

---------------------------------------------------------------------------

UPDATE prod_details ps

SET ps.prod_name = 'iphone 5s'

WHERE ps.prod_id = 100;

1 row updated in 0.031 seconds

SELECT *

FROM prod_details ps

WHERE ps.prod_id = 100;

--------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

--------------------------------------------------------------------

100 iphone 5s 5/21/2014 5/24/2014 Color : Black


--------------------------------------------------------------------

--update statement with out condition

--If you try to execute update statement without condition it'll update all the records inside the
table.

UPDATE prod_details ps

SET ps.comments = 'None';

5 row updated in 0.031 seconds

SELECT *

FROM prod_details ps;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 None

101 Samsung Galaxy III 8/20/2014 8/23/2014 None

103 Moto X 5/11/2014 5/24/2014 None

104 Moto G 5/19/2014 5/22/2014 None

105 Nokia Lumis 720p 5/26/2014 5/29/2014 None

----------------------------------------------------------------------

--if your update text contain ' means you can use following metnod (use '')
UPDATE prod_details ps

SET ps.comments = 'Some product''s are not available'

WHERE ps.prod_id = 100;

1 row updated in 0.031 seconds

SELECT *

FROM prod_details ps

WHERE ps.prod_id = 100;

------------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

------------------------------------------------------------------------------------

100 iphone 5s 5/21/2014 5/24/2014 Some product's are not available

------------------------------------------------------------------------------------

DELETE

Syntax:

DELETE FROM table_name

WHERE condition(s);
DELETE FROM prod_details

WHERE prod_id IN (104, 105);

2 row(S) deleted in 0.032 seconds

SELECT *

FROM prod_details ps;

---------------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Some product's are not available

101 Samsung Galaxy III 8/20/2014 8/23/2014 None

103 Moto X 5/11/2014 5/24/2014 None

---------------------------------------------------------------------------------------

DELETE FROM prod_details;

3 row(s) deleted in 0.062 seconds.

SELECT * FROM prod_details;


no rows selected.

DROP TABLE prod_details;

MERGE = Insert + Update

-- will update soon.

Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Data Define Language

Data Definition Language (DDL) statements are used to define the database structure or schema.

Some examples:

CREATE - to create objects in the database.

ALTER - alters the structure of the database.


ADD

RENAME

MODIFY

DROP

DROP - delete objects from the database

TRUNCATE - remove all records from a table,

including all spaces allocated for the records are removed.

COMMENT - add comments to the data dictionary.

RENAME - rename an object.

Creating Table

--------------------------------------------------------------------------

Data Types Size Default Size Explanation

--------------------------------------------------------------------------

NUMBER(P,S) P: 1 to 38 we can store number between 0-9

S: -84 to 127

VARCHAR2 4000 Bytes we can store 0-9, a-z, A-Z and special characters

CHAR 2000 Bytes 1

DATE 7 Used to store Date

TIMESTAMP Includes year, month, day, hour, minute, and seconds.

LONG 2 GB Only one long column is allowed in a table.

We can't use this column in ORDER BY clause.

CLOB 4 GB Character Large Object


BLOB Binary Larger Object

--------------------------------------------------------------------------

CREATE

ALTER : ADD RENAME MODIFY DROP RENAME

RENAME

DROP

TRUNCATE

--creating table

CREATE TABLE friends_details_tb

Name VARCHAR2(30) ,

Phone NUMBER(10) ,

Gender CHAR ,

dob DATE ,

other_details LONG ,

make_dtm TIMESTAMP

);

DESC friends_details_tb;

-----------------------------
NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

-----------------------------

--maximum you can keep 255 columns in a table

ALTER : Colum level operations

ADD RENAME MODIFY DROP

ADD : Used to add a column after the table hase been created

ALTER TABLE friends_details_tb

ADD email VARCHAR2(30);

DESC friends_details_tb;
-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

EMAIL VARCHAR2(30)

-----------------------------

--adding multiple columns by using single ALTER statement

SYNTAX

ALTER TABLE friends_details_tb

ADD (

column_1 Data_type(size),

column_2 Data_type(size),

column_3 Data_type(size),

column_4 Data_type(size)

);
RENAME : Used to Rename a column

ALTER TABLE friends_details_tb

RENAME COLUMN email TO email_id;

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

MODIFY : Used to change the data type or size of the data type.
ALTER TABLE friends_details_tb

MODIFY other_details CLOB;

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS CLOB

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

--Modifying multiple columns at a time

ALTER TABLE friends_details_tb

MODIFY ( column_name_1 old_datatype(new_size),

column_name_2 new_datatype(old_size),

column_name_3 new_datatype(new_size)

);
DROP : Used to drop the column after the table has been created.

ALTER TABLE friends_details_tb

DROP COLUMN other_details;

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

RENAME : Used to Rename a particular table.

SYNTAX
RENAME old_table_name TO new_table_name;

RENAME friends_details_tb TO fnd_det;

DESCRIBE fnd_det;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

TRUNCATE : Used to remove the entire content of the table (not a structure)

SYNTAX

TRUNCATE TABLE table_name;

TRUNCATE TABLE fnd_det;


DROP : Used to drop the tabel (Data + stucture of the table get removed from the database )

DROP TABLE fnd_det;

*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Statements in Oracle

Data Definition Language (DDL)

DDL statements are used to define the database structure or schema. Some examples:

CREATE - to create objects in the database

ALTER - alters the structure of the database

ADD
RENAME

MODIFY

DROP

DROP - delete objects from the database

TRUNCATE - remove all records from a table,

including all spaces allocated for the records are removed

RENAME - rename an object

Data Manipulation Language (DML)

DML statements are used for managing data within schema objects. Some examples:

INSERT - insert data into a table

UPDATE - updates existing data within a table

DELETE - deletes all records from a table, the space for the records remain

MERGE - UPSERT operation (insert or update)

Data Control Language (DCL)

DCL statements. Some examples:

GRANT - gives users access privileges to database

REVOKE - withdraw access privileges given with the GRANT command


Transaction Control (TCL)

TCL statements are used to manage the changes made by DML statements. It allows
statements to be grouped together into logical transactions.

COMMIT - save work done

SAVEPOINT - identify a point in a transaction to which you can later roll back

ROLLBACK - restore database to original since the last COMMIT

Posted 28th May 2014 by Unknown

0 Add a comment

MAY

19

DECODE and CASE statement

CREATE TABLE students (

roll_no NUMBER(4) ,
Name VARCHAR2(30) ,

dept_cd VARCHAR2(20) ,

total_marks NUMBER(3)

);

BEGIN

INSERT INTO students VALUES (2000,'Rahul','CSE',480);

INSERT INTO students VALUES (2001,'Bala','IT', 390);

INSERT INTO students VALUES (2002,'Ramesh','CSE',250);

INSERT INTO students VALUES (2003,'Karthi','EEE',185);

INSERT INTO students VALUES (2004,'Ravi','IT',345);

END;

SELECT * FROM students;

DECODE

Decode is a function. Its a Oracle one.

Works like IF-THEN-ELSE.

You can use DECODE only in SELECT clause.

In DECODE you can include 255 things include Exep, search , result and default value.

Example

SELECT roll_no,
NAME,

dept_cd,

DECODE(dept_cd,

'CSE',

'Computer Science and Engineering',

'IT',

'Information Technology',

'Default Value') AS "DEPARTMENT NAME"

FROM students;

Sample Output

------------------------------------------------------------

ROLL_NO NAME DEPT_CD DEPARTMENT NAME

------------------------------------------------------------

2000 Rahul CSE Computer Science and Engineering

2001 Bala IT Information Technology

2002 Ramesh CSE Computer Science and Engineering

2003 Karthi EEE Default Value

2004 Ravi IT Information Technology

------------------------------------------------------------

CASE

CASE is an expression. Its a ANSI standard.

Compare to DECODE case will be more faster.


Example

SELECT roll_no,

NAME,

dept_cd,

total_marks,

CASE

WHEN total_marks > 500 THEN

'A Grade'

WHEN total_marks > 400 THEN

'B Grade'

WHEN total_marks > 300 THEN

'C Grade'

ELSE

'U Grade'

END AS "GRADE"

FROM students;

-----------------------------------------------

ROLL_NO NAME DEPT_CD TOTAL_MARKS GRADE

-----------------------------------------------

2000 Rahul CSE 480 B Grade

2001 Bala IT 390 C Grade

2002 Ramesh CSE 250 U Grade


2003 Karthi EEE 185 U Grade

2004 Ravi IT 345 C Grade

-----------------------------------------------

Interview Questions:

What is DECODE?

What is CASE?

Difference between CASE and DECODE? Which one is faster?

Posted 19th May 2014 by Unknown

0 Add a comment

MAY

19

Sub Query

Query with in another query

1. Single Row sub query

2. Multi row Sub query


select * from employees;

Want to fetch the person Who are all getting salary more than Neena's salary ?

Neena's Salary : 17000

Select First_name, salary

From Employees

Where salary > 17000;

--change in Neena's salary won't work for the above query.

Select salary From Employees

Where First_name = 'Neena';

Sub Query :

Select First_name, salary

From Employees

Where salary > (

Select salary From Employees

Where First_name = 'Neena'

);
Select * from employees;

Select salary From Employees

Where First_name = 'Alexander';

Sub Query Returns one value it is called as Single row sub query

Sub Query Returns more than one value it is called as Multi row sub query

Single row sub query operators :

> < >= <= = <>

Multiple Row Sub query operators :

IN ALL ANY

Who are all getting salary more than the average salary?

Select
First_name,

Salary

From

Employees

WHERE

Salary > (

SELECT Round(avg(salary),0)

FROM Employees

);

Multiple Row Sub query (In ANY ALL)

Select First_name,Department_id, salary

From Employees

Where salary in(

Select Salary From Employees

Where First_name = 'Alexander'

);

Any : Minimum Value will be taken (3100)

Select First_name,Department_id, salary

From Employees

Where salary > ANY(


Select Salary From Employees

Where First_name = 'Alexander'

);

All : Maximum Value will be taken (9000)

Select First_name,Department_id, salary

From Employees

Where salary > All(

Select Salary From Employees

Where First_name = 'Alexander'

);

We can use sub query in all the classes except Group by and order by class.

Select

From

Where

-----------Group by

having

-----------Order by

SELECT
( Select Count(*) from Employees Where Department_id = 90 )Executive,

( Select Count(*) from Employees Where Department_id = 60 ) IT,

( Select Count(*) from Employees Where Department_id = 10 ) Administration,

( Select Count(*) from Employees Where Department_id = 100) Finance

FROM

Dual;

Select Min(salary) From Employees;

Select Min(salary) from

Select * from Employees

Where Department_id = 60

);

What is INLINE VIEW?

If u use sub query in From it is call it is as INLINE VIEW.

Intermediate result set

Correlated sub query

SELECT employee_number, name

FROM employees Bob

WHERE salary > (


SELECT AVG(salary)

FROM employees

WHERE department = Bob.department

);

Posted 19th May 2014 by Unknown

0 Add a comment

Loading

Dynamic Views theme. Powered by Blogger.Oracle sql & Pl/sql

search

Home Sql and pl/sql Sql Interview Questions

JUL

20

INLINE view in Oracle with 12c New Features

Named sub Query in FROM clause is call it as INLINE VIEW.

Oracle process a inline view faster than sub query


Inline View in Oracle

--Query to display all the employees who are all getting salary more than their department
average salary

SELECT First_name

, last_name

, salary

, department_id

FROM employees a , ( SELECT b.department_id

, AVG(b.salary) avg_sal

FROM employees b

GROUP BY b.department_id

)b

WHERE a.department_id = b.department_id

AND a.salary > b.avg_salary;

Display all the customer who have placed more number of orders by using INLINE view

CREATE TABLE customer_order_det_tb

( custm_id NUMBER ,

custm_nm VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,


ttl_amt NUMBER(7,2)

);

BEGIN

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '11-Jul-15' , 45000.00);

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '14-Jul-15' , 27000.00);

INSERT INTO customer_order_det_tb VALUES(101, 'Raja' , '13-Jul-15' , 17000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 34000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 38000.00);

COMMIT;

END;

SELECT c.*

FROM customer_order_det_tb c;

--------------------------------------------

custm_id custm_nm order_dt ttl_amt

--------------------------------------------

100 Murugappan 7/11/2015 45000.00

100 Murugappan 7/14/2015 27000.00

101 Raja 7/13/2015 17000.00

102 Ramesh 7/15/2015 34000.00

102 Ramesh 7/15/2015 38000.00

--------------------------------------------
--Writing a Quer to display all the customer who have placed maximum number of order

--Query #1 for inline view

SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC;

--------------------------------

custm_id custm_nm total_odr

--------------------------------

100 Murugappan 2

102 Ramesh 2

101 Raja 1

--------------------------------

--Query #2 for inline view

SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm;

----------

total_odr
----------

----------

Inline view to find all the customers who have placed maximum number of orders

/****************************************

Syntax

SELECT * FROM <query1> x, <query2> y

WHERE contition;

****************************************/

SELECT query1.* FROM

( SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC

) query1,

( SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm

) query2

WHERE query1.total_odr = query2.total_odr;


-------------------------------

custm_id custm_nm total_odr

-------------------------------

100 Murugappan 2

102 Ramesh 2

-------------------------------

DROP TABLE customer_order_det_tb;

--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT

SELECT first_name, salary

FROM ( SELECT first_name, salary

FROM employees e

WHERE job_id NOT IN ('SALESMAN','PRESIDENT')

ORDER BY salary DESC

WHERE ROWNUM < 4;

New Oracle 12c Inline view Syntax

LATERAL clause for In-line views


Allows for columns in the inline view to be accessed!!

Example :

--in 11g

SELECT * FROM employees e, (

SELECT *

FROM departments d

WHERE e.department_id = d.department_id);

ORA-0090: "E"."DEPARTMENT_ID": Invalid Identifier

--in 12c

SELECT * FROM employees e, LATERAL(

SELECT *

FROM departments d

WHERE e.department_id = d.department_id

);

--in 11g

WITH t

AS

( SELECT LEVEL a
FROM dual

CONNECT BY LEVEL <= 30)

SELECT *

FROM t, (SELECT *

FROM employees

WHERE department_id = t.a

);

ORA-00904: "T"."A": invalid Identifier

--in 12c

WITH t

AS

(SELECT LEVEL a FROM dual CONNECT BY LEVEL <= 30)

SELECT * FROM t,

LATERAL(SELECT *

FROM employees

WHERE department_id = t.a);

Hope you have enjoyed this little article

Feed backs are always Welcome :) (:

Posted 20th July 2015 by Unknown

0 Add a comment
JAN

23

Salary Related Questions in Oracle

--creating table

CREATE TABLE employee_data

eid NUMBER(4),

ename VARCHAR2(30),

depno NUMBER(3),

salary NUMBER(8)

);

BEGIN

--Inserting records

INSERT INTO employee_data VALUES(1000,'Name01',90,30000);

INSERT INTO employee_data VALUES(1001,'Name02',90,6000);

INSERT INTO employee_data VALUES(1002,'Name03',90,23000);


INSERT INTO employee_data VALUES(1003,'Name04',60,35000);

INSERT INTO employee_data VALUES(1004,'Name05',60,60000);

INSERT INTO employee_data VALUES(1005,'Name06',60,30000);

INSERT INTO employee_data VALUES(1006,'Name07',80,36000);

INSERT INTO employee_data VALUES(1007,'Name08',80,29000);

INSERT INTO employee_data VALUES(1008,'Name09',80,37000);

INSERT INTO employee_data VALUES(1009,'Name10',80,41000);

COMMIT;

END;

SELECT * FROM employee_data

ORDER BY salary DESC;

--query to find maximum salary from employee_data table

SELECT MAX(salary) FROM employee_data;

--query to find minimum salary from employee_data table

SELECT MIN(salary) FROM employee_data;

--query to find second maximum salary from employee_data table


SELECT MAX(salary)

FROM employee_data

WHERE salary NOT IN (SELECT MAX(salary)

FROM employee_data);

--query to select 5th maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= 5);

--query to select nth maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= &n);

--query to select all the details of the employee whose getting nth maximum salary
SELECT *

FROM (SELECT emp.*,

rownum rn

FROM (SELECT *

FROM employee_data

ORDER BY salary DESC) emp)

WHERE rn = 9;

--same query using row_numbr( ) function

SELECT *

FROM (SELECT emp.*,

row_number() over(ORDER BY salary) rank

FROM employee_data emp)

WHERE rank = 9;

--same query using rank( ) function

SELECT *

FROM (SELECT emp.*,

rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;
--same query using dense_rank( ) function

SELECT *

FROM (SELECT emp.*,

dense_rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--query to display display maximum salary in all the department

SELECT e.depno "Department id",

MAX(salary) "Maximum Salary"

FROM employee_data e

GROUP BY e.depno;

--query to display all the employees who are all getting salary more than average salary of the
company

SELECT e.* FROM employee_data e

WHERE salary > (SELECT AVG(salary) FROM employee_data);

--query to display all the employees who are all getting salary more than their department
average salary
SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE department_id = OUT.department_id);

--query to display all the employees who are all getting salary more than their manager salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE employee_id = OUT.manager_id);

Documented By : Murugappan Annamalai

Posted on : 23-Jan-15 16:34:00 IST.


Hope you have enjoyed this little article

Feed backs are always welcome :)

Posted 23rd January 2015 by Unknown

7 View comments

JAN

22

Why prefer COALESCE over NVL

Documented By : Nimish Garg

I prefer using "COALESCE" over "NVL" is some of the scenarios. Last week One of my friend
asked me what is the advantage of using "COALESCE" where we can simply use "NVL". I simply
gave him the reply from Oracle Docs i.e. NVL lets you replace null (returned as a blank) with a
string in the results of a query and COALESCE returns the first non-null expr in the expression list.
Oracle Database uses short-circuit evaluation with "COALESCE".

He replied that he knows the difference, he knows that "COALESCE" can take multiple arguments
and so on. He was more interested in understanding "short-circuit evaluation" of "COALESCE"
and the scenarios where I prefer using "COALESCE" over "NVL".

To make him understand I created following function which takes One second in every execution
and simply returns '--null--' and executed 2 very similar queries one with NVL and other with
COALESCE.
SQL> create or replace function f_null return varchar2

2 is

3 begin

4 dbms_lock.sleep(1);

5 return '--null--';

6 end;

7 /

Function created.

Following are the queries which I used to demonstrate that NVL evaluates both arguments even
if the second argument is not used and COALESCE uses short-circuit evaluation i.e. it only
evaluates the arguments only if they are needed.

SQL> select e.empno, e.ename ename, nvl(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE


7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.

Elapsed: 00:00:14.01

SQL> select e.empno, e.ename ename, coalesce(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE


7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.

Elapsed: 00:00:01.01

Here we can see easily that the first query with NVL took 14+ seconds, one second for each
record even if the "f_null" value was used only in one record. On the contrary as mentioned in
Oracle Documentation "COALESCE" uses its "short-circuit evaluation" and "f_null" was called
only once and so second query took only One Second. "COALESCE" is certainly use less resources
than NVL.

Posted 22nd January 2015 by Unknown

0 Add a comment

DEC

21
Constraints

It Enforce Rule On Table

We can create constraint at the time of Creating Table

1. Column Level Declaration

2. Table Level Declaration

1. We can provide own name.

Format : [part_of_project_name-table_name-column_name-constraint_type]

Example : gmind_emp_id_pk _uk _ck _f

2. system name name

Format : sys_cn

Example : SYS_C405323

We can create constraint after the table has been created

Types
Primary Key

Not allowed Null value

Not allowed you to enter duplicate value

Ex : Employee_id, Student_id

Unique Key

allowed Null value

Not allowed you to enter duplicate value

Ex : Contact_no, email

Foreign Key

It will allowed you to enter NULL and Duplicate value.

c1(pk) : 1 2 3

c2(f) : 1 1 2 3 4 Not allowed

Allowed you to enter duplicate value and null value


Not Null

It will not allowed you to enter null value

Check

You can check your own condition

Simple Table for understanding

------------------------------------

Duplicate NULL

------------------------------------

Primary Key X X

Unique Key X Allowed

Foreign Key Allowed Allowed

------------------------------------

creating table with all constraint type

Create table my_stu_details


(

S_id Number(2),

S_name Varchar2(30) Not Null, --SYS_Cn

s_mail Varchar2(30),

s_gender char(1),

s_did Number(3),

Constraint my_stu_sid_pk PRIMARY KEY (s_id),

constraint my_stu_mail_uk UNIQUE (s_mail) ,

Constraint my_stu_gen_ck CHECK (s_gender IN ('M', 'F', 'm', 'f')),

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

);

DESC my_stu_details;

------------------------------------

Name Type Nullable

------------------------------------

S_ID NUMBER(2)

S_NAME VARCHAR2(30)

S_MAIL VARCHAR2(30) Y

S_GENDER CHAR(1) Y

S_DID NUMBER(3) Y

------------------------------------
Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name1' , 'name1@gmail.com' , 'm' , 60 );

Select * from my_stu_details;

Validating Primary Key

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-00001: unique constraint (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (NULL, 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-01400: cannot insert NULL into (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (2 , 'name2' , 'name2@gmail.com' , 'F' , 90 );


Select * from my_stu_details;

Validating NOT NULL Constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , NULL , 'name3@gmail.com' , 'F' , 80 );

ORA-01400: cannot insert NULL into ("HR"."MY_STU_DETAILS"."S_NAME")

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , 'Name3' , 'name3@gmail.com' , 'F' , 80 );

Select * from my_stu_details;

Validating Unique Key Constraint

--Duplicate Check
Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , 'name3@gmail.com' , 'F' , 80 );

ORA-00001: unique constraint (HR.MY_STU_MAIL_UK) violated

--Null Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , null , 'M' , 70 );

Select * from my_stu_details;

Validating Check constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'j' , 70 );

ORA-02290: check constraint (HR.MY_STU_GEN_CK) violated


Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'M' , 70 );

Select * from my_stu_details;

Validating Foreign Key

Select * from Departments;

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 3 );

ORA-02291: integrity constraint (HR.MY_STU_DID_FK) violated - parent key not found

Departments table : parent table

my_stu_details : Child table

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 90 );


Select * from my_stu_details;

--------------------------------------------------------

s_id s_name s_mail s_gender s_did

--------------------------------------------------------

1 name1 name1@gmail.com m 60

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 M 70

5 Name5 name5@gmail.com M 70

6 Name6 name6@gmail.com F 90

--------------------------------------------------------

Deleting the Primary key value which is referred by Foreign Key

Select * from Departments;

DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID

------------------------------------------------------------

60 IT 103 1400 <---- Delete


-- don't execute this query

--Delete From Departments

--Where Department_id = 60;

1) ON DELETE SET NULL

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

1 name1 name1@gmail.com m -

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

2) ON DELETE SET CASCADE

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------
6 Name6 name6@gmail.com F 90

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

Syntax

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE CASCADE

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE SET NULL

Constraint Related Data Dictionary Table information.

To view constraint Information

SELECT c.owner,

c.constraint_name,

c.constraint_type,

c.table_name,
c.r_constraint_name,

c.status

FROM user_constraints c

WHERE c.table_name = 'MY_STU_DETAILS';

------------------------------------------------------------------------------------

owner constraint_name constraint_type table_name r_constraint_name status

------------------------------------------------------------------------------------

HR SYS_C004023 C MY_STU_DETAILS ENABLED

HR MY_STU_GEN_CK C MY_STU_DETAILS ENABLED

HR MY_STU_SID_PK P MY_STU_DETAILS ENABLED

HR MY_STU_MAIL_UK U MY_STU_DETAILS ENABLED

HR MY_STU_DID_FK R MY_STU_DETAILS DEPT_ID_PK ENABLED

------------------------------------------------------------------------------------

To view constraint name with corresponding column name

SELECT * FROM user_cons_columns c

WHERE c.table_name = 'MY_STU_DETAILS';

-------------------------------------------------------------

owner constraint_name table_name column_name position


-------------------------------------------------------------

HR MY_STU_MAIL_UK MY_STU_DETAILS S_MAIL 1

HR MY_STU_SID_PK MY_STU_DETAILS S_ID 1

HR MY_STU_GEN_CK MY_STU_DETAILS S_GENDER

HR SYS_C004023 MY_STU_DETAILS S_NAME

HR MY_STU_DID_FK MY_STU_DETAILS S_DID 1

-------------------------------------------------------------

Creating Composite Primary Key

Creating Primary Key with more than one number of column

ALTER TABLE table_name

ADD CONSTRAINT constraint_name PRIMARY KEY(column1, column_2 , column3);

In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.

creating constraint after the table creation

ALTER TABLE table_name

ADD CONSTRAINT constraint_name CONSTRAINT_TYPE(column_name);


ALTER TABLE table_name

DROP CONSTRAINT constraint_name;

ALTER TABLE table_name

DROP PRIMARY KEY;

To drop related foreign key

ALTER TABLE table_name

DROP PRIMARY KEY CASCADE;

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name;

Disable constraint with related foreign key constraint

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name CASCADE;

ALTER TABLE table_name


ENABLE CONSTRAINT constraint_name;

Interview Questions

What are all the type of constraint available in oracle?

Difference between PRIMARY KEY and UNIQUE key.

Difference between PRIMARY KEY ans FOREIGN KEY.

Difference between UNIQUE key and FOREIGN KEY.

Is it possible to create tow primary key in single table.

Write a syntax to create FOREIGN constraint.

How to create constraint after the table has been created?

How to enable and disable a constraint.

Which data dictionary table contains information about constraints?

Which Data Dictionary table contains information about constraint with corresponding column
name?

What is composite primary key?

Explain ON DELETE CASCADE and ON DELETE SET NULL option.

~Thanks For Reading~

Post your valuable feedback below


Posted 21st December 2014 by Unknown

1 View comments

UnknownMay 22, 2017 at 12:39 AM

good

Reply

DEC

listagg in Oracle 11g

Oracle 11gR2 listagg built-in function allows for many table columns to be displayed within a
single row, a non-first-normal form display

Syntax :

listagg(column_value,'delimiter') WITHIN GROUP(ORDER BY column_name)

--Example 1:

CREATE TABLE test_ins(empid NUMBER,product VARCHAR2(30));


BEGIN

INSERT INTO test_ins VALUES( 101,'pendrive');

INSERT INTO test_ins VALUES( 102,'toy');

INSERT INTO test_ins VALUES( 101,'ipod');

INSERT INTO test_ins VALUES( 102,'hat');

INSERT INTO test_ins VALUES( 103,'cpu');

INSERT INTO test_ins VALUES( 104,'pen');

INSERT INTO test_ins VALUES( 104,'car');

INSERT INTO test_ins VALUES( 104,'mat');

INSERT INTO test_ins VALUES( 105,'tv');

INSERT INTO test_ins VALUES( 106,'laptop');

commit;

END;

SELECT * FROM test_ins;

SELECT empid "Employee",

listagg(product,

',') within

GROUP (ORDER BY empid) "Products"

FROM test_ins

GROUP BY empid;

-->-- Result set --<--


DROP TABLE test_ins;

-->-- Example 2

select department_id "Department id", listagg(first_name,', ') WITHIN GROUP(ORDER BY


employee_id) "Employees"

FROM employees

WHERE department_id IN (10,20,30,60)

GROUP BY department_id;

-->-- Result set --<--


Posted 4th December 2014 by Unknown

0 Add a comment

NOV

Condition and Looping Statement

IF

IF ELSE

Multiple IF ELSE

LOOP

FOR LOOP

WHILE LOOP

create table test_udt(id NUMBER, salary NUMBER);

BEGIN
INSERT INTO test_udt VALUES(001,23000);

INSERT INTO test_udt VALUES(002,43000);

INSERT INTO test_udt VALUES(003,78000);

INSERT INTO test_udt VALUES(004,25000);

INSERT INTO test_udt VALUES(005,26000);

INSERT INTO test_udt VALUES(006,90000);

Commit;

END;

select * from test_udt;

IF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 1;

IF v_salary > 20000 THEN


UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

END IF;

commit;

END;

IF ELSE

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

ELSE
UPDATE test_udt t

SET t.salary = v_salary+20007

WHERE t.id = v_id ;

END IF;

commit;

END;

--same example with less number of lines

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

v_salary := v_salary+10005;

ELSE

v_salary := v_salary+20007;

END IF;
UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

Multiple IF ELSIF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 3;

IF v_id = 1 THEN

v_salary := 1000;

dbms_output.put_line('1 inside');
ELSIF v_id = 2 THEN

v_salary := 2000;

dbms_output.put_line('2 inside');

ELSIF v_id = 3 THEN

v_salary := 3000;

dbms_output.put_line('3 inside');

ELSIF v_id = 4 THEN

v_salary := 4000;

dbms_output.put_line('4 inside');

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

LOOP

--syntax
LOOP

--statements

--increment

--exit statement

END LOOP;

CREATE TABLE prod_details (pid VARCHAR2(3), pname VARCHAR2(30));

DECLARE

i NUMBER := 1;

x VARCHAR2(3);

BEGIN

LOOP

x := lpad(i,3,'0');

dbms_output.put_line('x value : '|| x);

INSERT INTO prod_details VALUES(i, 'Product '||i);

EXIT WHEN i >900;

i := i+1;

IF MOD(i,100) = 0 THEN

commit;

dbms_output.put_line('commit executed');

END IF;
END LOOP;

END;

SELECT * FROM prod_details ORDER BY 1;

DROP TABLE prod_details;

FOR LOOP

BEGIN

FOR I in 1..5

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

FOR LOOP - Reverse

BEGIN

FOR I in REVERSE 14..50

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;
/

WHILE LOOP

DECLARE

i_val NUMBER:=0;

BEGIN

WHILE (i_val < 11)

LOOP

dbms_output.put_line('The value of I is '||i_val);

i_val := i_val + 1;

END LOOP;

END;

sample output:

The value of I is 0

The value of I is 1

The value of I is 2

The value of I is 3

The value of I is 4

The value of I is 5

The value of I is 6

The value of I is 7
The value of I is 8

The value of I is 9

The value of I is 10

Posted 8th November 2014 by Unknown

0 Add a comment

OCT

21

Bulk Collect

This is used for array fetches

With this you can retrieve multiple rows of data with a single round trip.

This reduces the number of context switches between the pl/sql and sql engines.

You can use bulk collect in both dynamic and static sql.

You can use bulk collect in select, fetch into and returning into clauses.

SQL engine automatically initializes and extends the collections you reference in the bulk
collect clause.

You can fetch into multiple collections with one column each.

You can use the limit clause of bulk collect to restrict the no of rows retrieved.
SELECT * FROM product_details;

-->-- Bulk collect in FETCH INTO --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Bulk collect in SELECT clause --<--


DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

BEGIN

SELECT * BULK COLLECT INTO dta FROM product_details;

FOR i IN dta.FIRST .. dta.LAST LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- LIMIT in Bulk collect --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta LIMIT 30;

CLOSE proddt_cur;
FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Multiple fetches in INTO clause --<--

SELECT * FROM product_details;

DECLARE

TYPE alldata_typ1 IS TABLE OF product_details.p_id%TYPE;

TYPE alldata_typ2 IS TABLE OF product_details.p_name%TYPE;

dta1 alldata_typ1;

dta2 alldata_typ2;

CURSOR proddt_cur IS

SELECT p_id, p_name FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta1, dta2;

CLOSE proddt_cur;
FOR i IN dta1.FIRST .. dta1.COUNT LOOP

dbms_output.put_line('Department Id : ' || dta1(i));

END LOOP;

FOR i IN dta2.FIRST .. dta2.COUNT LOOP

dbms_output.put_line('Department Name : ' || dta2(i));

END LOOP;

END;

DROP TABLE dep_details;

DROP TABLE product_details;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Ref Cursor

This is unconstrained cursor which will return different types depends upon the user input.
Ref cursors cannot be closed implicitly.

Ref cursor with return type is called strong cursor.

Ref cursor without return type is called weak cursor.

You can declare ref cursor type in package spec as well as body.

You can declare ref cursor types in local subprograms or anonymous blocks.

CREATE OR REPLACE PROCEDURE ref_c_sp(dep_det_c IN OUT SYS_REFCURSOR)

AS

BEGIN

OPEN dep_det_c

FOR

SELECT * FROM dep_details d;

END;

DECLARE

dep_det_c SYS_REFCURSOR;

tab_data dep_details%ROWTYPE;

BEGIN

ref_c_sp(dep_det_c);

LOOP

FETCH dep_det_c INTO tab_data;


EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department Name : '|| tab_data.d_name);

END LOOP;

CLOSE dep_det_c;

END;

/*sample output*/

Department Name : Admin

Department Name : HR

Department Name : Sales

Department Name : Marketing

DROP PROCEDURE ref_c_sp;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Cursor
SQL Private work Area where the query get passed and executed.

Types

******

Implicit(SQL)

Explicit

-->-- advanced cursor types --<--

Parametrized Cursor

Ref Cursor

Implicit

********

ORACLE implicitly opens a cursor to process each SQL statement not associated with an
explicitly declared cursor.

PL/SQL lets you refer to the most recent implicit cursor as the SQL” cursor. So, although you
cannot use the OPEN,

FETCH, and CLOSE statements to control an implicit cursor, you can still use cursor attributes to
access information

about the most recently executed SQL statement.

Cursor Stages

**************
OPEN cursor_name

FETCH (with in loop)

CLOSE cursor_name

Explicit

The set of rows returned by a query can consist of zero, one, or multiple rows,

depending on how many rows meet your search criteria. When a query returns multiple rows,

you can explicitly define a cursor to process the rows. You use three commands to control the
cursor

Cursor Attributes

*****************

%FOUND

%NOTFOUND

%ISOPEN

%ROWCOUNT

%BULK_ROWCOUNT --<-- used to handle error while using bulk collection.

%BULK_EXCEPTIONS --<-- used to handle error while using bulk collection.

Cursor Declaration

DECLARE

CURSOR <cursor_name>

IS
<SELECT statement>

BEGIN

--> some stmt

END;

Cursor Loop

Loop

While Loop

For Loop

Cursor Clauses

Return

For update

Where current of

Bulk collect

-->-- creating table

create table product_details

p_id NUMBER,

p_name VARCHAR2(30),

p_order_dt DATE

);
-->-- Inserting data

BEGIN

FOR i IN 1 .. 75 LOOP

INSERT INTO product_details VALUES (i, 'prod_name_' || i, SYSDATE + i);

END LOOP;

commit;

END;

-->-- selecting data

SELECT * FROM product_details;

---------------------------------------------

p_id p_name p_order_dt

---------------------------------------------

1 prod_name_1 10/11/2014 3:48:32 PM

2 prod_name_2 10/12/2014 3:48:32 PM

3 prod_name_3 10/13/2014 3:48:32 PM

4 prod_name_4 10/14/2014 3:48:32 PM

5 prod_name_5 10/15/2014 3:48:32 PM

6 prod_name_6 10/16/2014 3:48:32 PM


7 prod_name_7 10/17/2014 3:48:32 PM

8 prod_name_8 10/18/2014 3:48:32 PM

9 prod_name_9 10/19/2014 3:48:32 PM

10 prod_name_10 10/20/2014 3:48:32 PM

11 prod_name_11 10/21/2014 3:48:32 PM

12 prod_name_12 10/22/2014 3:48:32 PM

13 prod_name_13 10/23/2014 3:48:32 PM

14 prod_name_14 10/24/2014 3:48:32 PM

15 prod_name_15 10/25/2014 3:48:32 PM

16 prod_name_16 10/26/2014 3:48:32 PM

17 prod_name_17 10/27/2014 3:48:32 PM

18 prod_name_18 10/28/2014 3:48:32 PM

19 prod_name_19 10/29/2014 3:48:32 PM

20 prod_name_20 10/30/2014 3:48:32 PM

---------------------------------------------

----------------------------------------------

Implicit Cursor

----------------------------------------------

--will update soon

----------------------------------------------

Explicit Cursor
----------------------------------------------

**********************************************

Processing cursor data by using LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND; --<-- if next record not found means control will
come out from the loop

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

END;
/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

EXIT WHEN prod_detail_cur%FOUND; --<-- if next record found means control will come
out from the loop
END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||


' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor Already closed


DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

-->-- CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;
END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor closed

**********************************************

Processing cursor data by using WHILE LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS
SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

OPEN prod_detail_cur;

FETCH prod_detail_cur

INTO all_data;

WHILE prod_detail_cur%FOUND LOOP

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

FETCH prod_detail_cur

INTO all_data;

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )


************************************************************

Processing cursor data by using FOR LOOP - CURSOR FOR LOOP

************************************************************

DECLARE

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

FOR i IN prod_detail_cur

LOOP

dbms_output.put_line('Product id : ' || i.p_id ||

' Product Name : ' || i.p_name ||

' ( Orderd on : ' || TRIM(i.p_order_dt) || ' )');

END LOOP;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )


Parameterized Cursor

*********************

This was used when you are going to use the cursor in more than one place with different
values for the same where clause.

Cursor parameters must be in mode.

Cursor parameters may have default values.

The scope of cursor parameter is within the select statement.

CREATE TABLE dep_details(d_id NUMBER,d_name VARCHAR2(30), location_id NUMBER);

BEGIN

INSRT INTO dep_details VALUES(001,'Admin',1010);

INSRT INTO dep_details VALUES(002,'HR',1010);

INSRT INTO dep_details VALUES(003,'Sales',1020);

INSRT INTO dep_details VALUES(004,'Marketing',1020);

commit;

END;

SELECT * FROM dep_details;


----------------------------

d_id d_name location_id

----------------------------

1 Admin 1010

2 HR 1010

3 Sales 1020

4 Marketing 1020

----------------------------

DECLARE

-->--Declaring parameterized cursor

CURSOR dep_det_c(p_location_id NUMBER) IS

SELECT * FROM dep_details d WHERE d.location_id = p_location_id;

all_data dep_details%ROWTYPE;

BEGIN

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

OPEN dep_det_c(1010);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);


END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

-->-- opening same cursor with different input value

OPEN dep_det_c(1020);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

END;

/*sample output*/

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 1 Department Name : Admin

Department id : 2 Department Name : HR


-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 3 Department Name : Sales

Department id : 4 Department Name : Marketing

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Handling Exception

Error Handling in oracle

ERROR

Any departure from the expected behavior of the system or program,

which stops the working of the system is an error.

Types : compile time error

Run time error

EXCEPTION

Any error or problem which one can handle and continue to work normally.
Handling Exception

When exception is raised, control passes to the exception section of the block.

i.e. EXCEPTION

WHEN name_of_exception THEN

Types : Pre Defined Exceptions

User Defined Exceptions

Predefined Exception

*********************

Oracle has predefined several exceptions that correspond to the most common oracle errors.

------------------------------------------------------------------------

Exception Oracle Error SQL Code Value

------------------------------------------------------------------------

ZERO_DIVIDE ORA-01476 -1476

NO_DATA_FOUND ORA-01403 +100

DUP_VAL_ON_INDEX ORA-00001 -1

TOO_MANY_ROWS ORA-01422 -1422

VALUE_ERROR ORA-06502 -6502

CURSOR_ALREADY_OPEN ORA-06511 -6511


OTHERS

------------------------------------------------------------------------

-->-- ZERO_DIVIDE --<--

Your program attempts to divide a number by zero.

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN ZERO_DIVIDE THEN

dbms_output.put_line('Divisor is equal to zero');

END;

-->-- NO_DATA_FOUND --<--

Single row SELECT returned no rows or your program referenced a deleted element in a nested
table

or an uninitialized element in an associative array (index-by table).

CREATE TABLE test_tb(id NUMBER PRIMARY KEY);


DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN NO_DATA_FOUND THEN

dbms_output.put_line('There is no data inside the table');

END;

-->-- DUP_VAL_ON_INDEX --<--

A program attempted to insert duplicate values in a column that is constrained by a unique


index.

INSERT INTO test_tb VALUES (1);

INSERT INTO test_tb VALUES (2);

commit;

BEGIN

INSERT INTO test_tb VALUES (2);

EXCEPTION

WHEN DUP_VAL_ON_INDEX THEN

dbms_output.put_line('Duplicate values are not allowed');


END;

-->-- TOO_MANY_ROWS --<--

Single row SELECT returned multiple rows.

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN TOO_MANY_ROWS THEN

dbms_output.put_line('Query returning more than one row');

END;

DROP TABLE test_tb;

-->-- VALUE_ERROR --<--

An arithmetic, conversion, truncation, or size constraint error occurred.

DECLARE
num1 NUMBER(2);

BEGIN

num1 := 345;

EXCEPTION

WHEN VALUE_ERROR THEN

dbms_output.put_line('check the size of the variable');

END;

-->-- CURSOR_ALREADY_OPEN --<--

A program attempted to open an already opened cursor.

CREATE TABLE emp(id NUMBER, name VARCHAR2(30));

BEGIN

INSERT INTO emp VALUES(1,'Name1');

INSERT INTO emp VALUES(2,'Name2');

INSERT INTO emp VALUES(3,'Name3');

INSERT INTO emp VALUES(4,'Name4');

COMMIT;

END;
SELECT * FROM emp;

DECLARE

cursor emp_c IS

SELECT * FROM emp;

all_data emp%ROWTYPE;

BEGIN

OPEN emp_c;

OPEN emp_c;

NULL;

CLOSE emp_c;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

END;

DROP TABLE emp;

-->-- OTHERS --<--

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;


EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

WHEN OTHERS THEN

dbms_output.put_line('Some other error ' || SQLERRM);

END;

User Defined Exception

**********************

A user-defined exception is an error that is defined by the programmer.

User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,

exceptions have a type EXCEPTION and scope.

DECLARE

v_gender CHAR := '&gender';

gender_ex EXCEPTION;

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE gender_ex;

END IF;

dbms_output.put_line('Gender : '||v_gender);
EXCEPTION

WHEN gender_ex THEN

dbms_output.put_line('Please Enter valid gender');

END;

create table test_insert (id NUMBER, Name VARCHAR2(30));

DECLARE

abort_ex EXCEPTION;

BEGIN

FOR i IN 1..100

LOOP

BEGIN

IF mod(i,10)=0 THEN

RAISE abort_ex;

END IF;

INSERT INTO test_insert VALUES(i, 'Name'||i);

EXCEPTION

WHEN abort_ex THEN

NULL;

END;

END LOOP;

COMMIT;

END;
SELECT * FROM test_insert;

DROP TABLE test_insert;

SQLERRM and SQLCODE

********************

SQLCODE returns the current error code, and SQLERRM returns the current error message
text;

For user-defined exception SQLCODE returns 1 and SQLERRM returns “user-defined


exception”.

SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.

CREATE TABLE test_tb (id NUMBER);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

dbms_output.put_line(v_id);

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('SQLERRM : ' || SQLERRM);


dbms_output.put_line('SQLCODE : ' || SQLCODE);

END;

/*sample output*/

SQLERRM : ORA-01403: no data found

SQLCODE : 100

DROP TABLE test_tb;

PRAGMA EXCEPTION_INIT

*********************

Using this you can associate a named exception with a particular oracle error.

This gives you the ability to trap this error specifically, rather than via an OTHERS handler.

Syntax:

PRAGMA EXCEPTION_INIT(exception_name, oracle_error_number);

DECLARE

v_result NUMBER;

PRAGMA EXCEPTION_INIT(Invalid, -1476);

BEGIN
SELECT 453 / 0 INTO v_result FROM dual;

dbms_output.put_line('Result : ' || v_result);

EXCEPTION

WHEN INVALID THEN

dbms_output.put_line('Invalid Exception');

END;

RAISE_APPLICATION_ERROR

************************

You can use this built-in function to create your own error messages, which can be more
descriptive than named exceptions.

Error Number :

Oracle Error Range : From -00000 to -19999

User Error Range : From -20000 to -20999

DECLARE

v_gender CHAR := '&gender';

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN


RAISE_APPLICATION_ERROR(-20003, 'Enter valid gender');

END IF;

dbms_output.put_line('Gender : ' || v_gender);

END;

Posted 21st October 2014 by Unknown

1 View comments

RajmohanMarch 13, 2018 at 6:49 AM

How to get the two table data without using Joins and sub query,union?

Reply

OCT

Package

1. You can groups logical related subprogram (procedures and functions)

2. It consist of two parts

I) specification

II) Body
3. It allows the oracle server to read multiple object in to a memory once

4. You can declare global variable,cursor, user define exeption

5. Overloading

6. we can't create anonyms block inside the package

create table err_log(sno NUMBER, u_name VARCHAR2(30), error_msg CLOB, hap_tm


TIMESTAMP);

select * from err_log;

--stand alone procedure

CREATE OR REPLACE PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id


%TYPE) IS

v_salary employees.salary%TYPE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT salary,

first_name

INTO v_salary,

v_first_name

FROM employees
WHERE employee_id = p_employee_id;

dbms_output.put_line('Salary of ' || v_first_name || ' is ' || v_salary);

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_sal_sp;

BEGIN

-- Call the procedure

emp_sal_sp(p_employee_id => :p_employee_id);

END;

CREATE OR REPLACE PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id


%TYPE) IS

v_hire_date DATE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);
BEGIN

SELECT hire_date,

first_name

INTO v_hire_date,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line(v_first_name || ' hired on ' || to_char(v_hire_date,'month ddth,


yyyy'));

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_hdt_sp;

BEGIN

-- Call the procedure

emp_hdt_sp(p_employee_id => :p_employee_id);


END;

create or replace function sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER

IS

v_c NUMBER;

BEGIN

v_c := p_a + p_b;

RETURN v_c;

END;

--Specification Part

CREATE OR REPLACE PACKAGE emp_pkg

IS

PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id%TYPE);

PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id%TYPE);

FUNCTION sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER;
END emp_pkg ;

--Body Part

CREATE OR REPLACE PACKAGE BODY emp_pkg

IS

PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id%TYPE) IS

v_salary employees.salary%TYPE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT salary,

first_name

INTO v_salary,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line('Salary of ' || v_first_name || ' is ' || v_salary);

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES
(1,

USER,

v_error,

systimestamp);

commit;

END emp_sal_sp;

PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id%TYPE) IS

v_hire_date DATE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT hire_date,

first_name

INTO v_hire_date,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line(v_first_name || ' hired on ' || to_char(v_hire_date,'month ddth,


yyyy'));

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES
(1,

USER,

v_error,

systimestamp);

commit;

END emp_hdt_sp;

FUNCTION sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER

IS

v_c NUMBER;

BEGIN

v_c := p_a + p_b;

RETURN v_c;

END;

END emp_pkg;

A package specification can exist without a package body, but

a package body can't exist without a package specification.

--Executing procedure inside the package


BEGIN

emp_pkg.emp_sal_sp(120);

END;

--Executing function inside the package

SELECT emp_pkg.sum_fn(23,567) FROM dual;

-- You can declare global variable,cursor, user define exeption

create or replace package all_detail

as

PROCEDURE emp2sal (a IN NUMBER);

PROCEDURE emp2exep (a IN NUMBER);

FUNCTION add2num (a IN NUMBER, b IN NUMBER)

RETURN NUMBER;

c NUMBER(8); --global declaration

abort_ex EXCEPTION; --global exception declaration

CURSOR emp_rec --global cursor declaration

IS
SELECT first_name, salary, hire_date, department_id

FROM employees;

End all_detail;

create or replace package body all_detail

as

PROCEDURE emp2sal (a IN NUMBER)

AS

BEGIN

SELECT salary

INTO c

FROM Employees

WHERE Employee_id = a;

Dbms_output.put_line('Salary of Employee ' || a || ' is ' || c);

EXCEPTION

WHEN no_data_found THEN

Dbms_output.put_line('Please enter valid id');

END emp2sal;
PROCEDURE emp2exep (a IN NUMBER)

AS

BEGIN

SELECT Round(Months_between(sysdate,hire_date)/12)

INTO c

FROM Employees

WHERE Employee_id = a;

Dbms_output.put_line( c || ' Years');

EXCEPTION

WHEN no_data_found THEN

Dbms_output.put_line('Please enter valid id');

END emp2exep;

FUNCTION add2num (a IN NUMBER, b IN NUMBER)

RETURN NUMBER

AS

BEGIN

c := a+b;

RETURN C;

END;

End all_detail;
/*Declaring a Bodiless Package */

CREATE OR REPLACE PACKAGE global_constant

IS

mile_2_kilo CONSTANT NUMBER := 1.6093;

kilo_2_mile CONSTANT NUMBER := 0.6214;

yard_2_meter CONSTANT NUMBER := 0.9144;

meter_2_yard CONSTANT NUMBER := 1.0936;

END global_constant;

BEGIN

DBMS_OUTPUT.PUT_LINE('20 miles = ' || 20*global_constant.mile_2_kilo||' km');

END;

/*Forward Declaration in package */

DECLARE

PROCEDURE P2; -- forward declaration

PROCEDURE P3;
PROCEDURE P1 IS

BEGIN

dbms_output.put_line('From procedure p1');

p2;

END P1;

PROCEDURE P2 IS

BEGIN

dbms_output.put_line('From procedure p2');

p3;

END P2;

PROCEDURE P3 IS

BEGIN

dbms_output.put_line('From procedure p3');

END P3;

BEGIN

p1;

END;

sample output:

From procedure p1

From procedure p2
From procedure p3

Drop package package_name;

Drop package body package_name;

SELECT text FROM user_source u

WHERE u.name = 'EMP_PKG';

Interview Questions:

What is package?

Advantage of package

Is it possible to create package body with out package specification?

what is package overloading?

what is forward declaration in package?

which data dictionary table contain source code of package?

How to declare global variable, exception and cursor?

How to execute procedure and function inside the package?

Posted 4th October 2014 by Unknown


0 Add a comment

OCT

%TYPE and %ROWTYPE

--%type is used to fetch the data type of the particular column

create table product_details

p_id NUMBER(3),

p_nm VARCHAR2(30),

p_qty NUMBER(8),

order_dt DATE

);

BEGIN

INSERT INTO product_details VALUES(100,'Name0',400,'23-Mar-13');

INSERT INTO product_details VALUES(101,'Name1',600,'26-Apr-13');

INSERT INTO product_details VALUES(102,'Name2',800,'27-Jan-12');

INSERT INTO product_details VALUES(103,'Name3',300,'23-Jul-11');


INSERT INTO product_details VALUES(104,'Name4',200,'22-Aug-11');

INSERT INTO product_details VALUES(105,'Name5',500,'25-Oct-12');

commit;

END;

SELECT * FROM product_details;

------------------------------------

P_ID P_NM P_QTY ORDER_DT

------------------------------------

100 Name0 400 03/23/2013

101 Name1 600 04/26/2013

102 Name2 800 01/27/2012

103 Name3 300 07/23/2011

104 Name4 200 08/22/2011

105 Name5 500 10/25/2012

------------------------------------

DECLARE

v_name VARCHAR2(4);

BEGIN

SELECT p_nm
INTO v_name

FROM product_details

WHERE p_id = 100;

dbms_output.put_line('Product Name : ' || v_name);

--error numeric or value error

END;

DECLARE

v_name VARCHAR2(5);

BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 100;

dbms_output.put_line('Product Name : ' || v_name);

END;

ALTER TABLE product_details

MODIFY p_nm VARCHAR2(15);

INSERT INTO product_details


VALUES

(106,

'name6',

700,

'26-Dec-12');

commit;

106 name6 700 12/26/2012

DECLARE

v_name VARCHAR2(5);

BEGIN

SELECT p_nm INTO v_name

FROM product_details

WHERE p_id = 106;

dbms_output.put_line('Product Name : ' || v_name);

--error

END;

/
DECLARE

v_name product_details.p_nm%TYPE;

BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 106;

dbms_output.put_line('Product Name : ' || v_name);

END;

DROP TABLE product_details;

DECLARE

dep_id departments.department_id%TYPE;

dep_name departments.department_name%TYPE;

dep_man_id departments.manager_id%TYPE;

dep_loc_id departments.location_id%TYPE;

BEGIN
SELECT department_id,

department_name,

manager_id,

location_id

INTO dep_id,

dep_name,

dep_man_id,

dep_loc_id

FROM departments

WHERE department_id = 10;

dbms_output.put_line('Department_id : ' || dep_id);

dbms_output.put_line('Department_name : ' || dep_name);

dbms_output.put_line('Manager_id : ' || dep_man_id);

dbms_output.put_line('Location_id : ' || dep_loc_id);

END;

--%rowtype is used to fetch the data type of all the column

--Insted of using %type if we use %rowtype means we can reduce the no of variables that we
declare
DECLARE

dep_detail departments%ROWTYPE;

BEGIN

SELECT *

INTO dep_detail

FROM departments

WHERE department_id = 10;

dbms_output.put_line('Department_id : ' || dep_detail.department_id);

dbms_output.put_line('Department_name : ' || dep_detail.department_name);

dbms_output.put_line('Manager_id : ' || dep_detail.manager_id);

dbms_output.put_line('Location_id : ' || dep_detail.location_id);

END;

DROP TABLE dept_details;

CREATE TABLE dept_details

dept_id number(3) ,

dept_name varchar2(30),

dept_manager_name varchar2(30)
);

insert into dept_details values(10,'dept1','manager_name1');

insert into dept_details values(20,'dept2','manager_name2');

SELECT * FROM dept_details;

-------------------------------------------------------

| DEPT_ID | DEPT_NAME | DEPT_MANAGER_NAME |

+------------+-----------------------+-----------------

| 10 | dept1 | manager_name1 |

| 20 | dept2 | manager_name2 |

------------+-----------------------+------------------

DECLARE

all_data dept_details%ROWTYPE;

BEGIN

all_data.dept_id := 100;

all_data.dept_name := 'Admin';

all_data.dept_manager_name := 'John';

UPDATE dept_details
SET ROW = all_data

WHERE dept_id = 10;

dbms_output.put_line(SQL%ROWCOUNT || ' Row(s) get updated');

END;

1 Row(s) get updated

select * from dept_details;

---------------------------------------------------

| DEPT_ID | DEPT_NAME | DEPT_MANAGER_NAME|

---------------------------------------------------

| 100 | Admin | John |

| 20 | dept2 | manager_name2 |

---------------------------------------------------

Interview Question :

1. What is the use of %TYPE?


2. What is the use of %ROWTYPE?

3. Difference between %TYPE and %ROWTYPE?

Posted 2nd October 2014 by Unknown

0 Add a comment

SEP

29

BULK Exceptions

/************************************************************************

* Handling Exceptions in Bulk Operations *

* Documented on 29-SEP-14 04.35.35.980894 PM +05:30 *

* Document By : Murugappan Annamalai *

* Reference : http://www.dba-oracle.com/plsql/t_plsql_exceptions.htm *

************************************************************************/

CREATE TABLE bulk_tb (ran_num NUMBER NOT NULL);


--inserting data using bulk collect

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

commit;

END;

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

200
TRUNCATE TABLE bulk_tb;

sample2.sql --without exception part

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));


commit;

END;

/*

Error Message :

ORA-01400: cannot insert NULL into ("HR"."bulk_tb"."ran_num")

ORA-06512: at line 15

*/

sample2.sql --with exception part

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;
/* will cause error while inserting data into bulk_tb

because of not null constraint */

BEGIN

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

COMMIT;

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('Error while inserting bulk record '||SQLERRM);

END;

END;

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

99

SQL%BULK_EXCEPTIONS(i).ERROR_INDEX
Holds the iteration (not the subscript) of the original FORALL statement that raised the
exception.

In sparsely populated collections,

the exception row must be found by looping through the original collection the correct
number of times.

SQL%BULK_EXCEPTIONS(i).ERROR_CODE

Holds the exceptions error code.

The total number of exceptions can be returned using the collections COUNT method,

which returns zero if no exceptions were raised. The save_exceptions.sql script,

a modified version of the handled_exception.sql script, demonstrates this functionality.

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

v_ex_count NUMBER(4);

abort_ex EXCEPTION;

PRAGMA EXCEPTION_INIT(abort_ex, -24381);

BEGIN

FOR i in 1..200

LOOP
v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

v_dat(150) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

EXECUTE IMMEDIATE 'TRUNCATE TABLE bulk_tb';

BEGIN

FORALL i IN v_dat.FIRST..v_dat.LAST SAVE EXCEPTIONS

INSERT INTO bulk_tb VALUES(v_dat(i));

COMMIT;

EXCEPTION

WHEN abort_ex THEN

v_ex_count := SQL%BULK_EXCEPTIONS.COUNT;

FOR i IN 1..v_ex_count LOOP

dbms_output.put_line('Error: ' || i ||' Array Index: ' || SQL


%BULK_EXCEPTIONS(i).error_index ||

' Message: ' || SQLERRM(SQL%BULK_EXCEPTIONS(i).ERROR_CODE));

END LOOP;

END;

END;
/*

Sample output:

Error: 1 Array Index: 100 Message: -1400: non-ORACLE exception

Error: 2 Array Index: 150 Message: -1400: non-ORACLE exception

*/

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

198

SAVE EXCEPTIONS clause being removed, in the above script now traps a different error number.

The output from this script is listed below.

/*

Sample output:
Error: 1 Array Index: 100 Message: -1400: non-ORACLE exception

*/

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

99

SELECT COUNT(*) FROM bulk_tb;

DROP TABLE bulk_tb;

Posted 29th September 2014 by Unknown

0 Add a comment

SEP

29

Cursor - FOR UPDATE


/************************************************************************

* FOR UPDATE clause in oracle *

* Document By : Murugappan Annamalai *

************************************************************************/

create table prod_details(p_id VARCHAR2(30), P_name VARCHAR2(30));

BEGIN

--Inserting data into prod_details table

FOR i IN 1..50 LOOP

INSERT INTO prod_details VALUES(i,'pname'||i);

END LOOP;

commit;

END;

SELECT * FROM prod_details;

DECLARE
CURSOR PROD_DTLS_C IS

SELECT * FROM PROD_DETAILS T1 FOR UPDATE OF P_ID;

V_PID PROD_DETAILS.P_ID%TYPE;

V_PRDNAME PROD_DETAILS.P_NAME%TYPE;

BEGIN

OPEN PROD_DTLS_C;

LOOP

FETCH PROD_DTLS_C INTO V_PID, V_PRDNAME;

IF PROD_DTLS_C%NOTFOUND THEN

EXIT;

ELSE

UPDATE PROD_DETAILS P

SET P.P_ID = LPAD(P_ID, 10, 0)

WHERE CURRENT OF PROD_DTLS_C;

END IF;

END LOOP;

CLOSE PROD_DTLS_C;

COMMIT;

END;
select * from PROD_DETAILS;

TRUNCATE TABLE prod_details;

BEGIN

--Inserting data into prod_details table

FOR i IN 1..50 LOOP

INSERT INTO prod_details VALUES(i,'pname'||i);

END LOOP;

commit;

END;

DECLARE

CURSOR PROD_DTLS_C IS

SELECT * FROM PROD_DETAILS T1 FOR UPDATE OF P_ID;

V_PID PROD_DETAILS.P_ID%TYPE;
V_PRDNAME PROD_DETAILS.P_NAME%TYPE;

BEGIN

OPEN PROD_DTLS_C;

LOOP

FETCH PROD_DTLS_C INTO V_PID, V_PRDNAME;

IF PROD_DTLS_C%NOTFOUND THEN

EXIT;

ELSE

UPDATE PROD_DETAILS P

SET P.P_ID = LPAD(P_ID, 10, 0)

WHERE CURRENT OF PROD_DTLS_C;

END IF;

COMMIT;

END LOOP;

CLOSE PROD_DTLS_C;

--COMMIT;

END;

select * from PROD_DETAILS;

Posted 29th September 2014 by Unknown


0 Add a comment

MAY

28

Escape Sequence in Oracle

Escape special characters when writing SQL queries

--to include single '

SELECT 'Steven's salary is more than 50k INR' AS "SAL_DETAILS"

FROM Dual;

ORA-01756 : quoted string not properly terminated

SELECT 'Steven''s salary is more than 50k INR' AS "SAL_DETAILS"

FROM Dual;

SAL_DETAILS

---------------------------------------

Steven's salary is more than 50k INR


--to include double '

SELECT 'You can print double quot ('''') in oracle' "Info"

FROM Dual;

Info

---------------------------------------

You can print double quot ('') in oracle

SELECT q'[some test ' some test ' some text ']' AS "In 10g"

FROM dual;

In 10g

------------------------------------

some test ' some test ' some text '

--Escape wild card characters ( _ and % )


The LIKE keyword allows for string searches.

The '_' wild card character is used to match exactly one character

While '%' is used to match zero or more occurrences of any characters.

These characters can be escaped in SQL as follows.

WITH mail_ids AS

SELECT 'an.murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an_murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an%murugappan@gmail.com' mail FROM Dual

SELECT * FROM mail_ids

WHERE mail LIKE '__$_%' ESCAPE '$';

mail

----------------------------------

an_murugappan@gmail.com

WITH mail_ids AS

SELECT 'an.murugappan@gmail.com' mail FROM Dual


UNION

SELECT 'an_murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an%murugappan@gmail.com' mail FROM Dual

SELECT * FROM mail_ids

WHERE mail LIKE '__/%%' ESCAPE '/';

mail

----------------------------------

an%murugappan@gmail.com

Escape ampersand (&) characters in SQL*Plus

SQL> select '&a' FROM dual;

'23'

----

23

SQL> SET ESCAPE '\'

SQL> select '\&a' FROM dual;


'&A'

----

&a

SQL> SET SCAN OFF;

SQL> select '&a' FROM dual;

'&A'

----

&a

SQL> SET SCAN ON;

SQL> select '&a' FROM dual;

'45'

----

45

Posted 28th May 2014 by Unknown

0 Add a comment
MAY

28

Data Manipulation Language

Data Manipulation Language (DML) statements are used for managing data within schema
objects. Some examples:

INSERT - insert data into a table

UPDATE - updates existing data within a table

DELETE - deletes all records from a table, the space for the records remain

MERGE - UPSERT operation (insert or update)

CREATE TABLE prod_details

prod_id NUMBER(4) ,

prod_name VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

Deliver_dt DATE DEFAULT SYSDATE+3 ,

comments VARCHAR2(300)

);

SELECT * FROM prod_details;


no_data_found

INSERT

INSERT INTO prod_details(prod_id,prod_name,order_dt,deliver_dt,comments)

VALUES(100,'Apple iphone 5s','21-May-14','24-May-14','Color : Black');

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

---------------------------------------------------------------------------

--Inserting records with out mentioning column name

INSERT INTO prod_details

VALUES(101,'Samsung Galaxy III','20-Aug-14','23-Aug-14','Color : White');

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------
100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

---------------------------------------------------------------------------

--Inserting selective number of values

INSERT INTO prod_details

VALUES(103,'Moto X','11-May-14','13-May-14');

ORA-00947 : not enough values

--While inserting selective number of values mentioning column name is compulsory.

INSERT INTO prod_details (prod_id,prod_name,order_dt,deliver_dt)

VALUES(103,'Moto X','11-May-14','13-May-14');

SELECT * FROM prod_details;

--------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

--------------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014


--------------------------------------------------------------------------------

--Inserting NULL value.

--If you want to insert NULL value you can ignore that column at the time of inserting

--or we can use NULL keyword to insert NULL.

INSERT INTO prod_details

VALUES(104,'Moto G','19-May-14','22-May-14',NULL);

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Noto G 5/19/2014 5/22/2014

---------------------------------------------------------------------------

--if you are not providing values for order_dt and deliver_dt column default value can be taken.

INSERT INTO prod_details(prod_id,prod_name,comments)

VALUES(105,'Nokia Lumis 720p','Color : Red');


SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

----------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Moto G 5/19/2014 5/22/2014

105 Nokia Lumis 720p 5/26/2014 5/29/2014 Color : Red

---------------------------------------------------------------------------

--Inserting data by using sub query

CREATE TABLE test_tab (id NUMBER, Name VARCHAR2(30));

INSERT INTO test_tab VALUES(1,'Name1');

INSERT INTO test_tab VALUES(2,'Name2');

INSERT INTO test_tab VALUES(3,'Name3');

SELECT COUNT(*) FROM test_tab;


COUNT(*)

-------

--creating table by using sub query (with out data)

CREATE TABLE ins_chk

SELECT * FROM test_tab

WHERE id = 900;

SELECT COUNT(*) FROM ins_chk;

COUNT(*)

-------

--Inserting data by using sub query

--copying data from test_tab to ins_chk

INSERT INTO ins_chk (SELECT * FROM test_tab);


3 rows inserted in 0.047 seconds.

SELECT COUNT(*) FROM ins_chk;

COUNT(*)

-------

DROP TABLE test_tab;

DROP TABLE ins_chk;

UPDATE

Syntax :

UPDATE table_name

SET column1_name = column1_value,

column2_name = column2_value,

column2_name = column3_value,

columnn_name = columnn_value

WHERE condition(s);
SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

----------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Moto G 5/19/2014 5/22/2014

105 Nokia Lumis 720p 5/26/2014 5/29/2014 Color : Red

---------------------------------------------------------------------------

UPDATE prod_details ps

SET ps.prod_name = 'iphone 5s'

WHERE ps.prod_id = 100;

1 row updated in 0.031 seconds

SELECT *

FROM prod_details ps

WHERE ps.prod_id = 100;

--------------------------------------------------------------------
PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

--------------------------------------------------------------------

100 iphone 5s 5/21/2014 5/24/2014 Color : Black

--------------------------------------------------------------------

--update statement with out condition

--If you try to execute update statement without condition it'll update all the records inside the
table.

UPDATE prod_details ps

SET ps.comments = 'None';

5 row updated in 0.031 seconds

SELECT *

FROM prod_details ps;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 None

101 Samsung Galaxy III 8/20/2014 8/23/2014 None

103 Moto X 5/11/2014 5/24/2014 None

104 Moto G 5/19/2014 5/22/2014 None

105 Nokia Lumis 720p 5/26/2014 5/29/2014 None

----------------------------------------------------------------------
--if your update text contain ' means you can use following metnod (use '')

UPDATE prod_details ps

SET ps.comments = 'Some product''s are not available'

WHERE ps.prod_id = 100;

1 row updated in 0.031 seconds

SELECT *

FROM prod_details ps

WHERE ps.prod_id = 100;

------------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

------------------------------------------------------------------------------------

100 iphone 5s 5/21/2014 5/24/2014 Some product's are not available

------------------------------------------------------------------------------------

DELETE

Syntax:
DELETE FROM table_name

WHERE condition(s);

DELETE FROM prod_details

WHERE prod_id IN (104, 105);

2 row(S) deleted in 0.032 seconds

SELECT *

FROM prod_details ps;

---------------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Some product's are not available

101 Samsung Galaxy III 8/20/2014 8/23/2014 None

103 Moto X 5/11/2014 5/24/2014 None

---------------------------------------------------------------------------------------

DELETE FROM prod_details;

3 row(s) deleted in 0.062 seconds.


SELECT * FROM prod_details;

no rows selected.

DROP TABLE prod_details;

MERGE = Insert + Update

-- will update soon.

Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Data Define Language

Data Definition Language (DDL) statements are used to define the database structure or schema.

Some examples:
CREATE - to create objects in the database.

ALTER - alters the structure of the database.

ADD

RENAME

MODIFY

DROP

DROP - delete objects from the database

TRUNCATE - remove all records from a table,

including all spaces allocated for the records are removed.

COMMENT - add comments to the data dictionary.

RENAME - rename an object.

Creating Table

--------------------------------------------------------------------------

Data Types Size Default Size Explanation

--------------------------------------------------------------------------

NUMBER(P,S) P: 1 to 38 we can store number between 0-9

S: -84 to 127

VARCHAR2 4000 Bytes we can store 0-9, a-z, A-Z and special characters

CHAR 2000 Bytes 1

DATE 7 Used to store Date

TIMESTAMP Includes year, month, day, hour, minute, and seconds.


LONG 2 GB Only one long column is allowed in a table.

We can't use this column in ORDER BY clause.

CLOB 4 GB Character Large Object

BLOB Binary Larger Object

--------------------------------------------------------------------------

CREATE

ALTER : ADD RENAME MODIFY DROP RENAME

RENAME

DROP

TRUNCATE

--creating table

CREATE TABLE friends_details_tb

Name VARCHAR2(30) ,

Phone NUMBER(10) ,

Gender CHAR ,

dob DATE ,

other_details LONG ,

make_dtm TIMESTAMP

);
DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

-----------------------------

--maximum you can keep 255 columns in a table

ALTER : Colum level operations

ADD RENAME MODIFY DROP

ADD : Used to add a column after the table hase been created

ALTER TABLE friends_details_tb

ADD email VARCHAR2(30);


DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

EMAIL VARCHAR2(30)

-----------------------------

--adding multiple columns by using single ALTER statement

SYNTAX

ALTER TABLE friends_details_tb

ADD (

column_1 Data_type(size),

column_2 Data_type(size),

column_3 Data_type(size),

column_4 Data_type(size)
);

RENAME : Used to Rename a column

ALTER TABLE friends_details_tb

RENAME COLUMN email TO email_id;

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------
MODIFY : Used to change the data type or size of the data type.

ALTER TABLE friends_details_tb

MODIFY other_details CLOB;

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS CLOB

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

--Modifying multiple columns at a time

ALTER TABLE friends_details_tb

MODIFY ( column_name_1 old_datatype(new_size),


column_name_2 new_datatype(old_size),

column_name_3 new_datatype(new_size)

);

DROP : Used to drop the column after the table has been created.

ALTER TABLE friends_details_tb

DROP COLUMN other_details;

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

RENAME : Used to Rename a particular table.


SYNTAX

RENAME old_table_name TO new_table_name;

RENAME friends_details_tb TO fnd_det;

DESCRIBE fnd_det;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

TRUNCATE : Used to remove the entire content of the table (not a structure)

SYNTAX

TRUNCATE TABLE table_name;


TRUNCATE TABLE fnd_det;

DROP : Used to drop the tabel (Data + stucture of the table get removed from the database )

DROP TABLE fnd_det;

*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Statements in Oracle

Data Definition Language (DDL)

DDL statements are used to define the database structure or schema. Some examples:
CREATE - to create objects in the database

ALTER - alters the structure of the database

ADD

RENAME

MODIFY

DROP

DROP - delete objects from the database

TRUNCATE - remove all records from a table,

including all spaces allocated for the records are removed

RENAME - rename an object

Data Manipulation Language (DML)

DML statements are used for managing data within schema objects. Some examples:

INSERT - insert data into a table

UPDATE - updates existing data within a table

DELETE - deletes all records from a table, the space for the records remain

MERGE - UPSERT operation (insert or update)

Data Control Language (DCL)

DCL statements. Some examples:


GRANT - gives users access privileges to database

REVOKE - withdraw access privileges given with the GRANT command

Transaction Control (TCL)

TCL statements are used to manage the changes made by DML statements. It allows
statements to be grouped together into logical transactions.

COMMIT - save work done

SAVEPOINT - identify a point in a transaction to which you can later roll back

ROLLBACK - restore database to original since the last COMMIT

Posted 28th May 2014 by Unknown

0 Add a comment

MAY

19

DECODE and CASE statement


CREATE TABLE students (

roll_no NUMBER(4) ,

Name VARCHAR2(30) ,

dept_cd VARCHAR2(20) ,

total_marks NUMBER(3)

);

BEGIN

INSERT INTO students VALUES (2000,'Rahul','CSE',480);

INSERT INTO students VALUES (2001,'Bala','IT', 390);

INSERT INTO students VALUES (2002,'Ramesh','CSE',250);

INSERT INTO students VALUES (2003,'Karthi','EEE',185);

INSERT INTO students VALUES (2004,'Ravi','IT',345);

END;

SELECT * FROM students;

DECODE

Decode is a function. Its a Oracle one.

Works like IF-THEN-ELSE.

You can use DECODE only in SELECT clause.

In DECODE you can include 255 things include Exep, search , result and default value.
Example

SELECT roll_no,

NAME,

dept_cd,

DECODE(dept_cd,

'CSE',

'Computer Science and Engineering',

'IT',

'Information Technology',

'Default Value') AS "DEPARTMENT NAME"

FROM students;

Sample Output

------------------------------------------------------------

ROLL_NO NAME DEPT_CD DEPARTMENT NAME

------------------------------------------------------------

2000 Rahul CSE Computer Science and Engineering

2001 Bala IT Information Technology

2002 Ramesh CSE Computer Science and Engineering

2003 Karthi EEE Default Value

2004 Ravi IT Information Technology

------------------------------------------------------------
CASE

CASE is an expression. Its a ANSI standard.

Compare to DECODE case will be more faster.

Example

SELECT roll_no,

NAME,

dept_cd,

total_marks,

CASE

WHEN total_marks > 500 THEN

'A Grade'

WHEN total_marks > 400 THEN

'B Grade'

WHEN total_marks > 300 THEN

'C Grade'

ELSE

'U Grade'

END AS "GRADE"

FROM students;

-----------------------------------------------

ROLL_NO NAME DEPT_CD TOTAL_MARKS GRADE

-----------------------------------------------
2000 Rahul CSE 480 B Grade

2001 Bala IT 390 C Grade

2002 Ramesh CSE 250 U Grade

2003 Karthi EEE 185 U Grade

2004 Ravi IT 345 C Grade

-----------------------------------------------

Interview Questions:

What is DECODE?

What is CASE?

Difference between CASE and DECODE? Which one is faster?

Posted 19th May 2014 by Unknown

0 Add a comment

MAY

19

Sub Query

Query with in another query

1. Single Row sub query


2. Multi row Sub query

select * from employees;

Want to fetch the person Who are all getting salary more than Neena's salary ?

Neena's Salary : 17000

Select First_name, salary

From Employees

Where salary > 17000;

--change in Neena's salary won't work for the above query.

Select salary From Employees

Where First_name = 'Neena';

Sub Query :

Select First_name, salary

From Employees

Where salary > (


Select salary From Employees

Where First_name = 'Neena'

);

Select * from employees;

Select salary From Employees

Where First_name = 'Alexander';

Sub Query Returns one value it is called as Single row sub query

Sub Query Returns more than one value it is called as Multi row sub query

Single row sub query operators :

> < >= <= = <>

Multiple Row Sub query operators :

IN ALL ANY
Who are all getting salary more than the average salary?

Select

First_name,

Salary

From

Employees

WHERE

Salary > (

SELECT Round(avg(salary),0)

FROM Employees

);

Multiple Row Sub query (In ANY ALL)

Select First_name,Department_id, salary

From Employees

Where salary in(

Select Salary From Employees

Where First_name = 'Alexander'

);

Any : Minimum Value will be taken (3100)


Select First_name,Department_id, salary

From Employees

Where salary > ANY(

Select Salary From Employees

Where First_name = 'Alexander'

);

All : Maximum Value will be taken (9000)

Select First_name,Department_id, salary

From Employees

Where salary > All(

Select Salary From Employees

Where First_name = 'Alexander'

);

We can use sub query in all the classes except Group by and order by class.

Select

From

Where

-----------Group by

having

-----------Order by
SELECT

( Select Count(*) from Employees Where Department_id = 90 )Executive,

( Select Count(*) from Employees Where Department_id = 60 ) IT,

( Select Count(*) from Employees Where Department_id = 10 ) Administration,

( Select Count(*) from Employees Where Department_id = 100) Finance

FROM

Dual;

Select Min(salary) From Employees;

Select Min(salary) from

Select * from Employees

Where Department_id = 60

);

What is INLINE VIEW?

If u use sub query in From it is call it is as INLINE VIEW.

Intermediate result set

Correlated sub query


SELECT employee_number, name

FROM employees Bob

WHERE salary > (

SELECT AVG(salary)

FROM employees

WHERE department = Bob.department

);

Posted 19th May 2014 by Unknown

0 Add a comment

Loading

Dynamic Views theme. Powered by Blogger.

Oracle sql & Pl/sql

search

Home Sql and pl/sql Sql Interview Questions

JUL

20
INLINE view in Oracle with 12c New Features

Named sub Query in FROM clause is call it as INLINE VIEW.

Oracle process a inline view faster than sub query

Inline View in Oracle

--Query to display all the employees who are all getting salary more than their department
average salary

SELECT First_name

, last_name

, salary

, department_id

FROM employees a , ( SELECT b.department_id

, AVG(b.salary) avg_sal

FROM employees b

GROUP BY b.department_id

)b

WHERE a.department_id = b.department_id

AND a.salary > b.avg_salary;

Display all the customer who have placed more number of orders by using INLINE view
CREATE TABLE customer_order_det_tb

( custm_id NUMBER ,

custm_nm VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

ttl_amt NUMBER(7,2)

);

BEGIN

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '11-Jul-15' , 45000.00);

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '14-Jul-15' , 27000.00);

INSERT INTO customer_order_det_tb VALUES(101, 'Raja' , '13-Jul-15' , 17000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 34000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 38000.00);

COMMIT;

END;

SELECT c.*

FROM customer_order_det_tb c;

--------------------------------------------

custm_id custm_nm order_dt ttl_amt

--------------------------------------------

100 Murugappan 7/11/2015 45000.00

100 Murugappan 7/14/2015 27000.00

101 Raja 7/13/2015 17000.00


102 Ramesh 7/15/2015 34000.00

102 Ramesh 7/15/2015 38000.00

--------------------------------------------

--Writing a Quer to display all the customer who have placed maximum number of order

--Query #1 for inline view

SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC;

--------------------------------

custm_id custm_nm total_odr

--------------------------------

100 Murugappan 2

102 Ramesh 2

101 Raja 1

--------------------------------

--Query #2 for inline view

SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt


GROUP BY cnt.custm_id, cnt.custm_nm;

----------

total_odr

----------

----------

Inline view to find all the customers who have placed maximum number of orders

/****************************************

Syntax

SELECT * FROM <query1> x, <query2> y

WHERE contition;

****************************************/

SELECT query1.* FROM

( SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC

) query1,

( SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt


GROUP BY cnt.custm_id, cnt.custm_nm

) query2

WHERE query1.total_odr = query2.total_odr;

-------------------------------

custm_id custm_nm total_odr

-------------------------------

100 Murugappan 2

102 Ramesh 2

-------------------------------

DROP TABLE customer_order_det_tb;

--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT

SELECT first_name, salary

FROM ( SELECT first_name, salary

FROM employees e

WHERE job_id NOT IN ('SALESMAN','PRESIDENT')

ORDER BY salary DESC

WHERE ROWNUM < 4;


New Oracle 12c Inline view Syntax

LATERAL clause for In-line views

Allows for columns in the inline view to be accessed!!

Example :

--in 11g

SELECT * FROM employees e, (

SELECT *

FROM departments d

WHERE e.department_id = d.department_id);

ORA-0090: "E"."DEPARTMENT_ID": Invalid Identifier

--in 12c

SELECT * FROM employees e, LATERAL(

SELECT *

FROM departments d

WHERE e.department_id = d.department_id

);
--in 11g

WITH t

AS

( SELECT LEVEL a

FROM dual

CONNECT BY LEVEL <= 30)

SELECT *

FROM t, (SELECT *

FROM employees

WHERE department_id = t.a

);

ORA-00904: "T"."A": invalid Identifier

--in 12c

WITH t

AS

(SELECT LEVEL a FROM dual CONNECT BY LEVEL <= 30)

SELECT * FROM t,

LATERAL(SELECT *

FROM employees

WHERE department_id = t.a);

Hope you have enjoyed this little article


Feed backs are always Welcome :) (:

Posted 20th July 2015 by Unknown

0 Add a comment

JAN

23

Salary Related Questions in Oracle

--creating table

CREATE TABLE employee_data

eid NUMBER(4),

ename VARCHAR2(30),

depno NUMBER(3),

salary NUMBER(8)

);

BEGIN
--Inserting records

INSERT INTO employee_data VALUES(1000,'Name01',90,30000);

INSERT INTO employee_data VALUES(1001,'Name02',90,6000);

INSERT INTO employee_data VALUES(1002,'Name03',90,23000);

INSERT INTO employee_data VALUES(1003,'Name04',60,35000);

INSERT INTO employee_data VALUES(1004,'Name05',60,60000);

INSERT INTO employee_data VALUES(1005,'Name06',60,30000);

INSERT INTO employee_data VALUES(1006,'Name07',80,36000);

INSERT INTO employee_data VALUES(1007,'Name08',80,29000);

INSERT INTO employee_data VALUES(1008,'Name09',80,37000);

INSERT INTO employee_data VALUES(1009,'Name10',80,41000);

COMMIT;

END;

SELECT * FROM employee_data

ORDER BY salary DESC;

--query to find maximum salary from employee_data table

SELECT MAX(salary) FROM employee_data;

--query to find minimum salary from employee_data table


SELECT MIN(salary) FROM employee_data;

--query to find second maximum salary from employee_data table

SELECT MAX(salary)

FROM employee_data

WHERE salary NOT IN (SELECT MAX(salary)

FROM employee_data);

--query to select 5th maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= 5);

--query to select nth maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data
ORDER BY salary DESC)

WHERE rownum <= &n);

--query to select all the details of the employee whose getting nth maximum salary

SELECT *

FROM (SELECT emp.*,

rownum rn

FROM (SELECT *

FROM employee_data

ORDER BY salary DESC) emp)

WHERE rn = 9;

--same query using row_numbr( ) function

SELECT *

FROM (SELECT emp.*,

row_number() over(ORDER BY salary) rank

FROM employee_data emp)

WHERE rank = 9;

--same query using rank( ) function

SELECT *
FROM (SELECT emp.*,

rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--same query using dense_rank( ) function

SELECT *

FROM (SELECT emp.*,

dense_rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--query to display display maximum salary in all the department

SELECT e.depno "Department id",

MAX(salary) "Maximum Salary"

FROM employee_data e

GROUP BY e.depno;

--query to display all the employees who are all getting salary more than average salary of the
company

SELECT e.* FROM employee_data e

WHERE salary > (SELECT AVG(salary) FROM employee_data);


--query to display all the employees who are all getting salary more than their department
average salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE department_id = OUT.department_id);

--query to display all the employees who are all getting salary more than their manager salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE employee_id = OUT.manager_id);


Documented By : Murugappan Annamalai

Posted on : 23-Jan-15 16:34:00 IST.

Hope you have enjoyed this little article

Feed backs are always welcome :)

Posted 23rd January 2015 by Unknown

7 View comments

JAN

22

Why prefer COALESCE over NVL

Documented By : Nimish Garg

I prefer using "COALESCE" over "NVL" is some of the scenarios. Last week One of my friend
asked me what is the advantage of using "COALESCE" where we can simply use "NVL". I simply
gave him the reply from Oracle Docs i.e. NVL lets you replace null (returned as a blank) with a
string in the results of a query and COALESCE returns the first non-null expr in the expression list.
Oracle Database uses short-circuit evaluation with "COALESCE".

He replied that he knows the difference, he knows that "COALESCE" can take multiple arguments
and so on. He was more interested in understanding "short-circuit evaluation" of "COALESCE"
and the scenarios where I prefer using "COALESCE" over "NVL".
To make him understand I created following function which takes One second in every execution
and simply returns '--null--' and executed 2 very similar queries one with NVL and other with
COALESCE.

SQL> create or replace function f_null return varchar2

2 is

3 begin

4 dbms_lock.sleep(1);

5 return '--null--';

6 end;

7 /

Function created.

Following are the queries which I used to demonstrate that NVL evaluates both arguments even
if the second argument is not used and COALESCE uses short-circuit evaluation i.e. it only
evaluates the arguments only if they are needed.

SQL> select e.empno, e.ename ename, nvl(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES


7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.

Elapsed: 00:00:14.01

SQL> select e.empno, e.ename ename, coalesce(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES


7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.

Elapsed: 00:00:01.01

Here we can see easily that the first query with NVL took 14+ seconds, one second for each
record even if the "f_null" value was used only in one record. On the contrary as mentioned in
Oracle Documentation "COALESCE" uses its "short-circuit evaluation" and "f_null" was called
only once and so second query took only One Second. "COALESCE" is certainly use less resources
than NVL.

Posted 22nd January 2015 by Unknown

0 Add a comment
DEC

21

Constraints

It Enforce Rule On Table

We can create constraint at the time of Creating Table

1. Column Level Declaration

2. Table Level Declaration

1. We can provide own name.

Format : [part_of_project_name-table_name-column_name-constraint_type]

Example : gmind_emp_id_pk _uk _ck _f

2. system name name

Format : sys_cn

Example : SYS_C405323
We can create constraint after the table has been created

Types

Primary Key

Not allowed Null value

Not allowed you to enter duplicate value

Ex : Employee_id, Student_id

Unique Key

allowed Null value

Not allowed you to enter duplicate value

Ex : Contact_no, email

Foreign Key

It will allowed you to enter NULL and Duplicate value.

c1(pk) : 1 2 3

c2(f) : 1 1 2 3 4 Not allowed


Allowed you to enter duplicate value and null value

Not Null

It will not allowed you to enter null value

Check

You can check your own condition

Simple Table for understanding

------------------------------------

Duplicate NULL

------------------------------------

Primary Key X X

Unique Key X Allowed

Foreign Key Allowed Allowed

------------------------------------

creating table with all constraint type


Create table my_stu_details

S_id Number(2),

S_name Varchar2(30) Not Null, --SYS_Cn

s_mail Varchar2(30),

s_gender char(1),

s_did Number(3),

Constraint my_stu_sid_pk PRIMARY KEY (s_id),

constraint my_stu_mail_uk UNIQUE (s_mail) ,

Constraint my_stu_gen_ck CHECK (s_gender IN ('M', 'F', 'm', 'f')),

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

);

DESC my_stu_details;

------------------------------------

Name Type Nullable

------------------------------------

S_ID NUMBER(2)

S_NAME VARCHAR2(30)

S_MAIL VARCHAR2(30) Y

S_GENDER CHAR(1) Y
S_DID NUMBER(3) Y

------------------------------------

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name1' , 'name1@gmail.com' , 'm' , 60 );

Select * from my_stu_details;

Validating Primary Key

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-00001: unique constraint (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (NULL, 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-01400: cannot insert NULL into (HR.MY_STU_SID_PK) violated


Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (2 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

Validating NOT NULL Constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , NULL , 'name3@gmail.com' , 'F' , 80 );

ORA-01400: cannot insert NULL into ("HR"."MY_STU_DETAILS"."S_NAME")

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , 'Name3' , 'name3@gmail.com' , 'F' , 80 );

Select * from my_stu_details;

Validating Unique Key Constraint


--Duplicate Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , 'name3@gmail.com' , 'F' , 80 );

ORA-00001: unique constraint (HR.MY_STU_MAIL_UK) violated

--Null Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , null , 'M' , 70 );

Select * from my_stu_details;

Validating Check constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'j' , 70 );


ORA-02290: check constraint (HR.MY_STU_GEN_CK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'M' , 70 );

Select * from my_stu_details;

Validating Foreign Key

Select * from Departments;

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 3 );

ORA-02291: integrity constraint (HR.MY_STU_DID_FK) violated - parent key not found

Departments table : parent table

my_stu_details : Child table


Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

--------------------------------------------------------

s_id s_name s_mail s_gender s_did

--------------------------------------------------------

1 name1 name1@gmail.com m 60

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 M 70

5 Name5 name5@gmail.com M 70

6 Name6 name6@gmail.com F 90

--------------------------------------------------------

Deleting the Primary key value which is referred by Foreign Key

Select * from Departments;


DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID

------------------------------------------------------------

60 IT 103 1400 <---- Delete

-- don't execute this query

--Delete From Departments

--Where Department_id = 60;

1) ON DELETE SET NULL

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

1 name1 name1@gmail.com m -

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

2) ON DELETE SET CASCADE


-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

Syntax

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE CASCADE

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE SET NULL

Constraint Related Data Dictionary Table information.

To view constraint Information

SELECT c.owner,
c.constraint_name,

c.constraint_type,

c.table_name,

c.r_constraint_name,

c.status

FROM user_constraints c

WHERE c.table_name = 'MY_STU_DETAILS';

------------------------------------------------------------------------------------

owner constraint_name constraint_type table_name r_constraint_name status

------------------------------------------------------------------------------------

HR SYS_C004023 C MY_STU_DETAILS ENABLED

HR MY_STU_GEN_CK C MY_STU_DETAILS ENABLED

HR MY_STU_SID_PK P MY_STU_DETAILS ENABLED

HR MY_STU_MAIL_UK U MY_STU_DETAILS ENABLED

HR MY_STU_DID_FK R MY_STU_DETAILS DEPT_ID_PK ENABLED

------------------------------------------------------------------------------------

To view constraint name with corresponding column name

SELECT * FROM user_cons_columns c

WHERE c.table_name = 'MY_STU_DETAILS';


-------------------------------------------------------------

owner constraint_name table_name column_name position

-------------------------------------------------------------

HR MY_STU_MAIL_UK MY_STU_DETAILS S_MAIL 1

HR MY_STU_SID_PK MY_STU_DETAILS S_ID 1

HR MY_STU_GEN_CK MY_STU_DETAILS S_GENDER

HR SYS_C004023 MY_STU_DETAILS S_NAME

HR MY_STU_DID_FK MY_STU_DETAILS S_DID 1

-------------------------------------------------------------

Creating Composite Primary Key

Creating Primary Key with more than one number of column

ALTER TABLE table_name

ADD CONSTRAINT constraint_name PRIMARY KEY(column1, column_2 , column3);

In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.

creating constraint after the table creation


ALTER TABLE table_name

ADD CONSTRAINT constraint_name CONSTRAINT_TYPE(column_name);

ALTER TABLE table_name

DROP CONSTRAINT constraint_name;

ALTER TABLE table_name

DROP PRIMARY KEY;

To drop related foreign key

ALTER TABLE table_name

DROP PRIMARY KEY CASCADE;

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name;

Disable constraint with related foreign key constraint

ALTER TABLE table_name


DISABLE CONSTRAINT constraint_name CASCADE;

ALTER TABLE table_name

ENABLE CONSTRAINT constraint_name;

Interview Questions

What are all the type of constraint available in oracle?

Difference between PRIMARY KEY and UNIQUE key.

Difference between PRIMARY KEY ans FOREIGN KEY.

Difference between UNIQUE key and FOREIGN KEY.

Is it possible to create tow primary key in single table.

Write a syntax to create FOREIGN constraint.

How to create constraint after the table has been created?

How to enable and disable a constraint.

Which data dictionary table contains information about constraints?

Which Data Dictionary table contains information about constraint with corresponding column
name?

What is composite primary key?

Explain ON DELETE CASCADE and ON DELETE SET NULL option.

~Thanks For Reading~


Post your valuable feedback below

Posted 21st December 2014 by Unknown

1 View comments

UnknownMay 22, 2017 at 12:39 AM

good

Reply

DEC

listagg in Oracle 11g

Oracle 11gR2 listagg built-in function allows for many table columns to be displayed within a
single row, a non-first-normal form display

Syntax :

listagg(column_value,'delimiter') WITHIN GROUP(ORDER BY column_name)


--Example 1:

CREATE TABLE test_ins(empid NUMBER,product VARCHAR2(30));

BEGIN

INSERT INTO test_ins VALUES( 101,'pendrive');

INSERT INTO test_ins VALUES( 102,'toy');

INSERT INTO test_ins VALUES( 101,'ipod');

INSERT INTO test_ins VALUES( 102,'hat');

INSERT INTO test_ins VALUES( 103,'cpu');

INSERT INTO test_ins VALUES( 104,'pen');

INSERT INTO test_ins VALUES( 104,'car');

INSERT INTO test_ins VALUES( 104,'mat');

INSERT INTO test_ins VALUES( 105,'tv');

INSERT INTO test_ins VALUES( 106,'laptop');

commit;

END;

SELECT * FROM test_ins;

SELECT empid "Employee",

listagg(product,

',') within

GROUP (ORDER BY empid) "Products"

FROM test_ins
GROUP BY empid;

-->-- Result set --<--

DROP TABLE test_ins;

-->-- Example 2

select department_id "Department id", listagg(first_name,', ') WITHIN GROUP(ORDER BY


employee_id) "Employees"

FROM employees

WHERE department_id IN (10,20,30,60)

GROUP BY department_id;
-->-- Result set --<--

Posted 4th December 2014 by Unknown

0 Add a comment

NOV

Condition and Looping Statement

IF

IF ELSE

Multiple IF ELSE

LOOP

FOR LOOP

WHILE LOOP
create table test_udt(id NUMBER, salary NUMBER);

BEGIN

INSERT INTO test_udt VALUES(001,23000);

INSERT INTO test_udt VALUES(002,43000);

INSERT INTO test_udt VALUES(003,78000);

INSERT INTO test_udt VALUES(004,25000);

INSERT INTO test_udt VALUES(005,26000);

INSERT INTO test_udt VALUES(006,90000);

Commit;

END;

select * from test_udt;

IF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt
WHERE id = 1;

IF v_salary > 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

END IF;

commit;

END;

IF ELSE

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

UPDATE test_udt t
SET t.salary = v_salary+10005

WHERE t.id = v_id ;

ELSE

UPDATE test_udt t

SET t.salary = v_salary+20007

WHERE t.id = v_id ;

END IF;

commit;

END;

--same example with less number of lines

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

v_salary := v_salary+10005;
ELSE

v_salary := v_salary+20007;

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

Multiple IF ELSIF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 3;
IF v_id = 1 THEN

v_salary := 1000;

dbms_output.put_line('1 inside');

ELSIF v_id = 2 THEN

v_salary := 2000;

dbms_output.put_line('2 inside');

ELSIF v_id = 3 THEN

v_salary := 3000;

dbms_output.put_line('3 inside');

ELSIF v_id = 4 THEN

v_salary := 4000;

dbms_output.put_line('4 inside');

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

LOOP
--syntax

LOOP

--statements

--increment

--exit statement

END LOOP;

CREATE TABLE prod_details (pid VARCHAR2(3), pname VARCHAR2(30));

DECLARE

i NUMBER := 1;

x VARCHAR2(3);

BEGIN

LOOP

x := lpad(i,3,'0');

dbms_output.put_line('x value : '|| x);

INSERT INTO prod_details VALUES(i, 'Product '||i);

EXIT WHEN i >900;

i := i+1;

IF MOD(i,100) = 0 THEN

commit;
dbms_output.put_line('commit executed');

END IF;

END LOOP;

END;

SELECT * FROM prod_details ORDER BY 1;

DROP TABLE prod_details;

FOR LOOP

BEGIN

FOR I in 1..5

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

FOR LOOP - Reverse

BEGIN

FOR I in REVERSE 14..50

LOOP
Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

WHILE LOOP

DECLARE

i_val NUMBER:=0;

BEGIN

WHILE (i_val < 11)

LOOP

dbms_output.put_line('The value of I is '||i_val);

i_val := i_val + 1;

END LOOP;

END;

sample output:

The value of I is 0

The value of I is 1

The value of I is 2

The value of I is 3

The value of I is 4
The value of I is 5

The value of I is 6

The value of I is 7

The value of I is 8

The value of I is 9

The value of I is 10

Posted 8th November 2014 by Unknown

0 Add a comment

OCT

21

Bulk Collect

This is used for array fetches

With this you can retrieve multiple rows of data with a single round trip.

This reduces the number of context switches between the pl/sql and sql engines.

You can use bulk collect in both dynamic and static sql.

You can use bulk collect in select, fetch into and returning into clauses.

SQL engine automatically initializes and extends the collections you reference in the bulk
collect clause.

You can fetch into multiple collections with one column each.

You can use the limit clause of bulk collect to restrict the no of rows retrieved.
SELECT * FROM product_details;

-->-- Bulk collect in FETCH INTO --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

/
-->-- Bulk collect in SELECT clause --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

BEGIN

SELECT * BULK COLLECT INTO dta FROM product_details;

FOR i IN dta.FIRST .. dta.LAST LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- LIMIT in Bulk collect --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT


INTO dta LIMIT 30;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Multiple fetches in INTO clause --<--

SELECT * FROM product_details;

DECLARE

TYPE alldata_typ1 IS TABLE OF product_details.p_id%TYPE;

TYPE alldata_typ2 IS TABLE OF product_details.p_name%TYPE;

dta1 alldata_typ1;

dta2 alldata_typ2;

CURSOR proddt_cur IS

SELECT p_id, p_name FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT


INTO dta1, dta2;

CLOSE proddt_cur;

FOR i IN dta1.FIRST .. dta1.COUNT LOOP

dbms_output.put_line('Department Id : ' || dta1(i));

END LOOP;

FOR i IN dta2.FIRST .. dta2.COUNT LOOP

dbms_output.put_line('Department Name : ' || dta2(i));

END LOOP;

END;

DROP TABLE dep_details;

DROP TABLE product_details;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Ref Cursor
This is unconstrained cursor which will return different types depends upon the user input.

Ref cursors cannot be closed implicitly.

Ref cursor with return type is called strong cursor.

Ref cursor without return type is called weak cursor.

You can declare ref cursor type in package spec as well as body.

You can declare ref cursor types in local subprograms or anonymous blocks.

CREATE OR REPLACE PROCEDURE ref_c_sp(dep_det_c IN OUT SYS_REFCURSOR)

AS

BEGIN

OPEN dep_det_c

FOR

SELECT * FROM dep_details d;

END;

DECLARE

dep_det_c SYS_REFCURSOR;

tab_data dep_details%ROWTYPE;

BEGIN

ref_c_sp(dep_det_c);
LOOP

FETCH dep_det_c INTO tab_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department Name : '|| tab_data.d_name);

END LOOP;

CLOSE dep_det_c;

END;

/*sample output*/

Department Name : Admin

Department Name : HR

Department Name : Sales

Department Name : Marketing

DROP PROCEDURE ref_c_sp;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT
21

Cursor

SQL Private work Area where the query get passed and executed.

Types

******

Implicit(SQL)

Explicit

-->-- advanced cursor types --<--

Parametrized Cursor

Ref Cursor

Implicit

********

ORACLE implicitly opens a cursor to process each SQL statement not associated with an
explicitly declared cursor.

PL/SQL lets you refer to the most recent implicit cursor as the SQL” cursor. So, although you
cannot use the OPEN,

FETCH, and CLOSE statements to control an implicit cursor, you can still use cursor attributes to
access information

about the most recently executed SQL statement.


Cursor Stages

**************

OPEN cursor_name

FETCH (with in loop)

CLOSE cursor_name

Explicit

The set of rows returned by a query can consist of zero, one, or multiple rows,

depending on how many rows meet your search criteria. When a query returns multiple rows,

you can explicitly define a cursor to process the rows. You use three commands to control the
cursor

Cursor Attributes

*****************

%FOUND

%NOTFOUND

%ISOPEN

%ROWCOUNT

%BULK_ROWCOUNT --<-- used to handle error while using bulk collection.

%BULK_EXCEPTIONS --<-- used to handle error while using bulk collection.

Cursor Declaration
DECLARE

CURSOR <cursor_name>

IS

<SELECT statement>

BEGIN

--> some stmt

END;

Cursor Loop

Loop

While Loop

For Loop

Cursor Clauses

Return

For update

Where current of

Bulk collect

-->-- creating table

create table product_details

p_id NUMBER,
p_name VARCHAR2(30),

p_order_dt DATE

);

-->-- Inserting data

BEGIN

FOR i IN 1 .. 75 LOOP

INSERT INTO product_details VALUES (i, 'prod_name_' || i, SYSDATE + i);

END LOOP;

commit;

END;

-->-- selecting data

SELECT * FROM product_details;

---------------------------------------------

p_id p_name p_order_dt

---------------------------------------------

1 prod_name_1 10/11/2014 3:48:32 PM

2 prod_name_2 10/12/2014 3:48:32 PM

3 prod_name_3 10/13/2014 3:48:32 PM


4 prod_name_4 10/14/2014 3:48:32 PM

5 prod_name_5 10/15/2014 3:48:32 PM

6 prod_name_6 10/16/2014 3:48:32 PM

7 prod_name_7 10/17/2014 3:48:32 PM

8 prod_name_8 10/18/2014 3:48:32 PM

9 prod_name_9 10/19/2014 3:48:32 PM

10 prod_name_10 10/20/2014 3:48:32 PM

11 prod_name_11 10/21/2014 3:48:32 PM

12 prod_name_12 10/22/2014 3:48:32 PM

13 prod_name_13 10/23/2014 3:48:32 PM

14 prod_name_14 10/24/2014 3:48:32 PM

15 prod_name_15 10/25/2014 3:48:32 PM

16 prod_name_16 10/26/2014 3:48:32 PM

17 prod_name_17 10/27/2014 3:48:32 PM

18 prod_name_18 10/28/2014 3:48:32 PM

19 prod_name_19 10/29/2014 3:48:32 PM

20 prod_name_20 10/30/2014 3:48:32 PM

---------------------------------------------

----------------------------------------------

Implicit Cursor

----------------------------------------------

--will update soon


----------------------------------------------

Explicit Cursor

----------------------------------------------

**********************************************

Processing cursor data by using LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND; --<-- if next record not found means control will
come out from the loop

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;
CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

dbms_output.put_line('Product id : ' || all_data.p_id ||


' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

EXIT WHEN prod_detail_cur%FOUND; --<-- if next record found means control will come
out from the loop

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;
EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor Already closed


DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

-->-- CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');


ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor closed

**********************************************

Processing cursor data by using WHILE LOOP

**********************************************

DECLARE
all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

OPEN prod_detail_cur;

FETCH prod_detail_cur

INTO all_data;

WHILE prod_detail_cur%FOUND LOOP

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

FETCH prod_detail_cur

INTO all_data;

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )


Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

************************************************************

Processing cursor data by using FOR LOOP - CURSOR FOR LOOP

************************************************************

DECLARE

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

FOR i IN prod_detail_cur

LOOP

dbms_output.put_line('Product id : ' || i.p_id ||

' Product Name : ' || i.p_name ||

' ( Orderd on : ' || TRIM(i.p_order_dt) || ' )');

END LOOP;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )


Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

Parameterized Cursor

*********************

This was used when you are going to use the cursor in more than one place with different
values for the same where clause.

Cursor parameters must be in mode.

Cursor parameters may have default values.

The scope of cursor parameter is within the select statement.

CREATE TABLE dep_details(d_id NUMBER,d_name VARCHAR2(30), location_id NUMBER);

BEGIN

INSRT INTO dep_details VALUES(001,'Admin',1010);

INSRT INTO dep_details VALUES(002,'HR',1010);

INSRT INTO dep_details VALUES(003,'Sales',1020);

INSRT INTO dep_details VALUES(004,'Marketing',1020);

commit;

END;
SELECT * FROM dep_details;

----------------------------

d_id d_name location_id

----------------------------

1 Admin 1010

2 HR 1010

3 Sales 1020

4 Marketing 1020

----------------------------

DECLARE

-->--Declaring parameterized cursor

CURSOR dep_det_c(p_location_id NUMBER) IS

SELECT * FROM dep_details d WHERE d.location_id = p_location_id;

all_data dep_details%ROWTYPE;

BEGIN

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

OPEN dep_det_c(1010);

LOOP

FETCH dep_det_c

INTO all_data;
EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

-->-- opening same cursor with different input value

OPEN dep_det_c(1020);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

END;

/*sample output*/
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 1 Department Name : Admin

Department id : 2 Department Name : HR

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 3 Department Name : Sales

Department id : 4 Department Name : Marketing

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Handling Exception

Error Handling in oracle

ERROR

Any departure from the expected behavior of the system or program,

which stops the working of the system is an error.

Types : compile time error

Run time error


EXCEPTION

Any error or problem which one can handle and continue to work normally.

Handling Exception

When exception is raised, control passes to the exception section of the block.

i.e. EXCEPTION

WHEN name_of_exception THEN

Types : Pre Defined Exceptions

User Defined Exceptions

Predefined Exception

*********************

Oracle has predefined several exceptions that correspond to the most common oracle errors.

------------------------------------------------------------------------

Exception Oracle Error SQL Code Value

------------------------------------------------------------------------

ZERO_DIVIDE ORA-01476 -1476

NO_DATA_FOUND ORA-01403 +100

DUP_VAL_ON_INDEX ORA-00001 -1
TOO_MANY_ROWS ORA-01422 -1422

VALUE_ERROR ORA-06502 -6502

CURSOR_ALREADY_OPEN ORA-06511 -6511

OTHERS

------------------------------------------------------------------------

-->-- ZERO_DIVIDE --<--

Your program attempts to divide a number by zero.

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN ZERO_DIVIDE THEN

dbms_output.put_line('Divisor is equal to zero');

END;

-->-- NO_DATA_FOUND --<--

Single row SELECT returned no rows or your program referenced a deleted element in a nested
table

or an uninitialized element in an associative array (index-by table).


CREATE TABLE test_tb(id NUMBER PRIMARY KEY);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN NO_DATA_FOUND THEN

dbms_output.put_line('There is no data inside the table');

END;

-->-- DUP_VAL_ON_INDEX --<--

A program attempted to insert duplicate values in a column that is constrained by a unique


index.

INSERT INTO test_tb VALUES (1);

INSERT INTO test_tb VALUES (2);

commit;

BEGIN

INSERT INTO test_tb VALUES (2);


EXCEPTION

WHEN DUP_VAL_ON_INDEX THEN

dbms_output.put_line('Duplicate values are not allowed');

END;

-->-- TOO_MANY_ROWS --<--

Single row SELECT returned multiple rows.

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN TOO_MANY_ROWS THEN

dbms_output.put_line('Query returning more than one row');

END;

DROP TABLE test_tb;

-->-- VALUE_ERROR --<--


An arithmetic, conversion, truncation, or size constraint error occurred.

DECLARE

num1 NUMBER(2);

BEGIN

num1 := 345;

EXCEPTION

WHEN VALUE_ERROR THEN

dbms_output.put_line('check the size of the variable');

END;

-->-- CURSOR_ALREADY_OPEN --<--

A program attempted to open an already opened cursor.

CREATE TABLE emp(id NUMBER, name VARCHAR2(30));

BEGIN

INSERT INTO emp VALUES(1,'Name1');

INSERT INTO emp VALUES(2,'Name2');

INSERT INTO emp VALUES(3,'Name3');

INSERT INTO emp VALUES(4,'Name4');

COMMIT;
END;

SELECT * FROM emp;

DECLARE

cursor emp_c IS

SELECT * FROM emp;

all_data emp%ROWTYPE;

BEGIN

OPEN emp_c;

OPEN emp_c;

NULL;

CLOSE emp_c;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

END;

DROP TABLE emp;

-->-- OTHERS --<--

DECLARE
v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

WHEN OTHERS THEN

dbms_output.put_line('Some other error ' || SQLERRM);

END;

User Defined Exception

**********************

A user-defined exception is an error that is defined by the programmer.

User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,

exceptions have a type EXCEPTION and scope.

DECLARE

v_gender CHAR := '&gender';

gender_ex EXCEPTION;

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN


RAISE gender_ex;

END IF;

dbms_output.put_line('Gender : '||v_gender);

EXCEPTION

WHEN gender_ex THEN

dbms_output.put_line('Please Enter valid gender');

END;

create table test_insert (id NUMBER, Name VARCHAR2(30));

DECLARE

abort_ex EXCEPTION;

BEGIN

FOR i IN 1..100

LOOP

BEGIN

IF mod(i,10)=0 THEN

RAISE abort_ex;

END IF;

INSERT INTO test_insert VALUES(i, 'Name'||i);

EXCEPTION

WHEN abort_ex THEN

NULL;

END;
END LOOP;

COMMIT;

END;

SELECT * FROM test_insert;

DROP TABLE test_insert;

SQLERRM and SQLCODE

********************

SQLCODE returns the current error code, and SQLERRM returns the current error message
text;

For user-defined exception SQLCODE returns 1 and SQLERRM returns “user-defined


exception”.

SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.

CREATE TABLE test_tb (id NUMBER);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

dbms_output.put_line(v_id);
EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('SQLERRM : ' || SQLERRM);

dbms_output.put_line('SQLCODE : ' || SQLCODE);

END;

/*sample output*/

SQLERRM : ORA-01403: no data found

SQLCODE : 100

DROP TABLE test_tb;

PRAGMA EXCEPTION_INIT

*********************

Using this you can associate a named exception with a particular oracle error.

This gives you the ability to trap this error specifically, rather than via an OTHERS handler.

Syntax:

PRAGMA EXCEPTION_INIT(exception_name, oracle_error_number);

DECLARE
v_result NUMBER;

PRAGMA EXCEPTION_INIT(Invalid, -1476);

BEGIN

SELECT 453 / 0 INTO v_result FROM dual;

dbms_output.put_line('Result : ' || v_result);

EXCEPTION

WHEN INVALID THEN

dbms_output.put_line('Invalid Exception');

END;

RAISE_APPLICATION_ERROR

************************

You can use this built-in function to create your own error messages, which can be more
descriptive than named exceptions.

Error Number :

Oracle Error Range : From -00000 to -19999

User Error Range : From -20000 to -20999

DECLARE
v_gender CHAR := '&gender';

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE_APPLICATION_ERROR(-20003, 'Enter valid gender');

END IF;

dbms_output.put_line('Gender : ' || v_gender);

END;

Posted 21st October 2014 by Unknown

1 View comments

RajmohanMarch 13, 2018 at 6:49 AM

How to get the two table data without using Joins and sub query,union?

Reply

OCT

Package

1. You can groups logical related subprogram (procedures and functions)


2. It consist of two parts

I) specification

II) Body

3. It allows the oracle server to read multiple object in to a memory once

4. You can declare global variable,cursor, user define exeption

5. Overloading

6. we can't create anonyms block inside the package

create table err_log(sno NUMBER, u_name VARCHAR2(30), error_msg CLOB, hap_tm


TIMESTAMP);

select * from err_log;

--stand alone procedure

CREATE OR REPLACE PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id


%TYPE) IS

v_salary employees.salary%TYPE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT salary,

first_name
INTO v_salary,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line('Salary of ' || v_first_name || ' is ' || v_salary);

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_sal_sp;

BEGIN

-- Call the procedure

emp_sal_sp(p_employee_id => :p_employee_id);

END;

CREATE OR REPLACE PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id


%TYPE) IS
v_hire_date DATE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT hire_date,

first_name

INTO v_hire_date,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line(v_first_name || ' hired on ' || to_char(v_hire_date,'month ddth,


yyyy'));

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_hdt_sp;
BEGIN

-- Call the procedure

emp_hdt_sp(p_employee_id => :p_employee_id);

END;

create or replace function sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER

IS

v_c NUMBER;

BEGIN

v_c := p_a + p_b;

RETURN v_c;

END;

--Specification Part

CREATE OR REPLACE PACKAGE emp_pkg

IS

PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id%TYPE);

PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id%TYPE);


FUNCTION sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER;

END emp_pkg ;

--Body Part

CREATE OR REPLACE PACKAGE BODY emp_pkg

IS

PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id%TYPE) IS

v_salary employees.salary%TYPE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT salary,

first_name

INTO v_salary,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line('Salary of ' || v_first_name || ' is ' || v_salary);

EXCEPTION

WHEN OTHERS THEN


v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_sal_sp;

PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id%TYPE) IS

v_hire_date DATE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT hire_date,

first_name

INTO v_hire_date,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line(v_first_name || ' hired on ' || to_char(v_hire_date,'month ddth,


yyyy'));

EXCEPTION

WHEN OTHERS THEN


v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_hdt_sp;

FUNCTION sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER

IS

v_c NUMBER;

BEGIN

v_c := p_a + p_b;

RETURN v_c;

END;

END emp_pkg;

A package specification can exist without a package body, but

a package body can't exist without a package specification.


--Executing procedure inside the package

BEGIN

emp_pkg.emp_sal_sp(120);

END;

--Executing function inside the package

SELECT emp_pkg.sum_fn(23,567) FROM dual;

-- You can declare global variable,cursor, user define exeption

create or replace package all_detail

as

PROCEDURE emp2sal (a IN NUMBER);

PROCEDURE emp2exep (a IN NUMBER);

FUNCTION add2num (a IN NUMBER, b IN NUMBER)

RETURN NUMBER;

c NUMBER(8); --global declaration

abort_ex EXCEPTION; --global exception declaration


CURSOR emp_rec --global cursor declaration

IS

SELECT first_name, salary, hire_date, department_id

FROM employees;

End all_detail;

create or replace package body all_detail

as

PROCEDURE emp2sal (a IN NUMBER)

AS

BEGIN

SELECT salary

INTO c

FROM Employees

WHERE Employee_id = a;

Dbms_output.put_line('Salary of Employee ' || a || ' is ' || c);

EXCEPTION

WHEN no_data_found THEN

Dbms_output.put_line('Please enter valid id');


END emp2sal;

PROCEDURE emp2exep (a IN NUMBER)

AS

BEGIN

SELECT Round(Months_between(sysdate,hire_date)/12)

INTO c

FROM Employees

WHERE Employee_id = a;

Dbms_output.put_line( c || ' Years');

EXCEPTION

WHEN no_data_found THEN

Dbms_output.put_line('Please enter valid id');

END emp2exep;

FUNCTION add2num (a IN NUMBER, b IN NUMBER)

RETURN NUMBER

AS

BEGIN

c := a+b;

RETURN C;
END;

End all_detail;

/*Declaring a Bodiless Package */

CREATE OR REPLACE PACKAGE global_constant

IS

mile_2_kilo CONSTANT NUMBER := 1.6093;

kilo_2_mile CONSTANT NUMBER := 0.6214;

yard_2_meter CONSTANT NUMBER := 0.9144;

meter_2_yard CONSTANT NUMBER := 1.0936;

END global_constant;

BEGIN

DBMS_OUTPUT.PUT_LINE('20 miles = ' || 20*global_constant.mile_2_kilo||' km');

END;

/*Forward Declaration in package */

DECLARE
PROCEDURE P2; -- forward declaration

PROCEDURE P3;

PROCEDURE P1 IS

BEGIN

dbms_output.put_line('From procedure p1');

p2;

END P1;

PROCEDURE P2 IS

BEGIN

dbms_output.put_line('From procedure p2');

p3;

END P2;

PROCEDURE P3 IS

BEGIN

dbms_output.put_line('From procedure p3');

END P3;

BEGIN

p1;

END;

sample output:
From procedure p1

From procedure p2

From procedure p3

Drop package package_name;

Drop package body package_name;

SELECT text FROM user_source u

WHERE u.name = 'EMP_PKG';

Interview Questions:

What is package?

Advantage of package

Is it possible to create package body with out package specification?

what is package overloading?

what is forward declaration in package?

which data dictionary table contain source code of package?

How to declare global variable, exception and cursor?

How to execute procedure and function inside the package?


Posted 4th October 2014 by Unknown

0 Add a comment

OCT

%TYPE and %ROWTYPE

--%type is used to fetch the data type of the particular column

create table product_details

p_id NUMBER(3),

p_nm VARCHAR2(30),

p_qty NUMBER(8),

order_dt DATE

);

BEGIN

INSERT INTO product_details VALUES(100,'Name0',400,'23-Mar-13');


INSERT INTO product_details VALUES(101,'Name1',600,'26-Apr-13');

INSERT INTO product_details VALUES(102,'Name2',800,'27-Jan-12');

INSERT INTO product_details VALUES(103,'Name3',300,'23-Jul-11');

INSERT INTO product_details VALUES(104,'Name4',200,'22-Aug-11');

INSERT INTO product_details VALUES(105,'Name5',500,'25-Oct-12');

commit;

END;

SELECT * FROM product_details;

------------------------------------

P_ID P_NM P_QTY ORDER_DT

------------------------------------

100 Name0 400 03/23/2013

101 Name1 600 04/26/2013

102 Name2 800 01/27/2012

103 Name3 300 07/23/2011

104 Name4 200 08/22/2011

105 Name5 500 10/25/2012

------------------------------------

DECLARE
v_name VARCHAR2(4);

BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 100;

dbms_output.put_line('Product Name : ' || v_name);

--error numeric or value error

END;

DECLARE

v_name VARCHAR2(5);

BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 100;

dbms_output.put_line('Product Name : ' || v_name);

END;

ALTER TABLE product_details

MODIFY p_nm VARCHAR2(15);


INSERT INTO product_details

VALUES

(106,

'name6',

700,

'26-Dec-12');

commit;

106 name6 700 12/26/2012

DECLARE

v_name VARCHAR2(5);

BEGIN

SELECT p_nm INTO v_name

FROM product_details

WHERE p_id = 106;

dbms_output.put_line('Product Name : ' || v_name);

--error

END;

/
DECLARE

v_name product_details.p_nm%TYPE;

BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 106;

dbms_output.put_line('Product Name : ' || v_name);

END;

DROP TABLE product_details;

DECLARE

dep_id departments.department_id%TYPE;

dep_name departments.department_name%TYPE;

dep_man_id departments.manager_id%TYPE;
dep_loc_id departments.location_id%TYPE;

BEGIN

SELECT department_id,

department_name,

manager_id,

location_id

INTO dep_id,

dep_name,

dep_man_id,

dep_loc_id

FROM departments

WHERE department_id = 10;

dbms_output.put_line('Department_id : ' || dep_id);

dbms_output.put_line('Department_name : ' || dep_name);

dbms_output.put_line('Manager_id : ' || dep_man_id);

dbms_output.put_line('Location_id : ' || dep_loc_id);

END;

--%rowtype is used to fetch the data type of all the column

--Insted of using %type if we use %rowtype means we can reduce the no of variables that we
declare
DECLARE

dep_detail departments%ROWTYPE;

BEGIN

SELECT *

INTO dep_detail

FROM departments

WHERE department_id = 10;

dbms_output.put_line('Department_id : ' || dep_detail.department_id);

dbms_output.put_line('Department_name : ' || dep_detail.department_name);

dbms_output.put_line('Manager_id : ' || dep_detail.manager_id);

dbms_output.put_line('Location_id : ' || dep_detail.location_id);

END;

DROP TABLE dept_details;

CREATE TABLE dept_details

(
dept_id number(3) ,

dept_name varchar2(30),

dept_manager_name varchar2(30)

);

insert into dept_details values(10,'dept1','manager_name1');

insert into dept_details values(20,'dept2','manager_name2');

SELECT * FROM dept_details;

-------------------------------------------------------

| DEPT_ID | DEPT_NAME | DEPT_MANAGER_NAME |

+------------+-----------------------+-----------------

| 10 | dept1 | manager_name1 |

| 20 | dept2 | manager_name2 |

------------+-----------------------+------------------

DECLARE

all_data dept_details%ROWTYPE;

BEGIN

all_data.dept_id := 100;

all_data.dept_name := 'Admin';
all_data.dept_manager_name := 'John';

UPDATE dept_details

SET ROW = all_data

WHERE dept_id = 10;

dbms_output.put_line(SQL%ROWCOUNT || ' Row(s) get updated');

END;

1 Row(s) get updated

select * from dept_details;

---------------------------------------------------

| DEPT_ID | DEPT_NAME | DEPT_MANAGER_NAME|

---------------------------------------------------

| 100 | Admin | John |

| 20 | dept2 | manager_name2 |

---------------------------------------------------
Interview Question :

1. What is the use of %TYPE?

2. What is the use of %ROWTYPE?

3. Difference between %TYPE and %ROWTYPE?

Posted 2nd October 2014 by Unknown

0 Add a comment

SEP

29

BULK Exceptions

/************************************************************************

* Handling Exceptions in Bulk Operations *

* Documented on 29-SEP-14 04.35.35.980894 PM +05:30 *

* Document By : Murugappan Annamalai *

* Reference : http://www.dba-oracle.com/plsql/t_plsql_exceptions.htm *

************************************************************************/
CREATE TABLE bulk_tb (ran_num NUMBER NOT NULL);

--inserting data using bulk collect

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

commit;

END;

SELECT COUNT(*) FROM bulk_tb;


COUNT(*)

-------

200

TRUNCATE TABLE bulk_tb;

sample2.sql --without exception part

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */


FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

commit;

END;

/*

Error Message :

ORA-01400: cannot insert NULL into ("HR"."bulk_tb"."ran_num")

ORA-06512: at line 15

*/

sample2.sql --with exception part

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;
END LOOP;

v_dat(100) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

BEGIN

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

COMMIT;

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('Error while inserting bulk record '||SQLERRM);

END;

END;

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

99
SQL%BULK_EXCEPTIONS(i).ERROR_INDEX

Holds the iteration (not the subscript) of the original FORALL statement that raised the
exception.

In sparsely populated collections,

the exception row must be found by looping through the original collection the correct
number of times.

SQL%BULK_EXCEPTIONS(i).ERROR_CODE

Holds the exceptions error code.

The total number of exceptions can be returned using the collections COUNT method,

which returns zero if no exceptions were raised. The save_exceptions.sql script,

a modified version of the handled_exception.sql script, demonstrates this functionality.

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

v_ex_count NUMBER(4);

abort_ex EXCEPTION;

PRAGMA EXCEPTION_INIT(abort_ex, -24381);


BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

v_dat(150) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

EXECUTE IMMEDIATE 'TRUNCATE TABLE bulk_tb';

BEGIN

FORALL i IN v_dat.FIRST..v_dat.LAST SAVE EXCEPTIONS

INSERT INTO bulk_tb VALUES(v_dat(i));

COMMIT;

EXCEPTION

WHEN abort_ex THEN

v_ex_count := SQL%BULK_EXCEPTIONS.COUNT;

FOR i IN 1..v_ex_count LOOP

dbms_output.put_line('Error: ' || i ||' Array Index: ' || SQL


%BULK_EXCEPTIONS(i).error_index ||

' Message: ' || SQLERRM(SQL%BULK_EXCEPTIONS(i).ERROR_CODE));

END LOOP;
END;

END;

/*

Sample output:

Error: 1 Array Index: 100 Message: -1400: non-ORACLE exception

Error: 2 Array Index: 150 Message: -1400: non-ORACLE exception

*/

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

198

SAVE EXCEPTIONS clause being removed, in the above script now traps a different error number.

The output from this script is listed below.


/*

Sample output:

Error: 1 Array Index: 100 Message: -1400: non-ORACLE exception

*/

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

99

SELECT COUNT(*) FROM bulk_tb;

DROP TABLE bulk_tb;

Posted 29th September 2014 by Unknown

0 Add a comment

SEP
29

Cursor - FOR UPDATE

/************************************************************************

* FOR UPDATE clause in oracle *

* Document By : Murugappan Annamalai *

************************************************************************/

create table prod_details(p_id VARCHAR2(30), P_name VARCHAR2(30));

BEGIN

--Inserting data into prod_details table

FOR i IN 1..50 LOOP

INSERT INTO prod_details VALUES(i,'pname'||i);

END LOOP;

commit;

END;

SELECT * FROM prod_details;


DECLARE

CURSOR PROD_DTLS_C IS

SELECT * FROM PROD_DETAILS T1 FOR UPDATE OF P_ID;

V_PID PROD_DETAILS.P_ID%TYPE;

V_PRDNAME PROD_DETAILS.P_NAME%TYPE;

BEGIN

OPEN PROD_DTLS_C;

LOOP

FETCH PROD_DTLS_C INTO V_PID, V_PRDNAME;

IF PROD_DTLS_C%NOTFOUND THEN

EXIT;

ELSE

UPDATE PROD_DETAILS P

SET P.P_ID = LPAD(P_ID, 10, 0)

WHERE CURRENT OF PROD_DTLS_C;

END IF;

END LOOP;
CLOSE PROD_DTLS_C;

COMMIT;

END;

select * from PROD_DETAILS;

TRUNCATE TABLE prod_details;

BEGIN

--Inserting data into prod_details table

FOR i IN 1..50 LOOP

INSERT INTO prod_details VALUES(i,'pname'||i);

END LOOP;

commit;

END;

DECLARE

CURSOR PROD_DTLS_C IS
SELECT * FROM PROD_DETAILS T1 FOR UPDATE OF P_ID;

V_PID PROD_DETAILS.P_ID%TYPE;

V_PRDNAME PROD_DETAILS.P_NAME%TYPE;

BEGIN

OPEN PROD_DTLS_C;

LOOP

FETCH PROD_DTLS_C INTO V_PID, V_PRDNAME;

IF PROD_DTLS_C%NOTFOUND THEN

EXIT;

ELSE

UPDATE PROD_DETAILS P

SET P.P_ID = LPAD(P_ID, 10, 0)

WHERE CURRENT OF PROD_DTLS_C;

END IF;

COMMIT;

END LOOP;

CLOSE PROD_DTLS_C;

--COMMIT;

END;
select * from PROD_DETAILS;

Posted 29th September 2014 by Unknown

0 Add a comment

MAY

28

Escape Sequence in Oracle

Escape special characters when writing SQL queries

--to include single '

SELECT 'Steven's salary is more than 50k INR' AS "SAL_DETAILS"

FROM Dual;

ORA-01756 : quoted string not properly terminated

SELECT 'Steven''s salary is more than 50k INR' AS "SAL_DETAILS"

FROM Dual;
SAL_DETAILS

---------------------------------------

Steven's salary is more than 50k INR

--to include double '

SELECT 'You can print double quot ('''') in oracle' "Info"

FROM Dual;

Info

---------------------------------------

You can print double quot ('') in oracle

SELECT q'[some test ' some test ' some text ']' AS "In 10g"

FROM dual;

In 10g

------------------------------------

some test ' some test ' some text '


--Escape wild card characters ( _ and % )

The LIKE keyword allows for string searches.

The '_' wild card character is used to match exactly one character

While '%' is used to match zero or more occurrences of any characters.

These characters can be escaped in SQL as follows.

WITH mail_ids AS

SELECT 'an.murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an_murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an%murugappan@gmail.com' mail FROM Dual

SELECT * FROM mail_ids

WHERE mail LIKE '__$_%' ESCAPE '$';

mail

----------------------------------

an_murugappan@gmail.com
WITH mail_ids AS

SELECT 'an.murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an_murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an%murugappan@gmail.com' mail FROM Dual

SELECT * FROM mail_ids

WHERE mail LIKE '__/%%' ESCAPE '/';

mail

----------------------------------

an%murugappan@gmail.com

Escape ampersand (&) characters in SQL*Plus

SQL> select '&a' FROM dual;

'23'

----

23
SQL> SET ESCAPE '\'

SQL> select '\&a' FROM dual;

'&A'

----

&a

SQL> SET SCAN OFF;

SQL> select '&a' FROM dual;

'&A'

----

&a

SQL> SET SCAN ON;

SQL> select '&a' FROM dual;

'45'

----

45

Posted 28th May 2014 by Unknown

0 Add a comment
MAY

28

Data Manipulation Language

Data Manipulation Language (DML) statements are used for managing data within schema
objects. Some examples:

INSERT - insert data into a table

UPDATE - updates existing data within a table

DELETE - deletes all records from a table, the space for the records remain

MERGE - UPSERT operation (insert or update)

CREATE TABLE prod_details

prod_id NUMBER(4) ,

prod_name VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

Deliver_dt DATE DEFAULT SYSDATE+3 ,

comments VARCHAR2(300)

);
SELECT * FROM prod_details;

no_data_found

INSERT

INSERT INTO prod_details(prod_id,prod_name,order_dt,deliver_dt,comments)

VALUES(100,'Apple iphone 5s','21-May-14','24-May-14','Color : Black');

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

---------------------------------------------------------------------------

--Inserting records with out mentioning column name

INSERT INTO prod_details

VALUES(101,'Samsung Galaxy III','20-Aug-14','23-Aug-14','Color : White');

SELECT * FROM prod_details;


---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

---------------------------------------------------------------------------

--Inserting selective number of values

INSERT INTO prod_details

VALUES(103,'Moto X','11-May-14','13-May-14');

ORA-00947 : not enough values

--While inserting selective number of values mentioning column name is compulsory.

INSERT INTO prod_details (prod_id,prod_name,order_dt,deliver_dt)

VALUES(103,'Moto X','11-May-14','13-May-14');

SELECT * FROM prod_details;

--------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

--------------------------------------------------------------------------------
100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

--------------------------------------------------------------------------------

--Inserting NULL value.

--If you want to insert NULL value you can ignore that column at the time of inserting

--or we can use NULL keyword to insert NULL.

INSERT INTO prod_details

VALUES(104,'Moto G','19-May-14','22-May-14',NULL);

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Noto G 5/19/2014 5/22/2014

---------------------------------------------------------------------------

--if you are not providing values for order_dt and deliver_dt column default value can be taken.
INSERT INTO prod_details(prod_id,prod_name,comments)

VALUES(105,'Nokia Lumis 720p','Color : Red');

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

----------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Moto G 5/19/2014 5/22/2014

105 Nokia Lumis 720p 5/26/2014 5/29/2014 Color : Red

---------------------------------------------------------------------------

--Inserting data by using sub query

CREATE TABLE test_tab (id NUMBER, Name VARCHAR2(30));

INSERT INTO test_tab VALUES(1,'Name1');

INSERT INTO test_tab VALUES(2,'Name2');

INSERT INTO test_tab VALUES(3,'Name3');


SELECT COUNT(*) FROM test_tab;

COUNT(*)

-------

--creating table by using sub query (with out data)

CREATE TABLE ins_chk

SELECT * FROM test_tab

WHERE id = 900;

SELECT COUNT(*) FROM ins_chk;

COUNT(*)

-------

--Inserting data by using sub query

--copying data from test_tab to ins_chk


INSERT INTO ins_chk (SELECT * FROM test_tab);

3 rows inserted in 0.047 seconds.

SELECT COUNT(*) FROM ins_chk;

COUNT(*)

-------

DROP TABLE test_tab;

DROP TABLE ins_chk;

UPDATE

Syntax :

UPDATE table_name

SET column1_name = column1_value,

column2_name = column2_value,
column2_name = column3_value,

columnn_name = columnn_value

WHERE condition(s);

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

----------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Moto G 5/19/2014 5/22/2014

105 Nokia Lumis 720p 5/26/2014 5/29/2014 Color : Red

---------------------------------------------------------------------------

UPDATE prod_details ps

SET ps.prod_name = 'iphone 5s'

WHERE ps.prod_id = 100;

1 row updated in 0.031 seconds

SELECT *

FROM prod_details ps
WHERE ps.prod_id = 100;

--------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

--------------------------------------------------------------------

100 iphone 5s 5/21/2014 5/24/2014 Color : Black

--------------------------------------------------------------------

--update statement with out condition

--If you try to execute update statement without condition it'll update all the records inside the
table.

UPDATE prod_details ps

SET ps.comments = 'None';

5 row updated in 0.031 seconds

SELECT *

FROM prod_details ps;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 None

101 Samsung Galaxy III 8/20/2014 8/23/2014 None

103 Moto X 5/11/2014 5/24/2014 None


104 Moto G 5/19/2014 5/22/2014 None

105 Nokia Lumis 720p 5/26/2014 5/29/2014 None

----------------------------------------------------------------------

--if your update text contain ' means you can use following metnod (use '')

UPDATE prod_details ps

SET ps.comments = 'Some product''s are not available'

WHERE ps.prod_id = 100;

1 row updated in 0.031 seconds

SELECT *

FROM prod_details ps

WHERE ps.prod_id = 100;

------------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

------------------------------------------------------------------------------------

100 iphone 5s 5/21/2014 5/24/2014 Some product's are not available

------------------------------------------------------------------------------------
DELETE

Syntax:

DELETE FROM table_name

WHERE condition(s);

DELETE FROM prod_details

WHERE prod_id IN (104, 105);

2 row(S) deleted in 0.032 seconds

SELECT *

FROM prod_details ps;

---------------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Some product's are not available

101 Samsung Galaxy III 8/20/2014 8/23/2014 None

103 Moto X 5/11/2014 5/24/2014 None

---------------------------------------------------------------------------------------
DELETE FROM prod_details;

3 row(s) deleted in 0.062 seconds.

SELECT * FROM prod_details;

no rows selected.

DROP TABLE prod_details;

MERGE = Insert + Update

-- will update soon.

Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Data Define Language


Data Definition Language (DDL) statements are used to define the database structure or schema.

Some examples:

CREATE - to create objects in the database.

ALTER - alters the structure of the database.

ADD

RENAME

MODIFY

DROP

DROP - delete objects from the database

TRUNCATE - remove all records from a table,

including all spaces allocated for the records are removed.

COMMENT - add comments to the data dictionary.

RENAME - rename an object.

Creating Table

--------------------------------------------------------------------------

Data Types Size Default Size Explanation

--------------------------------------------------------------------------

NUMBER(P,S) P: 1 to 38 we can store number between 0-9

S: -84 to 127

VARCHAR2 4000 Bytes we can store 0-9, a-z, A-Z and special characters
CHAR 2000 Bytes 1

DATE 7 Used to store Date

TIMESTAMP Includes year, month, day, hour, minute, and seconds.

LONG 2 GB Only one long column is allowed in a table.

We can't use this column in ORDER BY clause.

CLOB 4 GB Character Large Object

BLOB Binary Larger Object

--------------------------------------------------------------------------

CREATE

ALTER : ADD RENAME MODIFY DROP RENAME

RENAME

DROP

TRUNCATE

--creating table

CREATE TABLE friends_details_tb

Name VARCHAR2(30) ,

Phone NUMBER(10) ,

Gender CHAR ,

dob DATE ,

other_details LONG ,
make_dtm TIMESTAMP

);

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

-----------------------------

--maximum you can keep 255 columns in a table

ALTER : Colum level operations

ADD RENAME MODIFY DROP

ADD : Used to add a column after the table hase been created
ALTER TABLE friends_details_tb

ADD email VARCHAR2(30);

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

EMAIL VARCHAR2(30)

-----------------------------

--adding multiple columns by using single ALTER statement

SYNTAX

ALTER TABLE friends_details_tb

ADD (

column_1 Data_type(size),
column_2 Data_type(size),

column_3 Data_type(size),

column_4 Data_type(size)

);

RENAME : Used to Rename a column

ALTER TABLE friends_details_tb

RENAME COLUMN email TO email_id;

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)
-----------------------------

MODIFY : Used to change the data type or size of the data type.

ALTER TABLE friends_details_tb

MODIFY other_details CLOB;

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS CLOB

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

--Modifying multiple columns at a time


ALTER TABLE friends_details_tb

MODIFY ( column_name_1 old_datatype(new_size),

column_name_2 new_datatype(old_size),

column_name_3 new_datatype(new_size)

);

DROP : Used to drop the column after the table has been created.

ALTER TABLE friends_details_tb

DROP COLUMN other_details;

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------
RENAME : Used to Rename a particular table.

SYNTAX

RENAME old_table_name TO new_table_name;

RENAME friends_details_tb TO fnd_det;

DESCRIBE fnd_det;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

TRUNCATE : Used to remove the entire content of the table (not a structure)
SYNTAX

TRUNCATE TABLE table_name;

TRUNCATE TABLE fnd_det;

DROP : Used to drop the tabel (Data + stucture of the table get removed from the database )

DROP TABLE fnd_det;

*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Statements in Oracle

Data Definition Language (DDL)


DDL statements are used to define the database structure or schema. Some examples:

CREATE - to create objects in the database

ALTER - alters the structure of the database

ADD

RENAME

MODIFY

DROP

DROP - delete objects from the database

TRUNCATE - remove all records from a table,

including all spaces allocated for the records are removed

RENAME - rename an object

Data Manipulation Language (DML)

DML statements are used for managing data within schema objects. Some examples:

INSERT - insert data into a table

UPDATE - updates existing data within a table

DELETE - deletes all records from a table, the space for the records remain

MERGE - UPSERT operation (insert or update)


Data Control Language (DCL)

DCL statements. Some examples:

GRANT - gives users access privileges to database

REVOKE - withdraw access privileges given with the GRANT command

Transaction Control (TCL)

TCL statements are used to manage the changes made by DML statements. It allows
statements to be grouped together into logical transactions.

COMMIT - save work done

SAVEPOINT - identify a point in a transaction to which you can later roll back

ROLLBACK - restore database to original since the last COMMIT

Posted 28th May 2014 by Unknown

0 Add a comment

MAY
19

DECODE and CASE statement

CREATE TABLE students (

roll_no NUMBER(4) ,

Name VARCHAR2(30) ,

dept_cd VARCHAR2(20) ,

total_marks NUMBER(3)

);

BEGIN

INSERT INTO students VALUES (2000,'Rahul','CSE',480);

INSERT INTO students VALUES (2001,'Bala','IT', 390);

INSERT INTO students VALUES (2002,'Ramesh','CSE',250);

INSERT INTO students VALUES (2003,'Karthi','EEE',185);

INSERT INTO students VALUES (2004,'Ravi','IT',345);

END;

SELECT * FROM students;

DECODE

Decode is a function. Its a Oracle one.

Works like IF-THEN-ELSE.


You can use DECODE only in SELECT clause.

In DECODE you can include 255 things include Exep, search , result and default value.

Example

SELECT roll_no,

NAME,

dept_cd,

DECODE(dept_cd,

'CSE',

'Computer Science and Engineering',

'IT',

'Information Technology',

'Default Value') AS "DEPARTMENT NAME"

FROM students;

Sample Output

------------------------------------------------------------

ROLL_NO NAME DEPT_CD DEPARTMENT NAME

------------------------------------------------------------

2000 Rahul CSE Computer Science and Engineering

2001 Bala IT Information Technology

2002 Ramesh CSE Computer Science and Engineering

2003 Karthi EEE Default Value


2004 Ravi IT Information Technology

------------------------------------------------------------

CASE

CASE is an expression. Its a ANSI standard.

Compare to DECODE case will be more faster.

Example

SELECT roll_no,

NAME,

dept_cd,

total_marks,

CASE

WHEN total_marks > 500 THEN

'A Grade'

WHEN total_marks > 400 THEN

'B Grade'

WHEN total_marks > 300 THEN

'C Grade'

ELSE

'U Grade'

END AS "GRADE"

FROM students;
-----------------------------------------------

ROLL_NO NAME DEPT_CD TOTAL_MARKS GRADE

-----------------------------------------------

2000 Rahul CSE 480 B Grade

2001 Bala IT 390 C Grade

2002 Ramesh CSE 250 U Grade

2003 Karthi EEE 185 U Grade

2004 Ravi IT 345 C Grade

-----------------------------------------------

Interview Questions:

What is DECODE?

What is CASE?

Difference between CASE and DECODE? Which one is faster?

Posted 19th May 2014 by Unknown

0 Add a comment

MAY

19

Sub Query
Query with in another query

1. Single Row sub query

2. Multi row Sub query

select * from employees;

Want to fetch the person Who are all getting salary more than Neena's salary ?

Neena's Salary : 17000

Select First_name, salary

From Employees

Where salary > 17000;

--change in Neena's salary won't work for the above query.

Select salary From Employees

Where First_name = 'Neena';

Sub Query :
Select First_name, salary

From Employees

Where salary > (

Select salary From Employees

Where First_name = 'Neena'

);

Select * from employees;

Select salary From Employees

Where First_name = 'Alexander';

Sub Query Returns one value it is called as Single row sub query

Sub Query Returns more than one value it is called as Multi row sub query

Single row sub query operators :

> < >= <= = <>

Multiple Row Sub query operators :


IN ALL ANY

Who are all getting salary more than the average salary?

Select

First_name,

Salary

From

Employees

WHERE

Salary > (

SELECT Round(avg(salary),0)

FROM Employees

);

Multiple Row Sub query (In ANY ALL)

Select First_name,Department_id, salary

From Employees

Where salary in(

Select Salary From Employees

Where First_name = 'Alexander'

);
Any : Minimum Value will be taken (3100)

Select First_name,Department_id, salary

From Employees

Where salary > ANY(

Select Salary From Employees

Where First_name = 'Alexander'

);

All : Maximum Value will be taken (9000)

Select First_name,Department_id, salary

From Employees

Where salary > All(

Select Salary From Employees

Where First_name = 'Alexander'

);

We can use sub query in all the classes except Group by and order by class.

Select

From

Where
-----------Group by

having

-----------Order by

SELECT

( Select Count(*) from Employees Where Department_id = 90 )Executive,

( Select Count(*) from Employees Where Department_id = 60 ) IT,

( Select Count(*) from Employees Where Department_id = 10 ) Administration,

( Select Count(*) from Employees Where Department_id = 100) Finance

FROM

Dual;

Select Min(salary) From Employees;

Select Min(salary) from

Select * from Employees

Where Department_id = 60

);

What is INLINE VIEW?

If u use sub query in From it is call it is as INLINE VIEW.

Intermediate result set


Correlated sub query

SELECT employee_number, name

FROM employees Bob

WHERE salary > (

SELECT AVG(salary)

FROM employees

WHERE department = Bob.department

);

Posted 19th May 2014 by Unknown

0 Add a comment

Loading

Dynamic Views theme. Powered by Blogger.

Oracle sql & Pl/sql

search

Home Sql and pl/sql Sql Interview Questions


JUL

20

INLINE view in Oracle with 12c New Features

Named sub Query in FROM clause is call it as INLINE VIEW.

Oracle process a inline view faster than sub query

Inline View in Oracle

--Query to display all the employees who are all getting salary more than their department
average salary

SELECT First_name

, last_name

, salary

, department_id

FROM employees a , ( SELECT b.department_id

, AVG(b.salary) avg_sal

FROM employees b

GROUP BY b.department_id

)b

WHERE a.department_id = b.department_id

AND a.salary > b.avg_salary;


Display all the customer who have placed more number of orders by using INLINE view

CREATE TABLE customer_order_det_tb

( custm_id NUMBER ,

custm_nm VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

ttl_amt NUMBER(7,2)

);

BEGIN

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '11-Jul-15' , 45000.00);

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '14-Jul-15' , 27000.00);

INSERT INTO customer_order_det_tb VALUES(101, 'Raja' , '13-Jul-15' , 17000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 34000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 38000.00);

COMMIT;

END;

SELECT c.*

FROM customer_order_det_tb c;

--------------------------------------------

custm_id custm_nm order_dt ttl_amt

--------------------------------------------
100 Murugappan 7/11/2015 45000.00

100 Murugappan 7/14/2015 27000.00

101 Raja 7/13/2015 17000.00

102 Ramesh 7/15/2015 34000.00

102 Ramesh 7/15/2015 38000.00

--------------------------------------------

--Writing a Quer to display all the customer who have placed maximum number of order

--Query #1 for inline view

SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC;

--------------------------------

custm_id custm_nm total_odr

--------------------------------

100 Murugappan 2

102 Ramesh 2

101 Raja 1

--------------------------------

--Query #2 for inline view


SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm;

----------

total_odr

----------

----------

Inline view to find all the customers who have placed maximum number of orders

/****************************************

Syntax

SELECT * FROM <query1> x, <query2> y

WHERE contition;

****************************************/

SELECT query1.* FROM

( SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC


) query1,

( SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm

) query2

WHERE query1.total_odr = query2.total_odr;

-------------------------------

custm_id custm_nm total_odr

-------------------------------

100 Murugappan 2

102 Ramesh 2

-------------------------------

DROP TABLE customer_order_det_tb;

--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT

SELECT first_name, salary

FROM ( SELECT first_name, salary

FROM employees e

WHERE job_id NOT IN ('SALESMAN','PRESIDENT')

ORDER BY salary DESC

)
WHERE ROWNUM < 4;

New Oracle 12c Inline view Syntax

LATERAL clause for In-line views

Allows for columns in the inline view to be accessed!!

Example :

--in 11g

SELECT * FROM employees e, (

SELECT *

FROM departments d

WHERE e.department_id = d.department_id);

ORA-0090: "E"."DEPARTMENT_ID": Invalid Identifier

--in 12c

SELECT * FROM employees e, LATERAL(

SELECT *

FROM departments d

WHERE e.department_id = d.department_id


);

--in 11g

WITH t

AS

( SELECT LEVEL a

FROM dual

CONNECT BY LEVEL <= 30)

SELECT *

FROM t, (SELECT *

FROM employees

WHERE department_id = t.a

);

ORA-00904: "T"."A": invalid Identifier

--in 12c

WITH t

AS

(SELECT LEVEL a FROM dual CONNECT BY LEVEL <= 30)

SELECT * FROM t,

LATERAL(SELECT *

FROM employees

WHERE department_id = t.a);


Hope you have enjoyed this little article

Feed backs are always Welcome :) (:

Posted 20th July 2015 by Unknown

0 Add a comment

JAN

23

Salary Related Questions in Oracle

--creating table

CREATE TABLE employee_data

eid NUMBER(4),

ename VARCHAR2(30),

depno NUMBER(3),

salary NUMBER(8)

);
BEGIN

--Inserting records

INSERT INTO employee_data VALUES(1000,'Name01',90,30000);

INSERT INTO employee_data VALUES(1001,'Name02',90,6000);

INSERT INTO employee_data VALUES(1002,'Name03',90,23000);

INSERT INTO employee_data VALUES(1003,'Name04',60,35000);

INSERT INTO employee_data VALUES(1004,'Name05',60,60000);

INSERT INTO employee_data VALUES(1005,'Name06',60,30000);

INSERT INTO employee_data VALUES(1006,'Name07',80,36000);

INSERT INTO employee_data VALUES(1007,'Name08',80,29000);

INSERT INTO employee_data VALUES(1008,'Name09',80,37000);

INSERT INTO employee_data VALUES(1009,'Name10',80,41000);

COMMIT;

END;

SELECT * FROM employee_data

ORDER BY salary DESC;

--query to find maximum salary from employee_data table

SELECT MAX(salary) FROM employee_data;


--query to find minimum salary from employee_data table

SELECT MIN(salary) FROM employee_data;

--query to find second maximum salary from employee_data table

SELECT MAX(salary)

FROM employee_data

WHERE salary NOT IN (SELECT MAX(salary)

FROM employee_data);

--query to select 5th maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= 5);

--query to select nth maximum salary

SELECT MIN(salary)
FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= &n);

--query to select all the details of the employee whose getting nth maximum salary

SELECT *

FROM (SELECT emp.*,

rownum rn

FROM (SELECT *

FROM employee_data

ORDER BY salary DESC) emp)

WHERE rn = 9;

--same query using row_numbr( ) function

SELECT *

FROM (SELECT emp.*,

row_number() over(ORDER BY salary) rank

FROM employee_data emp)

WHERE rank = 9;
--same query using rank( ) function

SELECT *

FROM (SELECT emp.*,

rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--same query using dense_rank( ) function

SELECT *

FROM (SELECT emp.*,

dense_rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--query to display display maximum salary in all the department

SELECT e.depno "Department id",

MAX(salary) "Maximum Salary"

FROM employee_data e

GROUP BY e.depno;

--query to display all the employees who are all getting salary more than average salary of the
company
SELECT e.* FROM employee_data e

WHERE salary > (SELECT AVG(salary) FROM employee_data);

--query to display all the employees who are all getting salary more than their department
average salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE department_id = OUT.department_id);

--query to display all the employees who are all getting salary more than their manager salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE employee_id = OUT.manager_id);


Documented By : Murugappan Annamalai

Posted on : 23-Jan-15 16:34:00 IST.

Hope you have enjoyed this little article

Feed backs are always welcome :)

Posted 23rd January 2015 by Unknown

7 View comments

JAN

22

Why prefer COALESCE over NVL

Documented By : Nimish Garg

I prefer using "COALESCE" over "NVL" is some of the scenarios. Last week One of my friend
asked me what is the advantage of using "COALESCE" where we can simply use "NVL". I simply
gave him the reply from Oracle Docs i.e. NVL lets you replace null (returned as a blank) with a
string in the results of a query and COALESCE returns the first non-null expr in the expression list.
Oracle Database uses short-circuit evaluation with "COALESCE".
He replied that he knows the difference, he knows that "COALESCE" can take multiple arguments
and so on. He was more interested in understanding "short-circuit evaluation" of "COALESCE"
and the scenarios where I prefer using "COALESCE" over "NVL".

To make him understand I created following function which takes One second in every execution
and simply returns '--null--' and executed 2 very similar queries one with NVL and other with
COALESCE.

SQL> create or replace function f_null return varchar2

2 is

3 begin

4 dbms_lock.sleep(1);

5 return '--null--';

6 end;

7 /

Function created.

Following are the queries which I used to demonstrate that NVL evaluates both arguments even
if the second argument is not used and COALESCE uses short-circuit evaluation i.e. it only
evaluates the arguments only if they are needed.

SQL> select e.empno, e.ename ename, nvl(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME


---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.

Elapsed: 00:00:14.01

SQL> select e.empno, e.ename ename, coalesce(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME


---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.

Elapsed: 00:00:01.01

Here we can see easily that the first query with NVL took 14+ seconds, one second for each
record even if the "f_null" value was used only in one record. On the contrary as mentioned in
Oracle Documentation "COALESCE" uses its "short-circuit evaluation" and "f_null" was called
only once and so second query took only One Second. "COALESCE" is certainly use less resources
than NVL.

Posted 22nd January 2015 by Unknown


0 Add a comment

DEC

21

Constraints

It Enforce Rule On Table

We can create constraint at the time of Creating Table

1. Column Level Declaration

2. Table Level Declaration

1. We can provide own name.

Format : [part_of_project_name-table_name-column_name-constraint_type]

Example : gmind_emp_id_pk _uk _ck _f

2. system name name


Format : sys_cn

Example : SYS_C405323

We can create constraint after the table has been created

Types

Primary Key

Not allowed Null value

Not allowed you to enter duplicate value

Ex : Employee_id, Student_id

Unique Key

allowed Null value

Not allowed you to enter duplicate value

Ex : Contact_no, email

Foreign Key

It will allowed you to enter NULL and Duplicate value.


c1(pk) : 1 2 3

c2(f) : 1 1 2 3 4 Not allowed

Allowed you to enter duplicate value and null value

Not Null

It will not allowed you to enter null value

Check

You can check your own condition

Simple Table for understanding

------------------------------------

Duplicate NULL

------------------------------------

Primary Key X X

Unique Key X Allowed

Foreign Key Allowed Allowed

------------------------------------
creating table with all constraint type

Create table my_stu_details

S_id Number(2),

S_name Varchar2(30) Not Null, --SYS_Cn

s_mail Varchar2(30),

s_gender char(1),

s_did Number(3),

Constraint my_stu_sid_pk PRIMARY KEY (s_id),

constraint my_stu_mail_uk UNIQUE (s_mail) ,

Constraint my_stu_gen_ck CHECK (s_gender IN ('M', 'F', 'm', 'f')),

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

);

DESC my_stu_details;

------------------------------------

Name Type Nullable

------------------------------------

S_ID NUMBER(2)
S_NAME VARCHAR2(30)

S_MAIL VARCHAR2(30) Y

S_GENDER CHAR(1) Y

S_DID NUMBER(3) Y

------------------------------------

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name1' , 'name1@gmail.com' , 'm' , 60 );

Select * from my_stu_details;

Validating Primary Key

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-00001: unique constraint (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)


values (NULL, 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-01400: cannot insert NULL into (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (2 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

Validating NOT NULL Constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , NULL , 'name3@gmail.com' , 'F' , 80 );

ORA-01400: cannot insert NULL into ("HR"."MY_STU_DETAILS"."S_NAME")

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , 'Name3' , 'name3@gmail.com' , 'F' , 80 );

Select * from my_stu_details;


Validating Unique Key Constraint

--Duplicate Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , 'name3@gmail.com' , 'F' , 80 );

ORA-00001: unique constraint (HR.MY_STU_MAIL_UK) violated

--Null Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , null , 'M' , 70 );

Select * from my_stu_details;

Validating Check constraint


Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'j' , 70 );

ORA-02290: check constraint (HR.MY_STU_GEN_CK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'M' , 70 );

Select * from my_stu_details;

Validating Foreign Key

Select * from Departments;

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 3 );

ORA-02291: integrity constraint (HR.MY_STU_DID_FK) violated - parent key not found


Departments table : parent table

my_stu_details : Child table

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

--------------------------------------------------------

s_id s_name s_mail s_gender s_did

--------------------------------------------------------

1 name1 name1@gmail.com m 60

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 M 70

5 Name5 name5@gmail.com M 70

6 Name6 name6@gmail.com F 90

--------------------------------------------------------

Deleting the Primary key value which is referred by Foreign Key


Select * from Departments;

DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID

------------------------------------------------------------

60 IT 103 1400 <---- Delete

-- don't execute this query

--Delete From Departments

--Where Department_id = 60;

1) ON DELETE SET NULL

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

1 name1 name1@gmail.com m -

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------
2) ON DELETE SET CASCADE

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

Syntax

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE CASCADE

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE SET NULL

Constraint Related Data Dictionary Table information.


To view constraint Information

SELECT c.owner,

c.constraint_name,

c.constraint_type,

c.table_name,

c.r_constraint_name,

c.status

FROM user_constraints c

WHERE c.table_name = 'MY_STU_DETAILS';

------------------------------------------------------------------------------------

owner constraint_name constraint_type table_name r_constraint_name status

------------------------------------------------------------------------------------

HR SYS_C004023 C MY_STU_DETAILS ENABLED

HR MY_STU_GEN_CK C MY_STU_DETAILS ENABLED

HR MY_STU_SID_PK P MY_STU_DETAILS ENABLED

HR MY_STU_MAIL_UK U MY_STU_DETAILS ENABLED

HR MY_STU_DID_FK R MY_STU_DETAILS DEPT_ID_PK ENABLED

------------------------------------------------------------------------------------

To view constraint name with corresponding column name


SELECT * FROM user_cons_columns c

WHERE c.table_name = 'MY_STU_DETAILS';

-------------------------------------------------------------

owner constraint_name table_name column_name position

-------------------------------------------------------------

HR MY_STU_MAIL_UK MY_STU_DETAILS S_MAIL 1

HR MY_STU_SID_PK MY_STU_DETAILS S_ID 1

HR MY_STU_GEN_CK MY_STU_DETAILS S_GENDER

HR SYS_C004023 MY_STU_DETAILS S_NAME

HR MY_STU_DID_FK MY_STU_DETAILS S_DID 1

-------------------------------------------------------------

Creating Composite Primary Key

Creating Primary Key with more than one number of column

ALTER TABLE table_name

ADD CONSTRAINT constraint_name PRIMARY KEY(column1, column_2 , column3);

In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.
creating constraint after the table creation

ALTER TABLE table_name

ADD CONSTRAINT constraint_name CONSTRAINT_TYPE(column_name);

ALTER TABLE table_name

DROP CONSTRAINT constraint_name;

ALTER TABLE table_name

DROP PRIMARY KEY;

To drop related foreign key

ALTER TABLE table_name

DROP PRIMARY KEY CASCADE;

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name;

Disable constraint with related foreign key constraint


ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name CASCADE;

ALTER TABLE table_name

ENABLE CONSTRAINT constraint_name;

Interview Questions

What are all the type of constraint available in oracle?

Difference between PRIMARY KEY and UNIQUE key.

Difference between PRIMARY KEY ans FOREIGN KEY.

Difference between UNIQUE key and FOREIGN KEY.

Is it possible to create tow primary key in single table.

Write a syntax to create FOREIGN constraint.

How to create constraint after the table has been created?

How to enable and disable a constraint.

Which data dictionary table contains information about constraints?

Which Data Dictionary table contains information about constraint with corresponding column
name?

What is composite primary key?

Explain ON DELETE CASCADE and ON DELETE SET NULL option.


~Thanks For Reading~

Post your valuable feedback below

Posted 21st December 2014 by Unknown

1 View comments

UnknownMay 22, 2017 at 12:39 AM

good

Reply

DEC

listagg in Oracle 11g

Oracle 11gR2 listagg built-in function allows for many table columns to be displayed within a
single row, a non-first-normal form display

Syntax :
listagg(column_value,'delimiter') WITHIN GROUP(ORDER BY column_name)

--Example 1:

CREATE TABLE test_ins(empid NUMBER,product VARCHAR2(30));

BEGIN

INSERT INTO test_ins VALUES( 101,'pendrive');

INSERT INTO test_ins VALUES( 102,'toy');

INSERT INTO test_ins VALUES( 101,'ipod');

INSERT INTO test_ins VALUES( 102,'hat');

INSERT INTO test_ins VALUES( 103,'cpu');

INSERT INTO test_ins VALUES( 104,'pen');

INSERT INTO test_ins VALUES( 104,'car');

INSERT INTO test_ins VALUES( 104,'mat');

INSERT INTO test_ins VALUES( 105,'tv');

INSERT INTO test_ins VALUES( 106,'laptop');

commit;

END;

SELECT * FROM test_ins;

SELECT empid "Employee",

listagg(product,
',') within

GROUP (ORDER BY empid) "Products"

FROM test_ins

GROUP BY empid;

-->-- Result set --<--

DROP TABLE test_ins;

-->-- Example 2

select department_id "Department id", listagg(first_name,', ') WITHIN GROUP(ORDER BY


employee_id) "Employees"
FROM employees

WHERE department_id IN (10,20,30,60)

GROUP BY department_id;

-->-- Result set --<--

Posted 4th December 2014 by Unknown

0 Add a comment

NOV

Condition and Looping Statement

IF

IF ELSE

Multiple IF ELSE

LOOP

FOR LOOP

WHILE LOOP
create table test_udt(id NUMBER, salary NUMBER);

BEGIN

INSERT INTO test_udt VALUES(001,23000);

INSERT INTO test_udt VALUES(002,43000);

INSERT INTO test_udt VALUES(003,78000);

INSERT INTO test_udt VALUES(004,25000);

INSERT INTO test_udt VALUES(005,26000);

INSERT INTO test_udt VALUES(006,90000);

Commit;

END;

select * from test_udt;

IF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN
SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 1;

IF v_salary > 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

END IF;

commit;

END;

IF ELSE

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;
IF v_salary < 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

ELSE

UPDATE test_udt t

SET t.salary = v_salary+20007

WHERE t.id = v_id ;

END IF;

commit;

END;

--same example with less number of lines

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;
IF v_salary < 20000 THEN

v_salary := v_salary+10005;

ELSE

v_salary := v_salary+20007;

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

Multiple IF ELSIF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary
FROM test_udt

WHERE id = 3;

IF v_id = 1 THEN

v_salary := 1000;

dbms_output.put_line('1 inside');

ELSIF v_id = 2 THEN

v_salary := 2000;

dbms_output.put_line('2 inside');

ELSIF v_id = 3 THEN

v_salary := 3000;

dbms_output.put_line('3 inside');

ELSIF v_id = 4 THEN

v_salary := 4000;

dbms_output.put_line('4 inside');

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;


LOOP

--syntax

LOOP

--statements

--increment

--exit statement

END LOOP;

CREATE TABLE prod_details (pid VARCHAR2(3), pname VARCHAR2(30));

DECLARE

i NUMBER := 1;

x VARCHAR2(3);

BEGIN

LOOP

x := lpad(i,3,'0');

dbms_output.put_line('x value : '|| x);

INSERT INTO prod_details VALUES(i, 'Product '||i);

EXIT WHEN i >900;

i := i+1;
IF MOD(i,100) = 0 THEN

commit;

dbms_output.put_line('commit executed');

END IF;

END LOOP;

END;

SELECT * FROM prod_details ORDER BY 1;

DROP TABLE prod_details;

FOR LOOP

BEGIN

FOR I in 1..5

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

FOR LOOP - Reverse


BEGIN

FOR I in REVERSE 14..50

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

WHILE LOOP

DECLARE

i_val NUMBER:=0;

BEGIN

WHILE (i_val < 11)

LOOP

dbms_output.put_line('The value of I is '||i_val);

i_val := i_val + 1;

END LOOP;

END;

sample output:

The value of I is 0

The value of I is 1
The value of I is 2

The value of I is 3

The value of I is 4

The value of I is 5

The value of I is 6

The value of I is 7

The value of I is 8

The value of I is 9

The value of I is 10

Posted 8th November 2014 by Unknown

0 Add a comment

OCT

21

Bulk Collect

This is used for array fetches

With this you can retrieve multiple rows of data with a single round trip.

This reduces the number of context switches between the pl/sql and sql engines.

You can use bulk collect in both dynamic and static sql.

You can use bulk collect in select, fetch into and returning into clauses.
SQL engine automatically initializes and extends the collections you reference in the bulk
collect clause.

You can fetch into multiple collections with one column each.

You can use the limit clause of bulk collect to restrict the no of rows retrieved.

SELECT * FROM product_details;

-->-- Bulk collect in FETCH INTO --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;
END;

-->-- Bulk collect in SELECT clause --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

BEGIN

SELECT * BULK COLLECT INTO dta FROM product_details;

FOR i IN dta.FIRST .. dta.LAST LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- LIMIT in Bulk collect --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;


BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta LIMIT 30;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Multiple fetches in INTO clause --<--

SELECT * FROM product_details;

DECLARE

TYPE alldata_typ1 IS TABLE OF product_details.p_id%TYPE;

TYPE alldata_typ2 IS TABLE OF product_details.p_name%TYPE;

dta1 alldata_typ1;

dta2 alldata_typ2;

CURSOR proddt_cur IS

SELECT p_id, p_name FROM product_details;


BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta1, dta2;

CLOSE proddt_cur;

FOR i IN dta1.FIRST .. dta1.COUNT LOOP

dbms_output.put_line('Department Id : ' || dta1(i));

END LOOP;

FOR i IN dta2.FIRST .. dta2.COUNT LOOP

dbms_output.put_line('Department Name : ' || dta2(i));

END LOOP;

END;

DROP TABLE dep_details;

DROP TABLE product_details;

Posted 21st October 2014 by Unknown

0 Add a comment
OCT

21

Ref Cursor

This is unconstrained cursor which will return different types depends upon the user input.

Ref cursors cannot be closed implicitly.

Ref cursor with return type is called strong cursor.

Ref cursor without return type is called weak cursor.

You can declare ref cursor type in package spec as well as body.

You can declare ref cursor types in local subprograms or anonymous blocks.

CREATE OR REPLACE PROCEDURE ref_c_sp(dep_det_c IN OUT SYS_REFCURSOR)

AS

BEGIN

OPEN dep_det_c

FOR

SELECT * FROM dep_details d;

END;

DECLARE

dep_det_c SYS_REFCURSOR;
tab_data dep_details%ROWTYPE;

BEGIN

ref_c_sp(dep_det_c);

LOOP

FETCH dep_det_c INTO tab_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department Name : '|| tab_data.d_name);

END LOOP;

CLOSE dep_det_c;

END;

/*sample output*/

Department Name : Admin

Department Name : HR

Department Name : Sales

Department Name : Marketing

DROP PROCEDURE ref_c_sp;

Posted 21st October 2014 by Unknown


0 Add a comment

OCT

21

Cursor

SQL Private work Area where the query get passed and executed.

Types

******

Implicit(SQL)

Explicit

-->-- advanced cursor types --<--

Parametrized Cursor

Ref Cursor

Implicit

********

ORACLE implicitly opens a cursor to process each SQL statement not associated with an
explicitly declared cursor.

PL/SQL lets you refer to the most recent implicit cursor as the SQL” cursor. So, although you
cannot use the OPEN,
FETCH, and CLOSE statements to control an implicit cursor, you can still use cursor attributes to
access information

about the most recently executed SQL statement.

Cursor Stages

**************

OPEN cursor_name

FETCH (with in loop)

CLOSE cursor_name

Explicit

The set of rows returned by a query can consist of zero, one, or multiple rows,

depending on how many rows meet your search criteria. When a query returns multiple rows,

you can explicitly define a cursor to process the rows. You use three commands to control the
cursor

Cursor Attributes

*****************

%FOUND

%NOTFOUND

%ISOPEN

%ROWCOUNT

%BULK_ROWCOUNT --<-- used to handle error while using bulk collection.


%BULK_EXCEPTIONS --<-- used to handle error while using bulk collection.

Cursor Declaration

DECLARE

CURSOR <cursor_name>

IS

<SELECT statement>

BEGIN

--> some stmt

END;

Cursor Loop

Loop

While Loop

For Loop

Cursor Clauses

Return

For update

Where current of

Bulk collect

-->-- creating table


create table product_details

p_id NUMBER,

p_name VARCHAR2(30),

p_order_dt DATE

);

-->-- Inserting data

BEGIN

FOR i IN 1 .. 75 LOOP

INSERT INTO product_details VALUES (i, 'prod_name_' || i, SYSDATE + i);

END LOOP;

commit;

END;

-->-- selecting data

SELECT * FROM product_details;

---------------------------------------------

p_id p_name p_order_dt


---------------------------------------------

1 prod_name_1 10/11/2014 3:48:32 PM

2 prod_name_2 10/12/2014 3:48:32 PM

3 prod_name_3 10/13/2014 3:48:32 PM

4 prod_name_4 10/14/2014 3:48:32 PM

5 prod_name_5 10/15/2014 3:48:32 PM

6 prod_name_6 10/16/2014 3:48:32 PM

7 prod_name_7 10/17/2014 3:48:32 PM

8 prod_name_8 10/18/2014 3:48:32 PM

9 prod_name_9 10/19/2014 3:48:32 PM

10 prod_name_10 10/20/2014 3:48:32 PM

11 prod_name_11 10/21/2014 3:48:32 PM

12 prod_name_12 10/22/2014 3:48:32 PM

13 prod_name_13 10/23/2014 3:48:32 PM

14 prod_name_14 10/24/2014 3:48:32 PM

15 prod_name_15 10/25/2014 3:48:32 PM

16 prod_name_16 10/26/2014 3:48:32 PM

17 prod_name_17 10/27/2014 3:48:32 PM

18 prod_name_18 10/28/2014 3:48:32 PM

19 prod_name_19 10/29/2014 3:48:32 PM

20 prod_name_20 10/30/2014 3:48:32 PM

---------------------------------------------

----------------------------------------------
Implicit Cursor

----------------------------------------------

--will update soon

----------------------------------------------

Explicit Cursor

----------------------------------------------

**********************************************

Processing cursor data by using LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND; --<-- if next record not found means control will
come out from the loop
dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;
LOOP

FETCH prod_detail_cur

INTO all_data;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

EXIT WHEN prod_detail_cur%FOUND; --<-- if next record found means control will come
out from the loop

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN
OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )


Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor Already closed

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

-->-- CLOSE prod_detail_cur;


IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor closed

**********************************************

Processing cursor data by using WHILE LOOP


**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

OPEN prod_detail_cur;

FETCH prod_detail_cur

INTO all_data;

WHILE prod_detail_cur%FOUND LOOP

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

FETCH prod_detail_cur

INTO all_data;

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/
Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

************************************************************

Processing cursor data by using FOR LOOP - CURSOR FOR LOOP

************************************************************

DECLARE

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

FOR i IN prod_detail_cur

LOOP

dbms_output.put_line('Product id : ' || i.p_id ||

' Product Name : ' || i.p_name ||

' ( Orderd on : ' || TRIM(i.p_order_dt) || ' )');

END LOOP;

END;
/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

Parameterized Cursor

*********************

This was used when you are going to use the cursor in more than one place with different
values for the same where clause.

Cursor parameters must be in mode.

Cursor parameters may have default values.

The scope of cursor parameter is within the select statement.

CREATE TABLE dep_details(d_id NUMBER,d_name VARCHAR2(30), location_id NUMBER);

BEGIN

INSRT INTO dep_details VALUES(001,'Admin',1010);

INSRT INTO dep_details VALUES(002,'HR',1010);


INSRT INTO dep_details VALUES(003,'Sales',1020);

INSRT INTO dep_details VALUES(004,'Marketing',1020);

commit;

END;

SELECT * FROM dep_details;

----------------------------

d_id d_name location_id

----------------------------

1 Admin 1010

2 HR 1010

3 Sales 1020

4 Marketing 1020

----------------------------

DECLARE

-->--Declaring parameterized cursor

CURSOR dep_det_c(p_location_id NUMBER) IS

SELECT * FROM dep_details d WHERE d.location_id = p_location_id;

all_data dep_details%ROWTYPE;

BEGIN

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1010);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

-->-- opening same cursor with different input value

OPEN dep_det_c(1020);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

END;

/
/*sample output*/

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 1 Department Name : Admin

Department id : 2 Department Name : HR

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 3 Department Name : Sales

Department id : 4 Department Name : Marketing

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Handling Exception

Error Handling in oracle

ERROR

Any departure from the expected behavior of the system or program,


which stops the working of the system is an error.

Types : compile time error

Run time error

EXCEPTION

Any error or problem which one can handle and continue to work normally.

Handling Exception

When exception is raised, control passes to the exception section of the block.

i.e. EXCEPTION

WHEN name_of_exception THEN

Types : Pre Defined Exceptions

User Defined Exceptions

Predefined Exception

*********************

Oracle has predefined several exceptions that correspond to the most common oracle errors.

------------------------------------------------------------------------

Exception Oracle Error SQL Code Value


------------------------------------------------------------------------

ZERO_DIVIDE ORA-01476 -1476

NO_DATA_FOUND ORA-01403 +100

DUP_VAL_ON_INDEX ORA-00001 -1

TOO_MANY_ROWS ORA-01422 -1422

VALUE_ERROR ORA-06502 -6502

CURSOR_ALREADY_OPEN ORA-06511 -6511

OTHERS

------------------------------------------------------------------------

-->-- ZERO_DIVIDE --<--

Your program attempts to divide a number by zero.

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN ZERO_DIVIDE THEN

dbms_output.put_line('Divisor is equal to zero');

END;
-->-- NO_DATA_FOUND --<--

Single row SELECT returned no rows or your program referenced a deleted element in a nested
table

or an uninitialized element in an associative array (index-by table).

CREATE TABLE test_tb(id NUMBER PRIMARY KEY);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN NO_DATA_FOUND THEN

dbms_output.put_line('There is no data inside the table');

END;

-->-- DUP_VAL_ON_INDEX --<--

A program attempted to insert duplicate values in a column that is constrained by a unique


index.

INSERT INTO test_tb VALUES (1);


INSERT INTO test_tb VALUES (2);

commit;

BEGIN

INSERT INTO test_tb VALUES (2);

EXCEPTION

WHEN DUP_VAL_ON_INDEX THEN

dbms_output.put_line('Duplicate values are not allowed');

END;

-->-- TOO_MANY_ROWS --<--

Single row SELECT returned multiple rows.

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN TOO_MANY_ROWS THEN

dbms_output.put_line('Query returning more than one row');

END;
DROP TABLE test_tb;

-->-- VALUE_ERROR --<--

An arithmetic, conversion, truncation, or size constraint error occurred.

DECLARE

num1 NUMBER(2);

BEGIN

num1 := 345;

EXCEPTION

WHEN VALUE_ERROR THEN

dbms_output.put_line('check the size of the variable');

END;

-->-- CURSOR_ALREADY_OPEN --<--

A program attempted to open an already opened cursor.

CREATE TABLE emp(id NUMBER, name VARCHAR2(30));

BEGIN
INSERT INTO emp VALUES(1,'Name1');

INSERT INTO emp VALUES(2,'Name2');

INSERT INTO emp VALUES(3,'Name3');

INSERT INTO emp VALUES(4,'Name4');

COMMIT;

END;

SELECT * FROM emp;

DECLARE

cursor emp_c IS

SELECT * FROM emp;

all_data emp%ROWTYPE;

BEGIN

OPEN emp_c;

OPEN emp_c;

NULL;

CLOSE emp_c;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

END;

DROP TABLE emp;


-->-- OTHERS --<--

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

WHEN OTHERS THEN

dbms_output.put_line('Some other error ' || SQLERRM);

END;

User Defined Exception

**********************

A user-defined exception is an error that is defined by the programmer.

User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,

exceptions have a type EXCEPTION and scope.


DECLARE

v_gender CHAR := '&gender';

gender_ex EXCEPTION;

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE gender_ex;

END IF;

dbms_output.put_line('Gender : '||v_gender);

EXCEPTION

WHEN gender_ex THEN

dbms_output.put_line('Please Enter valid gender');

END;

create table test_insert (id NUMBER, Name VARCHAR2(30));

DECLARE

abort_ex EXCEPTION;

BEGIN

FOR i IN 1..100

LOOP

BEGIN

IF mod(i,10)=0 THEN

RAISE abort_ex;

END IF;
INSERT INTO test_insert VALUES(i, 'Name'||i);

EXCEPTION

WHEN abort_ex THEN

NULL;

END;

END LOOP;

COMMIT;

END;

SELECT * FROM test_insert;

DROP TABLE test_insert;

SQLERRM and SQLCODE

********************

SQLCODE returns the current error code, and SQLERRM returns the current error message
text;

For user-defined exception SQLCODE returns 1 and SQLERRM returns “user-defined


exception”.

SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.

CREATE TABLE test_tb (id NUMBER);


DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

dbms_output.put_line(v_id);

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('SQLERRM : ' || SQLERRM);

dbms_output.put_line('SQLCODE : ' || SQLCODE);

END;

/*sample output*/

SQLERRM : ORA-01403: no data found

SQLCODE : 100

DROP TABLE test_tb;

PRAGMA EXCEPTION_INIT

*********************

Using this you can associate a named exception with a particular oracle error.

This gives you the ability to trap this error specifically, rather than via an OTHERS handler.
Syntax:

PRAGMA EXCEPTION_INIT(exception_name, oracle_error_number);

DECLARE

v_result NUMBER;

PRAGMA EXCEPTION_INIT(Invalid, -1476);

BEGIN

SELECT 453 / 0 INTO v_result FROM dual;

dbms_output.put_line('Result : ' || v_result);

EXCEPTION

WHEN INVALID THEN

dbms_output.put_line('Invalid Exception');

END;

RAISE_APPLICATION_ERROR

************************

You can use this built-in function to create your own error messages, which can be more
descriptive than named exceptions.

Error Number :
Oracle Error Range : From -00000 to -19999

User Error Range : From -20000 to -20999

DECLARE

v_gender CHAR := '&gender';

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE_APPLICATION_ERROR(-20003, 'Enter valid gender');

END IF;

dbms_output.put_line('Gender : ' || v_gender);

END;

Posted 21st October 2014 by Unknown

1 View comments

RajmohanMarch 13, 2018 at 6:49 AM

How to get the two table data without using Joins and sub query,union?

Reply

OCT

4
Package

1. You can groups logical related subprogram (procedures and functions)

2. It consist of two parts

I) specification

II) Body

3. It allows the oracle server to read multiple object in to a memory once

4. You can declare global variable,cursor, user define exeption

5. Overloading

6. we can't create anonyms block inside the package

create table err_log(sno NUMBER, u_name VARCHAR2(30), error_msg CLOB, hap_tm


TIMESTAMP);

select * from err_log;

--stand alone procedure

CREATE OR REPLACE PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id


%TYPE) IS

v_salary employees.salary%TYPE;
v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT salary,

first_name

INTO v_salary,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line('Salary of ' || v_first_name || ' is ' || v_salary);

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_sal_sp;

BEGIN

-- Call the procedure


emp_sal_sp(p_employee_id => :p_employee_id);

END;

CREATE OR REPLACE PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id


%TYPE) IS

v_hire_date DATE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT hire_date,

first_name

INTO v_hire_date,

v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line(v_first_name || ' hired on ' || to_char(v_hire_date,'month ddth,


yyyy'));

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,
systimestamp);

commit;

END emp_hdt_sp;

BEGIN

-- Call the procedure

emp_hdt_sp(p_employee_id => :p_employee_id);

END;

create or replace function sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER

IS

v_c NUMBER;

BEGIN

v_c := p_a + p_b;

RETURN v_c;

END;

/
--Specification Part

CREATE OR REPLACE PACKAGE emp_pkg

IS

PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id%TYPE);

PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id%TYPE);

FUNCTION sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER;

END emp_pkg ;

--Body Part

CREATE OR REPLACE PACKAGE BODY emp_pkg

IS

PROCEDURE emp_sal_sp(p_employee_id IN employees.employee_id%TYPE) IS

v_salary employees.salary%TYPE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT salary,

first_name

INTO v_salary,
v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line('Salary of ' || v_first_name || ' is ' || v_salary);

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_sal_sp;

PROCEDURE emp_hdt_sp(p_employee_id IN employees.employee_id%TYPE) IS

v_hire_date DATE;

v_first_name employees.first_name%TYPE;

v_error VARCHAR2(1000);

BEGIN

SELECT hire_date,

first_name

INTO v_hire_date,
v_first_name

FROM employees

WHERE employee_id = p_employee_id;

dbms_output.put_line(v_first_name || ' hired on ' || to_char(v_hire_date,'month ddth,


yyyy'));

EXCEPTION

WHEN OTHERS THEN

v_error := 'Error while fetching salary. Error : ' || SQLERRM;

INSERT INTO err_log

VALUES

(1,

USER,

v_error,

systimestamp);

commit;

END emp_hdt_sp;

FUNCTION sum_fn (p_a IN NUMBER, p_b IN NUMBER)

RETURN NUMBER

IS

v_c NUMBER;

BEGIN

v_c := p_a + p_b;

RETURN v_c;

END;
END emp_pkg;

A package specification can exist without a package body, but

a package body can't exist without a package specification.

--Executing procedure inside the package

BEGIN

emp_pkg.emp_sal_sp(120);

END;

--Executing function inside the package

SELECT emp_pkg.sum_fn(23,567) FROM dual;

-- You can declare global variable,cursor, user define exeption

create or replace package all_detail

as

PROCEDURE emp2sal (a IN NUMBER);

PROCEDURE emp2exep (a IN NUMBER);


FUNCTION add2num (a IN NUMBER, b IN NUMBER)

RETURN NUMBER;

c NUMBER(8); --global declaration

abort_ex EXCEPTION; --global exception declaration

CURSOR emp_rec --global cursor declaration

IS

SELECT first_name, salary, hire_date, department_id

FROM employees;

End all_detail;

create or replace package body all_detail

as

PROCEDURE emp2sal (a IN NUMBER)

AS

BEGIN

SELECT salary

INTO c

FROM Employees
WHERE Employee_id = a;

Dbms_output.put_line('Salary of Employee ' || a || ' is ' || c);

EXCEPTION

WHEN no_data_found THEN

Dbms_output.put_line('Please enter valid id');

END emp2sal;

PROCEDURE emp2exep (a IN NUMBER)

AS

BEGIN

SELECT Round(Months_between(sysdate,hire_date)/12)

INTO c

FROM Employees

WHERE Employee_id = a;

Dbms_output.put_line( c || ' Years');

EXCEPTION

WHEN no_data_found THEN

Dbms_output.put_line('Please enter valid id');

END emp2exep;
FUNCTION add2num (a IN NUMBER, b IN NUMBER)

RETURN NUMBER

AS

BEGIN

c := a+b;

RETURN C;

END;

End all_detail;

/*Declaring a Bodiless Package */

CREATE OR REPLACE PACKAGE global_constant

IS

mile_2_kilo CONSTANT NUMBER := 1.6093;

kilo_2_mile CONSTANT NUMBER := 0.6214;

yard_2_meter CONSTANT NUMBER := 0.9144;

meter_2_yard CONSTANT NUMBER := 1.0936;

END global_constant;

BEGIN

DBMS_OUTPUT.PUT_LINE('20 miles = ' || 20*global_constant.mile_2_kilo||' km');


END;

/*Forward Declaration in package */

DECLARE

PROCEDURE P2; -- forward declaration

PROCEDURE P3;

PROCEDURE P1 IS

BEGIN

dbms_output.put_line('From procedure p1');

p2;

END P1;

PROCEDURE P2 IS

BEGIN

dbms_output.put_line('From procedure p2');

p3;

END P2;

PROCEDURE P3 IS

BEGIN

dbms_output.put_line('From procedure p3');

END P3;
BEGIN

p1;

END;

sample output:

From procedure p1

From procedure p2

From procedure p3

Drop package package_name;

Drop package body package_name;

SELECT text FROM user_source u

WHERE u.name = 'EMP_PKG';

Interview Questions:

What is package?

Advantage of package

Is it possible to create package body with out package specification?


what is package overloading?

what is forward declaration in package?

which data dictionary table contain source code of package?

How to declare global variable, exception and cursor?

How to execute procedure and function inside the package?

Posted 4th October 2014 by Unknown

0 Add a comment

OCT

%TYPE and %ROWTYPE

--%type is used to fetch the data type of the particular column

create table product_details

p_id NUMBER(3),

p_nm VARCHAR2(30),

p_qty NUMBER(8),
order_dt DATE

);

BEGIN

INSERT INTO product_details VALUES(100,'Name0',400,'23-Mar-13');

INSERT INTO product_details VALUES(101,'Name1',600,'26-Apr-13');

INSERT INTO product_details VALUES(102,'Name2',800,'27-Jan-12');

INSERT INTO product_details VALUES(103,'Name3',300,'23-Jul-11');

INSERT INTO product_details VALUES(104,'Name4',200,'22-Aug-11');

INSERT INTO product_details VALUES(105,'Name5',500,'25-Oct-12');

commit;

END;

SELECT * FROM product_details;

------------------------------------

P_ID P_NM P_QTY ORDER_DT

------------------------------------

100 Name0 400 03/23/2013

101 Name1 600 04/26/2013

102 Name2 800 01/27/2012

103 Name3 300 07/23/2011

104 Name4 200 08/22/2011


105 Name5 500 10/25/2012

------------------------------------

DECLARE

v_name VARCHAR2(4);

BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 100;

dbms_output.put_line('Product Name : ' || v_name);

--error numeric or value error

END;

DECLARE

v_name VARCHAR2(5);

BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 100;

dbms_output.put_line('Product Name : ' || v_name);


END;

ALTER TABLE product_details

MODIFY p_nm VARCHAR2(15);

INSERT INTO product_details

VALUES

(106,

'name6',

700,

'26-Dec-12');

commit;

106 name6 700 12/26/2012

DECLARE

v_name VARCHAR2(5);

BEGIN

SELECT p_nm INTO v_name


FROM product_details

WHERE p_id = 106;

dbms_output.put_line('Product Name : ' || v_name);

--error

END;

DECLARE

v_name product_details.p_nm%TYPE;

BEGIN

SELECT p_nm

INTO v_name

FROM product_details

WHERE p_id = 106;

dbms_output.put_line('Product Name : ' || v_name);

END;

DROP TABLE product_details;


DECLARE

dep_id departments.department_id%TYPE;

dep_name departments.department_name%TYPE;

dep_man_id departments.manager_id%TYPE;

dep_loc_id departments.location_id%TYPE;

BEGIN

SELECT department_id,

department_name,

manager_id,

location_id

INTO dep_id,

dep_name,

dep_man_id,

dep_loc_id

FROM departments

WHERE department_id = 10;

dbms_output.put_line('Department_id : ' || dep_id);

dbms_output.put_line('Department_name : ' || dep_name);

dbms_output.put_line('Manager_id : ' || dep_man_id);

dbms_output.put_line('Location_id : ' || dep_loc_id);


END;

--%rowtype is used to fetch the data type of all the column

--Insted of using %type if we use %rowtype means we can reduce the no of variables that we
declare

DECLARE

dep_detail departments%ROWTYPE;

BEGIN

SELECT *

INTO dep_detail

FROM departments

WHERE department_id = 10;

dbms_output.put_line('Department_id : ' || dep_detail.department_id);

dbms_output.put_line('Department_name : ' || dep_detail.department_name);

dbms_output.put_line('Manager_id : ' || dep_detail.manager_id);

dbms_output.put_line('Location_id : ' || dep_detail.location_id);

END;

/
DROP TABLE dept_details;

CREATE TABLE dept_details

dept_id number(3) ,

dept_name varchar2(30),

dept_manager_name varchar2(30)

);

insert into dept_details values(10,'dept1','manager_name1');

insert into dept_details values(20,'dept2','manager_name2');

SELECT * FROM dept_details;

-------------------------------------------------------

| DEPT_ID | DEPT_NAME | DEPT_MANAGER_NAME |

+------------+-----------------------+-----------------

| 10 | dept1 | manager_name1 |

| 20 | dept2 | manager_name2 |

------------+-----------------------+------------------
DECLARE

all_data dept_details%ROWTYPE;

BEGIN

all_data.dept_id := 100;

all_data.dept_name := 'Admin';

all_data.dept_manager_name := 'John';

UPDATE dept_details

SET ROW = all_data

WHERE dept_id = 10;

dbms_output.put_line(SQL%ROWCOUNT || ' Row(s) get updated');

END;

1 Row(s) get updated

select * from dept_details;

---------------------------------------------------
| DEPT_ID | DEPT_NAME | DEPT_MANAGER_NAME|

---------------------------------------------------

| 100 | Admin | John |

| 20 | dept2 | manager_name2 |

---------------------------------------------------

Interview Question :

1. What is the use of %TYPE?

2. What is the use of %ROWTYPE?

3. Difference between %TYPE and %ROWTYPE?

Posted 2nd October 2014 by Unknown

0 Add a comment

SEP

29

BULK Exceptions
/************************************************************************

* Handling Exceptions in Bulk Operations *

* Documented on 29-SEP-14 04.35.35.980894 PM +05:30 *

* Document By : Murugappan Annamalai *

* Reference : http://www.dba-oracle.com/plsql/t_plsql_exceptions.htm *

************************************************************************/

CREATE TABLE bulk_tb (ran_num NUMBER NOT NULL);

--inserting data using bulk collect

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));


commit;

END;

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

200

TRUNCATE TABLE bulk_tb;

sample2.sql --without exception part

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;
v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

commit;

END;

/*

Error Message :

ORA-01400: cannot insert NULL into ("HR"."bulk_tb"."ran_num")

ORA-06512: at line 15

*/

sample2.sql --with exception part

DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;


v_dat num_data_typ := num_data_typ();

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

BEGIN

FORALL i IN v_dat.FIRST..v_dat.LAST

INSERT INTO bulk_tb VALUES(v_dat(i));

COMMIT;

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('Error while inserting bulk record '||SQLERRM);

END;

END;
SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

99

SQL%BULK_EXCEPTIONS(i).ERROR_INDEX

Holds the iteration (not the subscript) of the original FORALL statement that raised the
exception.

In sparsely populated collections,

the exception row must be found by looping through the original collection the correct
number of times.

SQL%BULK_EXCEPTIONS(i).ERROR_CODE

Holds the exceptions error code.

The total number of exceptions can be returned using the collections COUNT method,

which returns zero if no exceptions were raised. The save_exceptions.sql script,

a modified version of the handled_exception.sql script, demonstrates this functionality.


DECLARE

TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;

v_dat num_data_typ := num_data_typ();

v_ex_count NUMBER(4);

abort_ex EXCEPTION;

PRAGMA EXCEPTION_INIT(abort_ex, -24381);

BEGIN

FOR i in 1..200

LOOP

v_dat.EXTEND;

v_dat(v_dat.LAST) := i;

END LOOP;

v_dat(100) := NULL;

v_dat(150) := NULL;

/* will cause error while inserting data into bulk_tb

because of not null constraint */

EXECUTE IMMEDIATE 'TRUNCATE TABLE bulk_tb';

BEGIN

FORALL i IN v_dat.FIRST..v_dat.LAST SAVE EXCEPTIONS

INSERT INTO bulk_tb VALUES(v_dat(i));

COMMIT;

EXCEPTION
WHEN abort_ex THEN

v_ex_count := SQL%BULK_EXCEPTIONS.COUNT;

FOR i IN 1..v_ex_count LOOP

dbms_output.put_line('Error: ' || i ||' Array Index: ' || SQL


%BULK_EXCEPTIONS(i).error_index ||

' Message: ' || SQLERRM(SQL%BULK_EXCEPTIONS(i).ERROR_CODE));

END LOOP;

END;

END;

/*

Sample output:

Error: 1 Array Index: 100 Message: -1400: non-ORACLE exception

Error: 2 Array Index: 150 Message: -1400: non-ORACLE exception

*/

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

198
SAVE EXCEPTIONS clause being removed, in the above script now traps a different error number.

The output from this script is listed below.

/*

Sample output:

Error: 1 Array Index: 100 Message: -1400: non-ORACLE exception

*/

SELECT COUNT(*) FROM bulk_tb;

COUNT(*)

-------

99

SELECT COUNT(*) FROM bulk_tb;

DROP TABLE bulk_tb;

/
Posted 29th September 2014 by Unknown

0 Add a comment

SEP

29

Cursor - FOR UPDATE

/************************************************************************

* FOR UPDATE clause in oracle *

* Document By : Murugappan Annamalai *

************************************************************************/

create table prod_details(p_id VARCHAR2(30), P_name VARCHAR2(30));

BEGIN

--Inserting data into prod_details table

FOR i IN 1..50 LOOP

INSERT INTO prod_details VALUES(i,'pname'||i);

END LOOP;
commit;

END;

SELECT * FROM prod_details;

DECLARE

CURSOR PROD_DTLS_C IS

SELECT * FROM PROD_DETAILS T1 FOR UPDATE OF P_ID;

V_PID PROD_DETAILS.P_ID%TYPE;

V_PRDNAME PROD_DETAILS.P_NAME%TYPE;

BEGIN

OPEN PROD_DTLS_C;

LOOP

FETCH PROD_DTLS_C INTO V_PID, V_PRDNAME;

IF PROD_DTLS_C%NOTFOUND THEN

EXIT;

ELSE

UPDATE PROD_DETAILS P
SET P.P_ID = LPAD(P_ID, 10, 0)

WHERE CURRENT OF PROD_DTLS_C;

END IF;

END LOOP;

CLOSE PROD_DTLS_C;

COMMIT;

END;

select * from PROD_DETAILS;

TRUNCATE TABLE prod_details;

BEGIN

--Inserting data into prod_details table

FOR i IN 1..50 LOOP

INSERT INTO prod_details VALUES(i,'pname'||i);

END LOOP;

commit;

END;
DECLARE

CURSOR PROD_DTLS_C IS

SELECT * FROM PROD_DETAILS T1 FOR UPDATE OF P_ID;

V_PID PROD_DETAILS.P_ID%TYPE;

V_PRDNAME PROD_DETAILS.P_NAME%TYPE;

BEGIN

OPEN PROD_DTLS_C;

LOOP

FETCH PROD_DTLS_C INTO V_PID, V_PRDNAME;

IF PROD_DTLS_C%NOTFOUND THEN

EXIT;

ELSE

UPDATE PROD_DETAILS P

SET P.P_ID = LPAD(P_ID, 10, 0)

WHERE CURRENT OF PROD_DTLS_C;

END IF;

COMMIT;

END LOOP;
CLOSE PROD_DTLS_C;

--COMMIT;

END;

select * from PROD_DETAILS;

Posted 29th September 2014 by Unknown

0 Add a comment

MAY

28

Escape Sequence in Oracle

Escape special characters when writing SQL queries

--to include single '

SELECT 'Steven's salary is more than 50k INR' AS "SAL_DETAILS"

FROM Dual;
ORA-01756 : quoted string not properly terminated

SELECT 'Steven''s salary is more than 50k INR' AS "SAL_DETAILS"

FROM Dual;

SAL_DETAILS

---------------------------------------

Steven's salary is more than 50k INR

--to include double '

SELECT 'You can print double quot ('''') in oracle' "Info"

FROM Dual;

Info

---------------------------------------

You can print double quot ('') in oracle

SELECT q'[some test ' some test ' some text ']' AS "In 10g"

FROM dual;
In 10g

------------------------------------

some test ' some test ' some text '

--Escape wild card characters ( _ and % )

The LIKE keyword allows for string searches.

The '_' wild card character is used to match exactly one character

While '%' is used to match zero or more occurrences of any characters.

These characters can be escaped in SQL as follows.

WITH mail_ids AS

SELECT 'an.murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an_murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an%murugappan@gmail.com' mail FROM Dual

SELECT * FROM mail_ids

WHERE mail LIKE '__$_%' ESCAPE '$';


mail

----------------------------------

an_murugappan@gmail.com

WITH mail_ids AS

SELECT 'an.murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an_murugappan@gmail.com' mail FROM Dual

UNION

SELECT 'an%murugappan@gmail.com' mail FROM Dual

SELECT * FROM mail_ids

WHERE mail LIKE '__/%%' ESCAPE '/';

mail

----------------------------------

an%murugappan@gmail.com

Escape ampersand (&) characters in SQL*Plus


SQL> select '&a' FROM dual;

'23'

----

23

SQL> SET ESCAPE '\'

SQL> select '\&a' FROM dual;

'&A'

----

&a

SQL> SET SCAN OFF;

SQL> select '&a' FROM dual;

'&A'

----

&a

SQL> SET SCAN ON;

SQL> select '&a' FROM dual;

'45'

----
45

Posted 28th May 2014 by Unknown

0 Add a comment

MAY

28

Data Manipulation Language

Data Manipulation Language (DML) statements are used for managing data within schema
objects. Some examples:

INSERT - insert data into a table

UPDATE - updates existing data within a table

DELETE - deletes all records from a table, the space for the records remain

MERGE - UPSERT operation (insert or update)

CREATE TABLE prod_details

prod_id NUMBER(4) ,
prod_name VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

Deliver_dt DATE DEFAULT SYSDATE+3 ,

comments VARCHAR2(300)

);

SELECT * FROM prod_details;

no_data_found

INSERT

INSERT INTO prod_details(prod_id,prod_name,order_dt,deliver_dt,comments)

VALUES(100,'Apple iphone 5s','21-May-14','24-May-14','Color : Black');

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

---------------------------------------------------------------------------

--Inserting records with out mentioning column name


INSERT INTO prod_details

VALUES(101,'Samsung Galaxy III','20-Aug-14','23-Aug-14','Color : White');

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

---------------------------------------------------------------------------

--Inserting selective number of values

INSERT INTO prod_details

VALUES(103,'Moto X','11-May-14','13-May-14');

ORA-00947 : not enough values

--While inserting selective number of values mentioning column name is compulsory.

INSERT INTO prod_details (prod_id,prod_name,order_dt,deliver_dt)

VALUES(103,'Moto X','11-May-14','13-May-14');
SELECT * FROM prod_details;

--------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

--------------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

--------------------------------------------------------------------------------

--Inserting NULL value.

--If you want to insert NULL value you can ignore that column at the time of inserting

--or we can use NULL keyword to insert NULL.

INSERT INTO prod_details

VALUES(104,'Moto G','19-May-14','22-May-14',NULL);

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black


101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Noto G 5/19/2014 5/22/2014

---------------------------------------------------------------------------

--if you are not providing values for order_dt and deliver_dt column default value can be taken.

INSERT INTO prod_details(prod_id,prod_name,comments)

VALUES(105,'Nokia Lumis 720p','Color : Red');

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

----------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Moto G 5/19/2014 5/22/2014

105 Nokia Lumis 720p 5/26/2014 5/29/2014 Color : Red

---------------------------------------------------------------------------

--Inserting data by using sub query


CREATE TABLE test_tab (id NUMBER, Name VARCHAR2(30));

INSERT INTO test_tab VALUES(1,'Name1');

INSERT INTO test_tab VALUES(2,'Name2');

INSERT INTO test_tab VALUES(3,'Name3');

SELECT COUNT(*) FROM test_tab;

COUNT(*)

-------

--creating table by using sub query (with out data)

CREATE TABLE ins_chk

SELECT * FROM test_tab

WHERE id = 900;

SELECT COUNT(*) FROM ins_chk;


COUNT(*)

-------

--Inserting data by using sub query

--copying data from test_tab to ins_chk

INSERT INTO ins_chk (SELECT * FROM test_tab);

3 rows inserted in 0.047 seconds.

SELECT COUNT(*) FROM ins_chk;

COUNT(*)

-------

DROP TABLE test_tab;

DROP TABLE ins_chk;

UPDATE
Syntax :

UPDATE table_name

SET column1_name = column1_value,

column2_name = column2_value,

column2_name = column3_value,

columnn_name = columnn_value

WHERE condition(s);

SELECT * FROM prod_details;

---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

----------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black

101 Samsung Galaxy III 8/20/2014 8/23/2014 Color : White

103 Moto X 5/11/2014 5/24/2014

104 Moto G 5/19/2014 5/22/2014

105 Nokia Lumis 720p 5/26/2014 5/29/2014 Color : Red

---------------------------------------------------------------------------

UPDATE prod_details ps

SET ps.prod_name = 'iphone 5s'


WHERE ps.prod_id = 100;

1 row updated in 0.031 seconds

SELECT *

FROM prod_details ps

WHERE ps.prod_id = 100;

--------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

--------------------------------------------------------------------

100 iphone 5s 5/21/2014 5/24/2014 Color : Black

--------------------------------------------------------------------

--update statement with out condition

--If you try to execute update statement without condition it'll update all the records inside the
table.

UPDATE prod_details ps

SET ps.comments = 'None';

5 row updated in 0.031 seconds

SELECT *

FROM prod_details ps;


---------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------

100 Apple iphone 5s 5/21/2014 5/24/2014 None

101 Samsung Galaxy III 8/20/2014 8/23/2014 None

103 Moto X 5/11/2014 5/24/2014 None

104 Moto G 5/19/2014 5/22/2014 None

105 Nokia Lumis 720p 5/26/2014 5/29/2014 None

----------------------------------------------------------------------

--if your update text contain ' means you can use following metnod (use '')

UPDATE prod_details ps

SET ps.comments = 'Some product''s are not available'

WHERE ps.prod_id = 100;

1 row updated in 0.031 seconds

SELECT *

FROM prod_details ps

WHERE ps.prod_id = 100;

------------------------------------------------------------------------------------
PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

------------------------------------------------------------------------------------

100 iphone 5s 5/21/2014 5/24/2014 Some product's are not available

------------------------------------------------------------------------------------

DELETE

Syntax:

DELETE FROM table_name

WHERE condition(s);

DELETE FROM prod_details

WHERE prod_id IN (104, 105);

2 row(S) deleted in 0.032 seconds

SELECT *

FROM prod_details ps;

---------------------------------------------------------------------------------------

PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS

---------------------------------------------------------------------------------------
100 Apple iphone 5s 5/21/2014 5/24/2014 Some product's are not available

101 Samsung Galaxy III 8/20/2014 8/23/2014 None

103 Moto X 5/11/2014 5/24/2014 None

---------------------------------------------------------------------------------------

DELETE FROM prod_details;

3 row(s) deleted in 0.062 seconds.

SELECT * FROM prod_details;

no rows selected.

DROP TABLE prod_details;

MERGE = Insert + Update

-- will update soon.

Posted 28th May 2014 by Unknown

0 Add a comment
MAY

28

Data Define Language

Data Definition Language (DDL) statements are used to define the database structure or schema.

Some examples:

CREATE - to create objects in the database.

ALTER - alters the structure of the database.

ADD

RENAME

MODIFY

DROP

DROP - delete objects from the database

TRUNCATE - remove all records from a table,

including all spaces allocated for the records are removed.

COMMENT - add comments to the data dictionary.

RENAME - rename an object.

Creating Table
--------------------------------------------------------------------------

Data Types Size Default Size Explanation

--------------------------------------------------------------------------

NUMBER(P,S) P: 1 to 38 we can store number between 0-9

S: -84 to 127

VARCHAR2 4000 Bytes we can store 0-9, a-z, A-Z and special characters

CHAR 2000 Bytes 1

DATE 7 Used to store Date

TIMESTAMP Includes year, month, day, hour, minute, and seconds.

LONG 2 GB Only one long column is allowed in a table.

We can't use this column in ORDER BY clause.

CLOB 4 GB Character Large Object

BLOB Binary Larger Object

--------------------------------------------------------------------------

CREATE

ALTER : ADD RENAME MODIFY DROP RENAME

RENAME

DROP

TRUNCATE

--creating table

CREATE TABLE friends_details_tb


(

Name VARCHAR2(30) ,

Phone NUMBER(10) ,

Gender CHAR ,

dob DATE ,

other_details LONG ,

make_dtm TIMESTAMP

);

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

-----------------------------

--maximum you can keep 255 columns in a table


ALTER : Colum level operations

ADD RENAME MODIFY DROP

ADD : Used to add a column after the table hase been created

ALTER TABLE friends_details_tb

ADD email VARCHAR2(30);

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

EMAIL VARCHAR2(30)

-----------------------------

--adding multiple columns by using single ALTER statement


SYNTAX

ALTER TABLE friends_details_tb

ADD (

column_1 Data_type(size),

column_2 Data_type(size),

column_3 Data_type(size),

column_4 Data_type(size)

);

RENAME : Used to Rename a column

ALTER TABLE friends_details_tb

RENAME COLUMN email TO email_id;

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)
PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS LONG

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

MODIFY : Used to change the data type or size of the data type.

ALTER TABLE friends_details_tb

MODIFY other_details CLOB;

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

OTHER_DETAILS CLOB
MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

--Modifying multiple columns at a time

ALTER TABLE friends_details_tb

MODIFY ( column_name_1 old_datatype(new_size),

column_name_2 new_datatype(old_size),

column_name_3 new_datatype(new_size)

);

DROP : Used to drop the column after the table has been created.

ALTER TABLE friends_details_tb

DROP COLUMN other_details;

DESC friends_details_tb;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)
PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE

MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

RENAME : Used to Rename a particular table.

SYNTAX

RENAME old_table_name TO new_table_name;

RENAME friends_details_tb TO fnd_det;

DESCRIBE fnd_det;

-----------------------------

NAME TYPE

-----------------------------

NAME VARCHAR2(30)

PHONE NUMBER(10)

GENDER CHAR(1)

DOB DATE
MAKE_DTM TIMESTAMP(6)

EMAIL_ID VARCHAR2(30)

-----------------------------

TRUNCATE : Used to remove the entire content of the table (not a structure)

SYNTAX

TRUNCATE TABLE table_name;

TRUNCATE TABLE fnd_det;

DROP : Used to drop the tabel (Data + stucture of the table get removed from the database )

DROP TABLE fnd_det;

*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

Posted 28th May 2014 by Unknown

0 Add a comment
MAY

28

Statements in Oracle

Data Definition Language (DDL)

DDL statements are used to define the database structure or schema. Some examples:

CREATE - to create objects in the database

ALTER - alters the structure of the database

ADD

RENAME

MODIFY

DROP

DROP - delete objects from the database

TRUNCATE - remove all records from a table,

including all spaces allocated for the records are removed

RENAME - rename an object

Data Manipulation Language (DML)

DML statements are used for managing data within schema objects. Some examples:
INSERT - insert data into a table

UPDATE - updates existing data within a table

DELETE - deletes all records from a table, the space for the records remain

MERGE - UPSERT operation (insert or update)

Data Control Language (DCL)

DCL statements. Some examples:

GRANT - gives users access privileges to database

REVOKE - withdraw access privileges given with the GRANT command

Transaction Control (TCL)

TCL statements are used to manage the changes made by DML statements. It allows
statements to be grouped together into logical transactions.

COMMIT - save work done

SAVEPOINT - identify a point in a transaction to which you can later roll back

ROLLBACK - restore database to original since the last COMMIT

Posted 28th May 2014 by Unknown


0 Add a comment

MAY

19

DECODE and CASE statement

CREATE TABLE students (

roll_no NUMBER(4) ,

Name VARCHAR2(30) ,

dept_cd VARCHAR2(20) ,

total_marks NUMBER(3)

);

BEGIN

INSERT INTO students VALUES (2000,'Rahul','CSE',480);

INSERT INTO students VALUES (2001,'Bala','IT', 390);

INSERT INTO students VALUES (2002,'Ramesh','CSE',250);

INSERT INTO students VALUES (2003,'Karthi','EEE',185);

INSERT INTO students VALUES (2004,'Ravi','IT',345);

END;

/
SELECT * FROM students;

DECODE

Decode is a function. Its a Oracle one.

Works like IF-THEN-ELSE.

You can use DECODE only in SELECT clause.

In DECODE you can include 255 things include Exep, search , result and default value.

Example

SELECT roll_no,

NAME,

dept_cd,

DECODE(dept_cd,

'CSE',

'Computer Science and Engineering',

'IT',

'Information Technology',

'Default Value') AS "DEPARTMENT NAME"

FROM students;

Sample Output

------------------------------------------------------------
ROLL_NO NAME DEPT_CD DEPARTMENT NAME

------------------------------------------------------------

2000 Rahul CSE Computer Science and Engineering

2001 Bala IT Information Technology

2002 Ramesh CSE Computer Science and Engineering

2003 Karthi EEE Default Value

2004 Ravi IT Information Technology

------------------------------------------------------------

CASE

CASE is an expression. Its a ANSI standard.

Compare to DECODE case will be more faster.

Example

SELECT roll_no,

NAME,

dept_cd,

total_marks,

CASE

WHEN total_marks > 500 THEN

'A Grade'

WHEN total_marks > 400 THEN

'B Grade'

WHEN total_marks > 300 THEN


'C Grade'

ELSE

'U Grade'

END AS "GRADE"

FROM students;

-----------------------------------------------

ROLL_NO NAME DEPT_CD TOTAL_MARKS GRADE

-----------------------------------------------

2000 Rahul CSE 480 B Grade

2001 Bala IT 390 C Grade

2002 Ramesh CSE 250 U Grade

2003 Karthi EEE 185 U Grade

2004 Ravi IT 345 C Grade

-----------------------------------------------

Interview Questions:

What is DECODE?

What is CASE?

Difference between CASE and DECODE? Which one is faster?

Posted 19th May 2014 by Unknown


0 Add a comment

MAY

19

Sub Query

Query with in another query

1. Single Row sub query

2. Multi row Sub query

select * from employees;

Want to fetch the person Who are all getting salary more than Neena's salary ?

Neena's Salary : 17000

Select First_name, salary

From Employees

Where salary > 17000;

--change in Neena's salary won't work for the above query.


Select salary From Employees

Where First_name = 'Neena';

Sub Query :

Select First_name, salary

From Employees

Where salary > (

Select salary From Employees

Where First_name = 'Neena'

);

Select * from employees;

Select salary From Employees

Where First_name = 'Alexander';

Sub Query Returns one value it is called as Single row sub query

Sub Query Returns more than one value it is called as Multi row sub query
Single row sub query operators :

> < >= <= = <>

Multiple Row Sub query operators :

IN ALL ANY

Who are all getting salary more than the average salary?

Select

First_name,

Salary

From

Employees

WHERE

Salary > (

SELECT Round(avg(salary),0)

FROM Employees

);

Multiple Row Sub query (In ANY ALL)


Select First_name,Department_id, salary

From Employees

Where salary in(

Select Salary From Employees

Where First_name = 'Alexander'

);

Any : Minimum Value will be taken (3100)

Select First_name,Department_id, salary

From Employees

Where salary > ANY(

Select Salary From Employees

Where First_name = 'Alexander'

);

All : Maximum Value will be taken (9000)

Select First_name,Department_id, salary

From Employees

Where salary > All(

Select Salary From Employees

Where First_name = 'Alexander'

);
We can use sub query in all the classes except Group by and order by class.

Select

From

Where

-----------Group by

having

-----------Order by

SELECT

( Select Count(*) from Employees Where Department_id = 90 )Executive,

( Select Count(*) from Employees Where Department_id = 60 ) IT,

( Select Count(*) from Employees Where Department_id = 10 ) Administration,

( Select Count(*) from Employees Where Department_id = 100) Finance

FROM

Dual;

Select Min(salary) From Employees;

Select Min(salary) from

Select * from Employees


Where Department_id = 60

);

What is INLINE VIEW?

If u use sub query in From it is call it is as INLINE VIEW.

Intermediate result set

Correlated sub query

SELECT employee_number, name

FROM employees Bob

WHERE salary > (

SELECT AVG(salary)

FROM employees

WHERE department = Bob.department

);

Posted 19th May 2014 by Unknown

0 Add a comment
Loading

Dynamic Views theme. Powered by Blogger.

Sql Interview Questions

Make sure that you guys learn all the topics before go through the Interview questions

Basic Questions:

Which Version of Oracle are you using?

What is the meaning of i, g and c in oracle version?

What is Schema in Oracle?

What is Schema Objects?

What is dual table in oracle?

What are all the Schema objects available in oracle?

What is SQL?

What is Data Dictionary table in oracle?

How to select data from other schema?

How to Select Unique Records from the particular column? or

How To select distinct records from the particular column.

How to view the structure of the Table?

Which Data Dictionary table contain Table information?

Which Data Dictionary Table contain information about all the objects in database?
Click here to learn Retriving data using SELECT statement

Restriction and Sorting:

What are all the operators available in oracle?

Difference between IN and EXISTS ? Which one is more Faster? Why?

Which operator is used for pattern matching or to do wildcard search?

Write a query to display all the name which starts with S.

Write a query to display all the name starts with S and ends with character n.

Write a query to display all the employees who are all working for department 90 and their
name must starts with S.

Display all the job id which contain _ (underscore) as 3rd character.

Write a query to print all the first_name which contains five characters.

Write a query to display all the employees who are all working in department 10,20,50 and 90.

Write a query to display first name, salary and department id of the employees who are all not
working for 10,20,50 and 90.

Display all the employees who are all hired in year 1994.

Write a query to display who are all getting salary between 5000 and 7000.

Display First_name, salary, department_id and manager_id of the employee who don't have
manager.

Display all the records in employees table and sort the first name in ascending order.

Display first name, department id and salary from employees table and sort the records ( sort
department id in ascending order and salary in descending order)

What is the default ordering of an ORDER BY clause in a SELECT statement .

Click here to learn Restriction and sorting

Choose a job you LOVE and you will never have to work a day in your life

- Confucius

Functions

What are the types of functions available in oracle.


Difference between single row function and multiple row function.

List out all the case and character functions.

Display first three characters from first name.

Display last two character from last name.

Display all the first name and position of a in that name (first occurrence of a).

Display all the first name and position of a in that name (second occurrence of a)

Display all the name which contain two or more number of a 's in the first name.

Difference between SUBSTR and INSTR function.

Difference between REPLACE and TRANSLATE function.

Difference between LPAD and RPAD.

Difference between LTRIM and RTRIM.

Display all the first name and its length.

List out all the number functions in oracle.

List out all the Date functions in oracle?

Display all the first name and their total year of experience. rename first name column name as
name and second column name as Year of Exep.

How to display months between two given date.

Write a query to display today's date.

Write a query to display the date after 3 months from today.

Display last date of the current month.

Display the up coming Wednesday date.

Which date function return number as output.

What are all the type conversion functions available.

How to convert date into character.

How to convert character in to date.

What is the use of general function.


Explain NVL, NVL2 , NULLIF and COALESCE function with example.

What are all the aggregate functions available in oracle.

Write a query to select maximum salary from employees table.

Write a query to select second maximum salary from employees table.

Display average salary in the department 90.

Display number of employees working in department 90 and 60.

Display all the department id and its maximum salary.

Display all the department id and number of employees working in that department.

Display all the department id and salary allocated for that department.

Display all the department id and number of employees working in that department. Total no
employees working for the particular department must be greater than 30.

Difference between WHERE clause and HAVING clause.

Difference between DECODE and CASE.

How to update all Male to Female and all female to Male by using single update statement?

Joins:

What is joins? What are all the difference types of joins available?

Explain outer join and its types with example.

What is Self Join and why is it required?

What is the difference between inner and outer join? Explain with example.

What is a Cartesian product.

If I try to Fetch data from 25 tables. How many number of join condition required?

Click here to learn Joins

Sub Queries:

What is a sub query? What are all the types of sub query?

List out the operators of single row and multiple row sub query.

Difference between single row and multiple row sub query.


What is Inline view?

Write a query to display all the employees who are all getting salary more than the average
salary of the department 60.

What is cor related sub query?

Write a query to display all the employees who are all getting salary more than the average
salary of the their department.

Write a query to display all the employees who are all getting salary more than their manager
salary.

What are the advantages and disadvantages of using a sub query?

How to rewrite joins by using sub query? Give example.

DDL, DML, DCL and DCL statements:

List out all the DDL statements.

What are all the data types available in oracle.

Difference between VARCHAR2 and CHAR data type.

How to create table in oracle.

How to create table with DEFAULT option.

How to copy the structure of particular table by using sub query? ( With data)

How to copy the structure of particular table by using sub query? ( With out data)

What is the use of DROP option in the ALTER TABLE command.

How to add the column after the table has been created?

How to rename the particular column in a table?

How to change the data type of the particular column after the table has been created.

How to rename the table.

How to drop the table?

How to truncate the table?

What are all the DML statements available?

How to INSERT records in to selective no of columns?


How to insert data by using sub query?

How to insert all the data from table X to table Y?

How to update more than one column at a time.

How to delete all the employees working in department 30.

If we ignore WHERE clause in UPDATE statement what ll happen?

If we ignore WHERE clause in DELETE statement what will happen?

Difference between DELETE, TRUNCATE and DROP.

What is the use of MERGE statement? Explain it with syntax.

What are all the Transaction Control Language available?

A table contain list of students record with their gender details. Write a update statement to
update all the male in to female and female into male.

Constraints:

What are all the type of constraint available in oracle?

Difference between PRIMARY KEY and UNIQUE key.

Difference between PRIMARY KEY ans FOREIGN KEY.

Difference between UNIQUE key and FOREIGN KEY.

Write a syntax to create FOREIGN constraint.

How to create constraint after the table has been created?

How to enable and disable a constraint.

Which data dictionary table contain information about constraints?

Explain ON DELETE CASCADE and ON DELETE SET NULL.

Views:

What is View?

What are are all the different types of views?

View contain data or not?

Which Data Dictionary table contain View information?


Is it possible to create view with out base table?

What is a use of view WITH CHECK OPTION and WITH READ ONLY?

List out the advantage and disadvantage of views.

Is it possible to perform DML operation on view?

How to perform insert operation on complex view?

Index:

What is INDEX?

When to create Index and when not to create index?

What are are all the types of index available?

How to enable and disable index?

Which Data Dictionary table contain information about Indexes.

Pseudo columns and sequences:

How to select first 5 records from a table?

What are all the Pseudo columns available?

Write a query to find out nth maximum salary?

While creating a sequence, what does cache and nocache options mean?

How do we set the LASTVALUE value in an Oracle Sequence?

How to Recompile the Procedure and Function?

Synonyms:

How to create synonyms?

Explain Private and public Synonym.

Which Data Dictionary Table contain information about Sequences?

Set operators:
What is the difference between JOIN and UNION?

What is the difference between UNION and UNION ALL?

What is the difference among UNION, MINUS and INTERSECT?

What are all the restriction we need to follow while using SET OPERATORS.

Analytical Functions:

What are the differences among ROWNUM, RANK and DENSE_RANK?

Explain LEAD and LAG Function.

Difference Between Questions in SQL:

Difference between IN and EXISTS ? Which one is more Faster? Why?

Difference between SUBSTR and INSTR function.

Difference between REPLACE and TRANSLATE function.

Difference between LPAD and RPAD.

Difference between LTRIM and RTRIM.

Difference between WHERE clause and HAVING clause.

Difference between DECODE and CASE.

What is the difference between inner and outer join? Explain with example.

Difference between single row and multiple row sub query.

Difference between DELETE, TRUNCATE and DROP.

Difference between PRIMARY KEY and UNIQUE key.

Difference between PRIMARY KEY ans FOREIGN KEY.

Difference between UNIQUE key and FOREIGN KEY.

What is the difference between JOIN and UNION?

What is the difference between UNION and UNION ALL?

What is the difference among UNION, MINUS and INTERSECT?


Give your valuable feedback below :)

Oracle sql & Pl/sql

search

Home Sql and pl/sql Sql Interview Questions

JUL

20

INLINE view in Oracle with 12c New Features

Named sub Query in FROM clause is call it as INLINE VIEW.

Oracle process a inline view faster than sub query

Inline View in Oracle

--Query to display all the employees who are all getting salary more than their department
average salary
SELECT First_name

, last_name

, salary

, department_id

FROM employees a , ( SELECT b.department_id

, AVG(b.salary) avg_sal

FROM employees b

GROUP BY b.department_id

)b

WHERE a.department_id = b.department_id

AND a.salary > b.avg_salary;

Display all the customer who have placed more number of orders by using INLINE view

CREATE TABLE customer_order_det_tb

( custm_id NUMBER ,

custm_nm VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDA

Sql Interview Questions


Make sure that you guys learn all the topics before go through the Interview questions

Basic Questions:

Which Version of Oracle are you using?

What is the meaning of i, g and c in oracle version?

What is Schema in Oracle?

What is Schema Objects?

What is dual table in oracle?

What are all the Schema objects available in oracle?

What is SQL?

What is Data Dictionary table in oracle?

How to select data from other schema?

How to Select Unique Records from the particular column? or

How To select distinct records from the particular column.

How to view the structure of the Table?

Which Data Dictionary table contain Table information?

Which Data Dictionary Table contain information about all the objects in database?

Click here to learn Retriving data using SELECT statement

Restriction and Sorting:

What are all the operators available in oracle?

Difference between IN and EXISTS ? Which one is more Faster? Why?

Which operator is used for pattern matching or to do wildcard search?

Write a query to display all the name which starts with S.

Write a query to display all the name starts with S and ends with character n.

Write a query to display all the employees who are all working for department 90 and their
name must starts with S.
Display all the job id which contain _ (underscore) as 3rd character.

Write a query to print all the first_name which contains five characters.

Write a query to display all the employees who are all working in department 10,20,50 and 90.

Write a query to display first name, salary and department id of the employees who are all not
working for 10,20,50 and 90.

Display all the employees who are all hired in year 1994.

Write a query to display who are all getting salary between 5000 and 7000.

Display First_name, salary, department_id and manager_id of the employee who don't have
manager.

Display all the records in employees table and sort the first name in ascending order.

Display first name, department id and salary from employees table and sort the records ( sort
department id in ascending order and salary in descending order)

What is the default ordering of an ORDER BY clause in a SELECT statement .

Click here to learn Restriction and sorting

Choose a job you LOVE and you will never have to work a day in your life

- Confucius

Functions

What are the types of functions available in oracle.

Difference between single row function and multiple row function.

List out all the case and character functions.

Display first three characters from first name.

Display last two character from last name.

Display all the first name and position of a in that name (first occurrence of a).

Display all the first name and position of a in that name (second occurrence of a)

Display all the name which contain two or more number of a 's in the first name.

Difference between SUBSTR and INSTR function.

Difference between REPLACE and TRANSLATE function.


Difference between LPAD and RPAD.

Difference between LTRIM and RTRIM.

Display all the first name and its length.

List out all the number functions in oracle.

List out all the Date functions in oracle?

Display all the first name and their total year of experience. rename first name column name as
name and second column name as Year of Exep.

How to display months between two given date.

Write a query to display today's date.

Write a query to display the date after 3 months from today.

Display last date of the current month.

Display the up coming Wednesday date.

Which date function return number as output.

What are all the type conversion functions available.

How to convert date into character.

How to convert character in to date.

What is the use of general function.

Explain NVL, NVL2 , NULLIF and COALESCE function with example.

What are all the aggregate functions available in oracle.

Write a query to select maximum salary from employees table.

Write a query to select second maximum salary from employees table.

Display average salary in the department 90.

Display number of employees working in department 90 and 60.

Display all the department id and its maximum salary.

Display all the department id and number of employees working in that department.

Display all the department id and salary allocated for that department.
Display all the department id and number of employees working in that department. Total no
employees working for the particular department must be greater than 30.

Difference between WHERE clause and HAVING clause.

Difference between DECODE and CASE.

How to update all Male to Female and all female to Male by using single update statement?

Joins:

What is joins? What are all the difference types of joins available?

Explain outer join and its types with example.

What is Self Join and why is it required?

What is the difference between inner and outer join? Explain with example.

What is a Cartesian product.

If I try to Fetch data from 25 tables. How many number of join condition required?

Click here to learn Joins

Sub Queries:

What is a sub query? What are all the types of sub query?

List out the operators of single row and multiple row sub query.

Difference between single row and multiple row sub query.

What is Inline view?

Write a query to display all the employees who are all getting salary more than the average
salary of the department 60.

What is cor related sub query?

Write a query to display all the employees who are all getting salary more than the average
salary of the their department.

Write a query to display all the employees who are all getting salary more than their manager
salary.

What are the advantages and disadvantages of using a sub query?

How to rewrite joins by using sub query? Give example.


DDL, DML, DCL and DCL statements:

List out all the DDL statements.

What are all the data types available in oracle.

Difference between VARCHAR2 and CHAR data type.

How to create table in oracle.

How to create table with DEFAULT option.

How to copy the structure of particular table by using sub query? ( With data)

How to copy the structure of particular table by using sub query? ( With out data)

What is the use of DROP option in the ALTER TABLE command.

How to add the column after the table has been created?

How to rename the particular column in a table?

How to change the data type of the particular column after the table has been created.

How to rename the table.

How to drop the table?

How to truncate the table?

What are all the DML statements available?

How to INSERT records in to selective no of columns?

How to insert data by using sub query?

How to insert all the data from table X to table Y?

How to update more than one column at a time.

How to delete all the employees working in department 30.

If we ignore WHERE clause in UPDATE statement what ll happen?

If we ignore WHERE clause in DELETE statement what will happen?

Difference between DELETE, TRUNCATE and DROP.

What is the use of MERGE statement? Explain it with syntax.


What are all the Transaction Control Language available?

A table contain list of students record with their gender details. Write a update statement to
update all the male in to female and female into male.

Constraints:

What are all the type of constraint available in oracle?

Difference between PRIMARY KEY and UNIQUE key.

Difference between PRIMARY KEY ans FOREIGN KEY.

Difference between UNIQUE key and FOREIGN KEY.

Write a syntax to create FOREIGN constraint.

How to create constraint after the table has been created?

How to enable and disable a constraint.

Which data dictionary table contain information about constraints?

Explain ON DELETE CASCADE and ON DELETE SET NULL.

Views:

What is View?

What are are all the different types of views?

View contain data or not?

Which Data Dictionary table contain View information?

Is it possible to create view with out base table?

What is a use of view WITH CHECK OPTION and WITH READ ONLY?

List out the advantage and disadvantage of views.

Is it possible to perform DML operation on view?

How to perform insert operation on complex view?

Index:

What is INDEX?

When to create Index and when not to create index?


What are are all the types of index available?

How to enable and disable index?

Which Data Dictionary table contain information about Indexes.

Pseudo columns and sequences:

How to select first 5 records from a table?

What are all the Pseudo columns available?

Write a query to find out nth maximum salary?

While creating a sequence, what does cache and nocache options mean?

How do we set the LASTVALUE value in an Oracle Sequence?

How to Recompile the Procedure and Function?

Synonyms:

How to create synonyms?

Explain Private and public Synonym.

Which Data Dictionary Table contain information about Sequences?

Set operators:

What is the difference between JOIN and UNION?

What is the difference between UNION and UNION ALL?

What is the difference among UNION, MINUS and INTERSECT?

What are all the restriction we need to follow while using SET OPERATORS.

Analytical Functions:

What are the differences among ROWNUM, RANK and DENSE_RANK?

Explain LEAD and LAG Function.


Difference Between Questions in SQL:

Difference between IN and EXISTS ? Which one is more Faster? Why?

Difference between SUBSTR and INSTR function.

Difference between REPLACE and TRANSLATE function.

Difference between LPAD and RPAD.

Difference between LTRIM and RTRIM.

Difference between WHERE clause and HAVING clause.

Difference between DECODE and CASE.

What is the difference between inner and outer join? Explain with example.

Difference between single row and multiple row sub query.

Difference between DELETE, TRUNCATE and DROP.

Difference between PRIMARY KEY and UNIQUE key.

Difference between PRIMARY KEY ans FOREIGN KEY.

Difference between UNIQUE key and FOREIGN KEY.

What is the difference between JOIN and UNION?

What is the difference between UNION and UNION ALL?

What is the difference among UNION, MINUS and INTERSECT?

Give your valuable feedback below :)


Oracle sql & Pl/sql

search

Home Sql and pl/sql Sql Interview Questions

JUL

20

INLINE view in Oracle with 12c New Features

Named sub Query in FROM clause is call it as INLINE VIEW.

Oracle process a inline view faster than sub query

Inline View in Oracle

--Query to display all the employees who are all getting salary more than their department
average salary

SELECT First_name

, last_name

, salary

, department_id

FROM employees a , ( SELECT b.department_id

, AVG(b.salary) avg_sal

FROM employees b
GROUP BY b.department_id

)b

WHERE a.department_id = b.department_id

AND a.salary > b.avg_salary;

Display all the customer who have placed more number of orders by using INLINE view

CREATE TABLE customer_order_det_tb

( custm_id NUMBER ,

custm_nm VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

ttl_amt NUMBER(7,2)

);

BEGIN

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '11-Jul-15' , 45000.00);

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '14-Jul-15' , 27000.00);

INSERT INTO customer_order_det_tb VALUES(101, 'Raja' , '13-Jul-15' , 17000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 34000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 38000.00);

COMMIT;

END;
SELECT c.*

FROM customer_order_det_tb c;

--------------------------------------------

custm_id custm_nm order_dt ttl_amt

--------------------------------------------

100 Murugappan 7/11/2015 45000.00

100 Murugappan 7/14/2015 27000.00

101 Raja 7/13/2015 17000.00

102 Ramesh 7/15/2015 34000.00

102 Ramesh 7/15/2015 38000.00

--------------------------------------------

--Writing a Quer to display all the customer who have placed maximum number of order

--Query #1 for inline view

SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC;

--------------------------------

custm_id custm_nm total_odr

--------------------------------
100 Murugappan 2

102 Ramesh 2

101 Raja 1

--------------------------------

--Query #2 for inline view

SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm;

----------

total_odr

----------

----------

Inline view to find all the customers who have placed maximum number of orders

/****************************************

Syntax

SELECT * FROM <query1> x, <query2> y

WHERE contition;

****************************************/
SELECT query1.* FROM

( SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC

) query1,

( SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm

) query2

WHERE query1.total_odr = query2.total_odr;

-------------------------------

custm_id custm_nm total_odr

-------------------------------

100 Murugappan 2

102 Ramesh 2

-------------------------------

DROP TABLE customer_order_det_tb;

--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT
SELECT first_name, salary

FROM ( SELECT first_name, salary

FROM employees e

WHERE job_id NOT IN ('SALESMAN','PRESIDENT')

ORDER BY salary DESC

WHERE ROWNUM < 4;

New Oracle 12c Inline view Syntax

LATERAL clause for In-line views

Allows for columns in the inline view to be accessed!!

Example :

--in 11g

SELECT * FROM employees e, (

SELECT *

FROM departments d

WHERE e.department_id = d.department_id);

ORA-0090: "E"."DEPARTMENT_ID": Invalid Identifier


--in 12c

SELECT * FROM employees e, LATERAL(

SELECT *

FROM departments d

WHERE e.department_id = d.department_id

);

--in 11g

WITH t

AS

( SELECT LEVEL a

FROM dual

CONNECT BY LEVEL <= 30)

SELECT *

FROM t, (SELECT *

FROM employees

WHERE department_id = t.a

);

ORA-00904: "T"."A": invalid Identifier

--in 12c

WITH t
AS

(SELECT LEVEL a FROM dual CONNECT BY LEVEL <= 30)

SELECT * FROM t,

LATERAL(SELECT *

FROM employees

WHERE department_id = t.a);

Hope you have enjoyed this little article

Feed backs are always Welcome :) (:

Posted 20th July 2015 by Unknown

0 Add a comment

JAN

23

Salary Related Questions in Oracle

--creating table

CREATE TABLE employee_data

(
eid NUMBER(4),

ename VARCHAR2(30),

depno NUMBER(3),

salary NUMBER(8)

);

BEGIN

--Inserting records

INSERT INTO employee_data VALUES(1000,'Name01',90,30000);

INSERT INTO employee_data VALUES(1001,'Name02',90,6000);

INSERT INTO employee_data VALUES(1002,'Name03',90,23000);

INSERT INTO employee_data VALUES(1003,'Name04',60,35000);

INSERT INTO employee_data VALUES(1004,'Name05',60,60000);

INSERT INTO employee_data VALUES(1005,'Name06',60,30000);

INSERT INTO employee_data VALUES(1006,'Name07',80,36000);

INSERT INTO employee_data VALUES(1007,'Name08',80,29000);

INSERT INTO employee_data VALUES(1008,'Name09',80,37000);

INSERT INTO employee_data VALUES(1009,'Name10',80,41000);

COMMIT;

END;

/
SELECT * FROM employee_data

ORDER BY salary DESC;

--query to find maximum salary from employee_data table

SELECT MAX(salary) FROM employee_data;

--query to find minimum salary from employee_data table

SELECT MIN(salary) FROM employee_data;

--query to find second maximum salary from employee_data table

SELECT MAX(salary)

FROM employee_data

WHERE salary NOT IN (SELECT MAX(salary)

FROM employee_data);

--query to select 5th maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)


WHERE rownum <= 5);

--query to select nth maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= &n);

--query to select all the details of the employee whose getting nth maximum salary

SELECT *

FROM (SELECT emp.*,

rownum rn

FROM (SELECT *

FROM employee_data

ORDER BY salary DESC) emp)

WHERE rn = 9;

--same query using row_numbr( ) function


SELECT *

FROM (SELECT emp.*,

row_number() over(ORDER BY salary) rank

FROM employee_data emp)

WHERE rank = 9;

--same query using rank( ) function

SELECT *

FROM (SELECT emp.*,

rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--same query using dense_rank( ) function

SELECT *

FROM (SELECT emp.*,

dense_rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--query to display display maximum salary in all the department


SELECT e.depno "Department id",

MAX(salary) "Maximum Salary"

FROM employee_data e

GROUP BY e.depno;

--query to display all the employees who are all getting salary more than average salary of the
company

SELECT e.* FROM employee_data e

WHERE salary > (SELECT AVG(salary) FROM employee_data);

--query to display all the employees who are all getting salary more than their department
average salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE department_id = OUT.department_id);

--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE employee_id = OUT.manager_id);

Documented By : Murugappan Annamalai

Posted on : 23-Jan-15 16:34:00 IST.

Hope you have enjoyed this little article

Feed backs are always welcome :)

Posted 23rd January 2015 by Unknown

7 View comments

JAN

22

Why prefer COALESCE over NVL


Documented By : Nimish Garg

I prefer using "COALESCE" over "NVL" is some of the scenarios. Last week One of my friend
asked me what is the advantage of using "COALESCE" where we can simply use "NVL". I simply
gave him the reply from Oracle Docs i.e. NVL lets you replace null (returned as a blank) with a
string in the results of a query and COALESCE returns the first non-null expr in the expression list.
Oracle Database uses short-circuit evaluation with "COALESCE".

He replied that he knows the difference, he knows that "COALESCE" can take multiple arguments
and so on. He was more interested in understanding "short-circuit evaluation" of "COALESCE"
and the scenarios where I prefer using "COALESCE" over "NVL".

To make him understand I created following function which takes One second in every execution
and simply returns '--null--' and executed 2 very similar queries one with NVL and other with
COALESCE.

SQL> create or replace function f_null return varchar2

2 is

3 begin

4 dbms_lock.sleep(1);

5 return '--null--';

6 end;

7 /

Function created.

Following are the queries which I used to demonstrate that NVL evaluates both arguments even
if the second argument is not used and COALESCE uses short-circuit evaluation i.e. it only
evaluates the arguments only if they are needed.

SQL> select e.empno, e.ename ename, nvl(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.
Elapsed: 00:00:14.01

SQL> select e.empno, e.ename ename, coalesce(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.
Elapsed: 00:00:01.01

Here we can see easily that the first query with NVL took 14+ seconds, one second for each
record even if the "f_null" value was used only in one record. On the contrary as mentioned in
Oracle Documentation "COALESCE" uses its "short-circuit evaluation" and "f_null" was called
only once and so second query took only One Second. "COALESCE" is certainly use less resources
than NVL.

Posted 22nd January 2015 by Unknown

0 Add a comment

DEC

21

Constraints

It Enforce Rule On Table

We can create constraint at the time of Creating Table

1. Column Level Declaration

2. Table Level Declaration


1. We can provide own name.

Format : [part_of_project_name-table_name-column_name-constraint_type]

Example : gmind_emp_id_pk _uk _ck _f

2. system name name

Format : sys_cn

Example : SYS_C405323

We can create constraint after the table has been created

Types

Primary Key

Not allowed Null value

Not allowed you to enter duplicate value

Ex : Employee_id, Student_id

Unique Key
allowed Null value

Not allowed you to enter duplicate value

Ex : Contact_no, email

Foreign Key

It will allowed you to enter NULL and Duplicate value.

c1(pk) : 1 2 3

c2(f) : 1 1 2 3 4 Not allowed

Allowed you to enter duplicate value and null value

Not Null

It will not allowed you to enter null value

Check

You can check your own condition

Simple Table for understanding


------------------------------------

Duplicate NULL

------------------------------------

Primary Key X X

Unique Key X Allowed

Foreign Key Allowed Allowed

------------------------------------

creating table with all constraint type

Create table my_stu_details

S_id Number(2),

S_name Varchar2(30) Not Null, --SYS_Cn

s_mail Varchar2(30),

s_gender char(1),

s_did Number(3),

Constraint my_stu_sid_pk PRIMARY KEY (s_id),

constraint my_stu_mail_uk UNIQUE (s_mail) ,

Constraint my_stu_gen_ck CHECK (s_gender IN ('M', 'F', 'm', 'f')),

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

);
DESC my_stu_details;

------------------------------------

Name Type Nullable

------------------------------------

S_ID NUMBER(2)

S_NAME VARCHAR2(30)

S_MAIL VARCHAR2(30) Y

S_GENDER CHAR(1) Y

S_DID NUMBER(3) Y

------------------------------------

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name1' , 'name1@gmail.com' , 'm' , 60 );

Select * from my_stu_details;

Validating Primary Key


Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-00001: unique constraint (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (NULL, 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-01400: cannot insert NULL into (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (2 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

Validating NOT NULL Constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , NULL , 'name3@gmail.com' , 'F' , 80 );

ORA-01400: cannot insert NULL into ("HR"."MY_STU_DETAILS"."S_NAME")


Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , 'Name3' , 'name3@gmail.com' , 'F' , 80 );

Select * from my_stu_details;

Validating Unique Key Constraint

--Duplicate Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , 'name3@gmail.com' , 'F' , 80 );

ORA-00001: unique constraint (HR.MY_STU_MAIL_UK) violated

--Null Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , null , 'M' , 70 );


Select * from my_stu_details;

Validating Check constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'j' , 70 );

ORA-02290: check constraint (HR.MY_STU_GEN_CK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'M' , 70 );

Select * from my_stu_details;

Validating Foreign Key

Select * from Departments;


Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 3 );

ORA-02291: integrity constraint (HR.MY_STU_DID_FK) violated - parent key not found

Departments table : parent table

my_stu_details : Child table

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

--------------------------------------------------------

s_id s_name s_mail s_gender s_did

--------------------------------------------------------

1 name1 name1@gmail.com m 60

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 M 70

5 Name5 name5@gmail.com M 70
6 Name6 name6@gmail.com F 90

--------------------------------------------------------

Deleting the Primary key value which is referred by Foreign Key

Select * from Departments;

DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID

------------------------------------------------------------

60 IT 103 1400 <---- Delete

-- don't execute this query

--Delete From Departments

--Where Department_id = 60;

1) ON DELETE SET NULL

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------
6 Name6 name6@gmail.com F 90

1 name1 name1@gmail.com m -

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

2) ON DELETE SET CASCADE

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

Syntax

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE CASCADE
Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE SET NULL

Constraint Related Data Dictionary Table information.

To view constraint Information

SELECT c.owner,

c.constraint_name,

c.constraint_type,

c.table_name,

c.r_constraint_name,

c.status

FROM user_constraints c

WHERE c.table_name = 'MY_STU_DETAILS';

------------------------------------------------------------------------------------

owner constraint_name constraint_type table_name r_constraint_name status

------------------------------------------------------------------------------------

HR SYS_C004023 C MY_STU_DETAILS ENABLED

HR MY_STU_GEN_CK C MY_STU_DETAILS ENABLED

HR MY_STU_SID_PK P MY_STU_DETAILS ENABLED


HR MY_STU_MAIL_UK U MY_STU_DETAILS ENABLED

HR MY_STU_DID_FK R MY_STU_DETAILS DEPT_ID_PK ENABLED

------------------------------------------------------------------------------------

To view constraint name with corresponding column name

SELECT * FROM user_cons_columns c

WHERE c.table_name = 'MY_STU_DETAILS';

-------------------------------------------------------------

owner constraint_name table_name column_name position

-------------------------------------------------------------

HR MY_STU_MAIL_UK MY_STU_DETAILS S_MAIL 1

HR MY_STU_SID_PK MY_STU_DETAILS S_ID 1

HR MY_STU_GEN_CK MY_STU_DETAILS S_GENDER

HR SYS_C004023 MY_STU_DETAILS S_NAME

HR MY_STU_DID_FK MY_STU_DETAILS S_DID 1

-------------------------------------------------------------

Creating Composite Primary Key


Creating Primary Key with more than one number of column

ALTER TABLE table_name

ADD CONSTRAINT constraint_name PRIMARY KEY(column1, column_2 , column3);

In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.

creating constraint after the table creation

ALTER TABLE table_name

ADD CONSTRAINT constraint_name CONSTRAINT_TYPE(column_name);

ALTER TABLE table_name

DROP CONSTRAINT constraint_name;

ALTER TABLE table_name

DROP PRIMARY KEY;

To drop related foreign key

ALTER TABLE table_name


DROP PRIMARY KEY CASCADE;

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name;

Disable constraint with related foreign key constraint

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name CASCADE;

ALTER TABLE table_name

ENABLE CONSTRAINT constraint_name;

Interview Questions

What are all the type of constraint available in oracle?

Difference between PRIMARY KEY and UNIQUE key.

Difference between PRIMARY KEY ans FOREIGN KEY.

Difference between UNIQUE key and FOREIGN KEY.

Is it possible to create tow primary key in single table.


Write a syntax to create FOREIGN constraint.

How to create constraint after the table has been created?

How to enable and disable a constraint.

Which data dictionary table contains information about constraints?

Which Data Dictionary table contains information about constraint with corresponding column
name?

What is composite primary key?

Explain ON DELETE CASCADE and ON DELETE SET NULL option.

~Thanks For Reading~

Post your valuable feedback below

Posted 21st December 2014 by Unknown

1 View comments

DEC

listagg in Oracle 11g

Oracle 11gR2 listagg built-in function allows for many table columns to be displayed within a
single row, a non-first-normal form display
Syntax :

listagg(column_value,'delimiter') WITHIN GROUP(ORDER BY column_name)

--Example 1:

CREATE TABLE test_ins(empid NUMBER,product VARCHAR2(30));

BEGIN

INSERT INTO test_ins VALUES( 101,'pendrive');

INSERT INTO test_ins VALUES( 102,'toy');

INSERT INTO test_ins VALUES( 101,'ipod');

INSERT INTO test_ins VALUES( 102,'hat');

INSERT INTO test_ins VALUES( 103,'cpu');

INSERT INTO test_ins VALUES( 104,'pen');

INSERT INTO test_ins VALUES( 104,'car');

INSERT INTO test_ins VALUES( 104,'mat');

INSERT INTO test_ins VALUES( 105,'tv');

INSERT INTO test_ins VALUES( 106,'laptop');

commit;

END;

SELECT * FROM test_ins;


SELECT empid "Employee",

listagg(product,

',') within

GROUP (ORDER BY empid) "Products"

FROM test_ins

GROUP BY empid;

-->-- Result set --<--

DROP TABLE test_ins;

-->-- Example 2
select department_id "Department id", listagg(first_name,', ') WITHIN GROUP(ORDER BY
employee_id) "Employees"

FROM employees

WHERE department_id IN (10,20,30,60)

GROUP BY department_id;

-->-- Result set --<--

Posted 4th December 2014 by Unknown

0 Add a comment

NOV

Condition and Looping Statement

IF

IF ELSE

Multiple IF ELSE

LOOP

FOR LOOP
WHILE LOOP

create table test_udt(id NUMBER, salary NUMBER);

BEGIN

INSERT INTO test_udt VALUES(001,23000);

INSERT INTO test_udt VALUES(002,43000);

INSERT INTO test_udt VALUES(003,78000);

INSERT INTO test_udt VALUES(004,25000);

INSERT INTO test_udt VALUES(005,26000);

INSERT INTO test_udt VALUES(006,90000);

Commit;

END;

select * from test_udt;

IF

DECLARE

v_salary NUMBER;

v_id NUMBER;
BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 1;

IF v_salary > 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

END IF;

commit;

END;

IF ELSE

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt
WHERE id = 2;

IF v_salary < 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

ELSE

UPDATE test_udt t

SET t.salary = v_salary+20007

WHERE t.id = v_id ;

END IF;

commit;

END;

--same example with less number of lines

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt
WHERE id = 2;

IF v_salary < 20000 THEN

v_salary := v_salary+10005;

ELSE

v_salary := v_salary+20007;

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

Multiple IF ELSIF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary
INTO v_id,v_salary

FROM test_udt

WHERE id = 3;

IF v_id = 1 THEN

v_salary := 1000;

dbms_output.put_line('1 inside');

ELSIF v_id = 2 THEN

v_salary := 2000;

dbms_output.put_line('2 inside');

ELSIF v_id = 3 THEN

v_salary := 3000;

dbms_output.put_line('3 inside');

ELSIF v_id = 4 THEN

v_salary := 4000;

dbms_output.put_line('4 inside');

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

/
select * from test_udt;

LOOP

--syntax

LOOP

--statements

--increment

--exit statement

END LOOP;

CREATE TABLE prod_details (pid VARCHAR2(3), pname VARCHAR2(30));

DECLARE

i NUMBER := 1;

x VARCHAR2(3);

BEGIN

LOOP

x := lpad(i,3,'0');

dbms_output.put_line('x value : '|| x);

INSERT INTO prod_details VALUES(i, 'Product '||i);

EXIT WHEN i >900;


i := i+1;

IF MOD(i,100) = 0 THEN

commit;

dbms_output.put_line('commit executed');

END IF;

END LOOP;

END;

SELECT * FROM prod_details ORDER BY 1;

DROP TABLE prod_details;

FOR LOOP

BEGIN

FOR I in 1..5

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

FOR LOOP - Reverse


BEGIN

FOR I in REVERSE 14..50

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

WHILE LOOP

DECLARE

i_val NUMBER:=0;

BEGIN

WHILE (i_val < 11)

LOOP

dbms_output.put_line('The value of I is '||i_val);

i_val := i_val + 1;

END LOOP;

END;

sample output:

The value of I is 0
The value of I is 1

The value of I is 2

The value of I is 3

The value of I is 4

The value of I is 5

The value of I is 6

The value of I is 7

The value of I is 8

The value of I is 9

The value of I is 10

Posted 8th November 2014 by Unknown

0 Add a comment

OCT

21

Bulk Collect

This is used for array fetches

With this you can retrieve multiple rows of data with a single round trip.

This reduces the number of context switches between the pl/sql and sql engines.

You can use bulk collect in both dynamic and static sql.

You can use bulk collect in select, fetch into and returning into clauses.
SQL engine automatically initializes and extends the collections you reference in the bulk
collect clause.

You can fetch into multiple collections with one column each.

You can use the limit clause of bulk collect to restrict the no of rows retrieved.

SELECT * FROM product_details;

-->-- Bulk collect in FETCH INTO --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;
END;

-->-- Bulk collect in SELECT clause --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

BEGIN

SELECT * BULK COLLECT INTO dta FROM product_details;

FOR i IN dta.FIRST .. dta.LAST LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- LIMIT in Bulk collect --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;


BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta LIMIT 30;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Multiple fetches in INTO clause --<--

SELECT * FROM product_details;

DECLARE

TYPE alldata_typ1 IS TABLE OF product_details.p_id%TYPE;

TYPE alldata_typ2 IS TABLE OF product_details.p_name%TYPE;

dta1 alldata_typ1;

dta2 alldata_typ2;

CURSOR proddt_cur IS

SELECT p_id, p_name FROM product_details;


BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta1, dta2;

CLOSE proddt_cur;

FOR i IN dta1.FIRST .. dta1.COUNT LOOP

dbms_output.put_line('Department Id : ' || dta1(i));

END LOOP;

FOR i IN dta2.FIRST .. dta2.COUNT LOOP

dbms_output.put_line('Department Name : ' || dta2(i));

END LOOP;

END;

DROP TABLE dep_details;

DROP TABLE product_details;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT
21

Ref Cursor

This is unconstrained cursor which will return different types depends upon the user input.

Ref cursors cannot be closed implicitly.

Ref cursor with return type is called strong cursor.

Ref cursor without return type is called weak cursor.

You can declare ref cursor type in package spec as well as body.

You can declare ref cursor types in local subprograms or anonymous blocks.

CREATE OR REPLACE PROCEDURE ref_c_sp(dep_det_c IN OUT SYS_REFCURSOR)

AS

BEGIN

OPEN dep_det_c

FOR

SELECT * FROM dep_details d;

END;

DECLARE

dep_det_c SYS_REFCURSOR;

tab_data dep_details%ROWTYPE;
BEGIN

ref_c_sp(dep_det_c);

LOOP

FETCH dep_det_c INTO tab_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department Name : '|| tab_data.d_name);

END LOOP;

CLOSE dep_det_c;

END;

/*sample output*/

Department Name : Admin

Department Name : HR

Department Name : Sales

Department Name : Marketing

DROP PROCEDURE ref_c_sp;

Posted 21st October 2014 by Unknown

0 Add a comment
OCT

21

Cursor

SQL Private work Area where the query get passed and executed.

Types

******

Implicit(SQL)

Explicit

-->-- advanced cursor types --<--

Parametrized Cursor

Ref Cursor

Implicit

********

ORACLE implicitly opens a cursor to process each SQL statement not associated with an
explicitly declared cursor.

PL/SQL lets you refer to the most recent implicit cursor as the SQL” cursor. So, although you
cannot use the OPEN,

FETCH, and CLOSE statements to control an implicit cursor, you can still use cursor attributes to
access information

about the most recently executed SQL statement.


Cursor Stages

**************

OPEN cursor_name

FETCH (with in loop)

CLOSE cursor_name

Explicit

The set of rows returned by a query can consist of zero, one, or multiple rows,

depending on how many rows meet your search criteria. When a query returns multiple rows,

you can explicitly define a cursor to process the rows. You use three commands to control the
cursor

Cursor Attributes

*****************

%FOUND

%NOTFOUND

%ISOPEN

%ROWCOUNT

%BULK_ROWCOUNT --<-- used to handle error while using bulk collection.

%BULK_EXCEPTIONS --<-- used to handle error while using bulk collection.

Cursor Declaration
DECLARE

CURSOR <cursor_name>

IS

<SELECT statement>

BEGIN

--> some stmt

END;

Cursor Loop

Loop

While Loop

For Loop

Cursor Clauses

Return

For update

Where current of

Bulk collect

-->-- creating table

create table product_details

(
p_id NUMBER,

p_name VARCHAR2(30),

p_order_dt DATE

);

-->-- Inserting data

BEGIN

FOR i IN 1 .. 75 LOOP

INSERT INTO product_details VALUES (i, 'prod_name_' || i, SYSDATE + i);

END LOOP;

commit;

END;

-->-- selecting data

SELECT * FROM product_details;

---------------------------------------------

p_id p_name p_order_dt

---------------------------------------------

1 prod_name_1 10/11/2014 3:48:32 PM

2 prod_name_2 10/12/2014 3:48:32 PM


3 prod_name_3 10/13/2014 3:48:32 PM

4 prod_name_4 10/14/2014 3:48:32 PM

5 prod_name_5 10/15/2014 3:48:32 PM

6 prod_name_6 10/16/2014 3:48:32 PM

7 prod_name_7 10/17/2014 3:48:32 PM

8 prod_name_8 10/18/2014 3:48:32 PM

9 prod_name_9 10/19/2014 3:48:32 PM

10 prod_name_10 10/20/2014 3:48:32 PM

11 prod_name_11 10/21/2014 3:48:32 PM

12 prod_name_12 10/22/2014 3:48:32 PM

13 prod_name_13 10/23/2014 3:48:32 PM

14 prod_name_14 10/24/2014 3:48:32 PM

15 prod_name_15 10/25/2014 3:48:32 PM

16 prod_name_16 10/26/2014 3:48:32 PM

17 prod_name_17 10/27/2014 3:48:32 PM

18 prod_name_18 10/28/2014 3:48:32 PM

19 prod_name_19 10/29/2014 3:48:32 PM

20 prod_name_20 10/30/2014 3:48:32 PM

---------------------------------------------

----------------------------------------------

Implicit Cursor

----------------------------------------------
--will update soon

----------------------------------------------

Explicit Cursor

----------------------------------------------

**********************************************

Processing cursor data by using LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND; --<-- if next record not found means control will
come out from the loop

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');


END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;
dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

EXIT WHEN prod_detail_cur%FOUND; --<-- if next record found means control will come
out from the loop

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur
INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )


prod_detail_cur cursor Already closed

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

-->-- CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;
dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor closed

**********************************************

Processing cursor data by using WHILE LOOP

**********************************************
DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

OPEN prod_detail_cur;

FETCH prod_detail_cur

INTO all_data;

WHILE prod_detail_cur%FOUND LOOP

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

FETCH prod_detail_cur

INTO all_data;

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )


Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

************************************************************

Processing cursor data by using FOR LOOP - CURSOR FOR LOOP

************************************************************

DECLARE

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

FOR i IN prod_detail_cur

LOOP

dbms_output.put_line('Product id : ' || i.p_id ||

' Product Name : ' || i.p_name ||

' ( Orderd on : ' || TRIM(i.p_order_dt) || ' )');

END LOOP;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )


Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

Parameterized Cursor

*********************

This was used when you are going to use the cursor in more than one place with different
values for the same where clause.

Cursor parameters must be in mode.

Cursor parameters may have default values.

The scope of cursor parameter is within the select statement.

CREATE TABLE dep_details(d_id NUMBER,d_name VARCHAR2(30), location_id NUMBER);

BEGIN

INSRT INTO dep_details VALUES(001,'Admin',1010);

INSRT INTO dep_details VALUES(002,'HR',1010);

INSRT INTO dep_details VALUES(003,'Sales',1020);

INSRT INTO dep_details VALUES(004,'Marketing',1020);

commit;
END;

SELECT * FROM dep_details;

----------------------------

d_id d_name location_id

----------------------------

1 Admin 1010

2 HR 1010

3 Sales 1020

4 Marketing 1020

----------------------------

DECLARE

-->--Declaring parameterized cursor

CURSOR dep_det_c(p_location_id NUMBER) IS

SELECT * FROM dep_details d WHERE d.location_id = p_location_id;

all_data dep_details%ROWTYPE;

BEGIN

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

OPEN dep_det_c(1010);

LOOP

FETCH dep_det_c
INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

-->-- opening same cursor with different input value

OPEN dep_det_c(1020);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

END;

/*sample output*/
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 1 Department Name : Admin

Department id : 2 Department Name : HR

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 3 Department Name : Sales

Department id : 4 Department Name : Marketing

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Handling Exception

Error Handling in oracle

ERROR

Any departure from the expected behavior of the system or program,

which stops the working of the system is an error.

Types : compile time error

Run time error


EXCEPTION

Any error or problem which one can handle and continue to work normally.

Handling Exception

When exception is raised, control passes to the exception section of the block.

i.e. EXCEPTION

WHEN name_of_exception THEN

Types : Pre Defined Exceptions

User Defined Exceptions

Predefined Exception

*********************

Oracle has predefined several exceptions that correspond to the most common oracle errors.

------------------------------------------------------------------------

Exception Oracle Error SQL Code Value

------------------------------------------------------------------------

ZERO_DIVIDE ORA-01476 -1476

NO_DATA_FOUND ORA-01403 +100

DUP_VAL_ON_INDEX ORA-00001 -1
TOO_MANY_ROWS ORA-01422 -1422

VALUE_ERROR ORA-06502 -6502

CURSOR_ALREADY_OPEN ORA-06511 -6511

OTHERS

------------------------------------------------------------------------

-->-- ZERO_DIVIDE --<--

Your program attempts to divide a number by zero.

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN ZERO_DIVIDE THEN

dbms_output.put_line('Divisor is equal to zero');

END;

-->-- NO_DATA_FOUND --<--

Single row SELECT returned no rows or your program referenced a deleted element in a nested
table

or an uninitialized element in an associative array (index-by table).


CREATE TABLE test_tb(id NUMBER PRIMARY KEY);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN NO_DATA_FOUND THEN

dbms_output.put_line('There is no data inside the table');

END;

-->-- DUP_VAL_ON_INDEX --<--

A program attempted to insert duplicate values in a column that is constrained by a unique


index.

INSERT INTO test_tb VALUES (1);

INSERT INTO test_tb VALUES (2);

commit;

BEGIN

INSERT INTO test_tb VALUES (2);


EXCEPTION

WHEN DUP_VAL_ON_INDEX THEN

dbms_output.put_line('Duplicate values are not allowed');

END;

-->-- TOO_MANY_ROWS --<--

Single row SELECT returned multiple rows.

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN TOO_MANY_ROWS THEN

dbms_output.put_line('Query returning more than one row');

END;

DROP TABLE test_tb;

-->-- VALUE_ERROR --<--


An arithmetic, conversion, truncation, or size constraint error occurred.

DECLARE

num1 NUMBER(2);

BEGIN

num1 := 345;

EXCEPTION

WHEN VALUE_ERROR THEN

dbms_output.put_line('check the size of the variable');

END;

-->-- CURSOR_ALREADY_OPEN --<--

A program attempted to open an already opened cursor.

CREATE TABLE emp(id NUMBER, name VARCHAR2(30));

BEGIN

INSERT INTO emp VALUES(1,'Name1');

INSERT INTO emp VALUES(2,'Name2');

INSERT INTO emp VALUES(3,'Name3');

INSERT INTO emp VALUES(4,'Name4');

COMMIT;
END;

SELECT * FROM emp;

DECLARE

cursor emp_c IS

SELECT * FROM emp;

all_data emp%ROWTYPE;

BEGIN

OPEN emp_c;

OPEN emp_c;

NULL;

CLOSE emp_c;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

END;

DROP TABLE emp;

-->-- OTHERS --<--

DECLARE
v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

WHEN OTHERS THEN

dbms_output.put_line('Some other error ' || SQLERRM);

END;

User Defined Exception

**********************

A user-defined exception is an error that is defined by the programmer.

User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,

exceptions have a type EXCEPTION and scope.

DECLARE

v_gender CHAR := '&gender';

gender_ex EXCEPTION;

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN


RAISE gender_ex;

END IF;

dbms_output.put_line('Gender : '||v_gender);

EXCEPTION

WHEN gender_ex THEN

dbms_output.put_line('Please Enter valid gender');

END;

create table test_insert (id NUMBER, Name VARCHAR2(30));

DECLARE

abort_ex EXCEPTION;

BEGIN

FOR i IN 1..100

LOOP

BEGIN

IF mod(i,10)=0 THEN

RAISE abort_ex;

END IF;

INSERT INTO test_insert VALUES(i, 'Name'||i);

EXCEPTION

WHEN abort_ex THEN

NULL;

END;
END LOOP;

COMMIT;

END;

SELECT * FROM test_insert;

DROP TABLE test_insert;

SQLERRM and SQLCODE

********************

SQLCODE returns the current error code, and SQLERRM returns the current error message
text;

For user-defined exception SQLCODE returns 1 and SQLERRM returns “user-defined


exception”.

SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.

CREATE TABLE test_tb (id NUMBER);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

dbms_output.put_line(v_id);
EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('SQLERRM : ' || SQLERRM);

dbms_output.put_line('SQLCODE : ' || SQLCODE);

END;

/*sample output*/

SQLERRM : ORA-01403: no data found

SQLCODE : 100

DROP TABLE test_tb;

PRAGMA EXCEPTION_INIT

*********************

Using this you can associate a named exception with a particular oracle error.

This gives you the ability to trap this error specifically, rather than via an OTHERS handler.

Syntax:

PRAGMA EXCEPTION_INIT(exception_name, oracle_error_number);

DECLARE
v_result NUMBER;

PRAGMA EXCEPTION_INIT(Invalid, -1476);

BEGIN

SELECT 453 / 0 INTO v_result FROM dual;

dbms_output.put_line('Result : ' || v_result);

EXCEPTION

WHEN INVALID THEN

dbms_output.put_line('Invalid Exception');

END;

RAISE_APPLICATION_ERROR

************************

You can use this built-in function to create your own error messages, which can be more
descriptive than named exceptions.

Error Number :

Oracle Error Range : From -00000 to -19999

User Error Range : From -20000 to -20999

DECLARE
v_gender CHAR := '&gender';

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE_APPLICATION_ERROR(-20003, 'Enter valid gender');

END IF;

dbms_output.put_line('Gender : ' || v_gender);

END;

Posted 21st October 2014 by Unknown

1 View comments

Loading

Dynamic Views theme. Powered by Blogger.

Sql Interview Questions


Make sure that you guys learn all the topics before go through the Interview questions

Basic Questions:

Which Version of Oracle are you using?

What is the meaning of i, g and c in oracle version?

What is Schema in Oracle?

What is Schema Objects?

What is dual table in oracle?

What are all the Schema objects available in oracle?

What is SQL?

What is Data Dictionary table in oracle?

How to select data from other schema?

How to Select Unique Records from the particular column? or

How To select distinct records from the particular column.

How to view the structure of the Table?

Which Data Dictionary table contain Table information?

Which Data Dictionary Table contain information about all the objects in database?

Click here to learn Retriving data using SELECT statement

Restriction and Sorting:

What are all the operators available in oracle?

Difference between IN and EXISTS ? Which one is more Faster? Why?

Which operator is used for pattern matching or to do wildcard search?

Write a query to display all the name which starts with S.

Write a query to display all the name starts with S and ends with character n.

Write a query to display all the employees who are all working for department 90 and their
name must starts with S.

Display all the job id which contain _ (underscore) as 3rd character.


Write a query to print all the first_name which contains five characters.

Write a query to display all the employees who are all working in department 10,20,50 and 90.

Write a query to display first name, salary and department id of the employees who are all not
working for 10,20,50 and 90.

Display all the employees who are all hired in year 1994.

Write a query to display who are all getting salary between 5000 and 7000.

Display First_name, salary, department_id and manager_id of the employee who don't have
manager.

Display all the records in employees table and sort the first name in ascending order.

Display first name, department id and salary from employees table and sort the records ( sort
department id in ascending order and salary in descending order)

What is the default ordering of an ORDER BY clause in a SELECT statement .

Click here to learn Restriction and sorting

Choose a job you LOVE and you will never have to work a day in your life

- Confucius

Functions

What are the types of functions available in oracle.

Difference between single row function and multiple row function.

List out all the case and character functions.

Display first three characters from first name.

Display last two character from last name.

Display all the first name and position of a in that name (first occurrence of a).

Display all the first name and position of a in that name (second occurrence of a)

Display all the name which contain two or more number of a 's in the first name.

Difference between SUBSTR and INSTR function.

Difference between REPLACE and TRANSLATE function.

Difference between LPAD and RPAD.


Difference between LTRIM and RTRIM.

Display all the first name and its length.

List out all the number functions in oracle.

List out all the Date functions in oracle?

Display all the first name and their total year of experience. rename first name column name as
name and second column name as Year of Exep.

How to display months between two given date.

Write a query to display today's date.

Write a query to display the date after 3 months from today.

Display last date of the current month.

Display the up coming Wednesday date.

Which date function return number as output.

What are all the type conversion functions available.

How to convert date into character.

How to convert character in to date.

What is the use of general function.

Explain NVL, NVL2 , NULLIF and COALESCE function with example.

What are all the aggregate functions available in oracle.

Write a query to select maximum salary from employees table.

Write a query to select second maximum salary from employees table.

Display average salary in the department 90.

Display number of employees working in department 90 and 60.

Display all the department id and its maximum salary.

Display all the department id and number of employees working in that department.

Display all the department id and salary allocated for that department.

Display all the department id and number of employees working in that department. Total no
employees working for the particular department must be greater than 30.

Difference between WHERE clause and HAVING clause.

Difference between DECODE and CASE.

How to update all Male to Female and all female to Male by using single update statement?

Joins:

What is joins? What are all the difference types of joins available?

Explain outer join and its types with example.

What is Self Join and why is it required?

What is the difference between inner and outer join? Explain with example.

What is a Cartesian product.

If I try to Fetch data from 25 tables. How many number of join condition required?

Click here to learn Joins

Sub Queries:

What is a sub query? What are all the types of sub query?

List out the operators of single row and multiple row sub query.

Difference between single row and multiple row sub query.

What is Inline view?

Write a query to display all the employees who are all getting salary more than the average
salary of the department 60.

What is cor related sub query?

Write a query to display all the employees who are all getting salary more than the average
salary of the their department.

Write a query to display all the employees who are all getting salary more than their manager
salary.

What are the advantages and disadvantages of using a sub query?

How to rewrite joins by using sub query? Give example.

DDL, DML, DCL and DCL statements:


List out all the DDL statements.

What are all the data types available in oracle.

Difference between VARCHAR2 and CHAR data type.

How to create table in oracle.

How to create table with DEFAULT option.

How to copy the structure of particular table by using sub query? ( With data)

How to copy the structure of particular table by using sub query? ( With out data)

What is the use of DROP option in the ALTER TABLE command.

How to add the column after the table has been created?

How to rename the particular column in a table?

How to change the data type of the particular column after the table has been created.

How to rename the table.

How to drop the table?

How to truncate the table?

What are all the DML statements available?

How to INSERT records in to selective no of columns?

How to insert data by using sub query?

How to insert all the data from table X to table Y?

How to update more than one column at a time.

How to delete all the employees working in department 30.

If we ignore WHERE clause in UPDATE statement what ll happen?

If we ignore WHERE clause in DELETE statement what will happen?

Difference between DELETE, TRUNCATE and DROP.

What is the use of MERGE statement? Explain it with syntax.

What are all the Transaction Control Language available?


A table contain list of students record with their gender details. Write a update statement to
update all the male in to female and female into male.

Constraints:

What are all the type of constraint available in oracle?

Difference between PRIMARY KEY and UNIQUE key.

Difference between PRIMARY KEY ans FOREIGN KEY.

Difference between UNIQUE key and FOREIGN KEY.

Write a syntax to create FOREIGN constraint.

How to create constraint after the table has been created?

How to enable and disable a constraint.

Which data dictionary table contain information about constraints?

Explain ON DELETE CASCADE and ON DELETE SET NULL.

Views:

What is View?

What are are all the different types of views?

View contain data or not?

Which Data Dictionary table contain View information?

Is it possible to create view with out base table?

What is a use of view WITH CHECK OPTION and WITH READ ONLY?

List out the advantage and disadvantage of views.

Is it possible to perform DML operation on view?

How to perform insert operation on complex view?

Index:

What is INDEX?

When to create Index and when not to create index?

What are are all the types of index available?


How to enable and disable index?

Which Data Dictionary table contain information about Indexes.

Pseudo columns and sequences:

How to select first 5 records from a table?

What are all the Pseudo columns available?

Write a query to find out nth maximum salary?

While creating a sequence, what does cache and nocache options mean?

How do we set the LASTVALUE value in an Oracle Sequence?

How to Recompile the Procedure and Function?

Synonyms:

How to create synonyms?

Explain Private and public Synonym.

Which Data Dictionary Table contain information about Sequences?

Set operators:

What is the difference between JOIN and UNION?

What is the difference between UNION and UNION ALL?

What is the difference among UNION, MINUS and INTERSECT?

What are all the restriction we need to follow while using SET OPERATORS.

Analytical Functions:

What are the differences among ROWNUM, RANK and DENSE_RANK?

Explain LEAD and LAG Function.

Difference Between Questions in SQL:


Difference between IN and EXISTS ? Which one is more Faster? Why?

Difference between SUBSTR and INSTR function.

Difference between REPLACE and TRANSLATE function.

Difference between LPAD and RPAD.

Difference between LTRIM and RTRIM.

Difference between WHERE clause and HAVING clause.

Difference between DECODE and CASE.

What is the difference between inner and outer join? Explain with example.

Difference between single row and multiple row sub query.

Difference between DELETE, TRUNCATE and DROP.

Difference between PRIMARY KEY and UNIQUE key.

Difference between PRIMARY KEY ans FOREIGN KEY.

Difference between UNIQUE key and FOREIGN KEY.

What is the difference between JOIN and UNION?

What is the difference between UNION and UNION ALL?

What is the difference among UNION, MINUS and INTERSECT?

Give your valuable feedback below :)


Oracle sql & Pl/sql

search

Home Sql and pl/sql Sql Interview Questions

JUL

20

INLINE view in Oracle with 12c New Features

Named sub Query in FROM clause is call it as INLINE VIEW.

Oracle process a inline view faster than sub query

Inline View in Oracle

--Query to display all the employees who are all getting salary more than their department
average salary

SELECT First_name

, last_name

, salary

, department_id

FROM employees a , ( SELECT b.department_id

, AVG(b.salary) avg_sal

FROM employees b

GROUP BY b.department_id
)b

WHERE a.department_id = b.department_id

AND a.salary > b.avg_salary;

Display all the customer who have placed more number of orders by using INLINE view

CREATE TABLE customer_order_det_tb

( custm_id NUMBER ,

custm_nm VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

ttl_amt NUMBER(7,2)

);

BEGIN

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '11-Jul-15' , 45000.00);

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '14-Jul-15' , 27000.00);

INSERT INTO customer_order_det_tb VALUES(101, 'Raja' , '13-Jul-15' , 17000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 34000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 38000.00);

COMMIT;

END;

SELECT c.*
FROM customer_order_det_tb c;

--------------------------------------------

custm_id custm_nm order_dt ttl_amt

--------------------------------------------

100 Murugappan 7/11/2015 45000.00

100 Murugappan 7/14/2015 27000.00

101 Raja 7/13/2015 17000.00

102 Ramesh 7/15/2015 34000.00

102 Ramesh 7/15/2015 38000.00

--------------------------------------------

--Writing a Quer to display all the customer who have placed maximum number of order

--Query #1 for inline view

SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC;

--------------------------------

custm_id custm_nm total_odr

--------------------------------

100 Murugappan 2
102 Ramesh 2

101 Raja 1

--------------------------------

--Query #2 for inline view

SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm;

----------

total_odr

----------

----------

Inline view to find all the customers who have placed maximum number of orders

/****************************************

Syntax

SELECT * FROM <query1> x, <query2> y

WHERE contition;

****************************************/
SELECT query1.* FROM

( SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC

) query1,

( SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm

) query2

WHERE query1.total_odr = query2.total_odr;

-------------------------------

custm_id custm_nm total_odr

-------------------------------

100 Murugappan 2

102 Ramesh 2

-------------------------------

DROP TABLE customer_order_det_tb;

--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT

SELECT first_name, salary


FROM ( SELECT first_name, salary

FROM employees e

WHERE job_id NOT IN ('SALESMAN','PRESIDENT')

ORDER BY salary DESC

WHERE ROWNUM < 4;

New Oracle 12c Inline view Syntax

LATERAL clause for In-line views

Allows for columns in the inline view to be accessed!!

Example :

--in 11g

SELECT * FROM employees e, (

SELECT *

FROM departments d

WHERE e.department_id = d.department_id);

ORA-0090: "E"."DEPARTMENT_ID": Invalid Identifier


--in 12c

SELECT * FROM employees e, LATERAL(

SELECT *

FROM departments d

WHERE e.department_id = d.department_id

);

--in 11g

WITH t

AS

( SELECT LEVEL a

FROM dual

CONNECT BY LEVEL <= 30)

SELECT *

FROM t, (SELECT *

FROM employees

WHERE department_id = t.a

);

ORA-00904: "T"."A": invalid Identifier

--in 12c

WITH t

AS
(SELECT LEVEL a FROM dual CONNECT BY LEVEL <= 30)

SELECT * FROM t,

LATERAL(SELECT *

FROM employees

WHERE department_id = t.a);

Hope you have enjoyed this little article

Feed backs are always Welcome :) (:

Posted 20th July 2015 by Unknown

0 Add a comment

JAN

23

Salary Related Questions in Oracle

--creating table

CREATE TABLE employee_data

eid NUMBER(4),
ename VARCHAR2(30),

depno NUMBER(3),

salary NUMBER(8)

);

BEGIN

--Inserting records

INSERT INTO employee_data VALUES(1000,'Name01',90,30000);

INSERT INTO employee_data VALUES(1001,'Name02',90,6000);

INSERT INTO employee_data VALUES(1002,'Name03',90,23000);

INSERT INTO employee_data VALUES(1003,'Name04',60,35000);

INSERT INTO employee_data VALUES(1004,'Name05',60,60000);

INSERT INTO employee_data VALUES(1005,'Name06',60,30000);

INSERT INTO employee_data VALUES(1006,'Name07',80,36000);

INSERT INTO employee_data VALUES(1007,'Name08',80,29000);

INSERT INTO employee_data VALUES(1008,'Name09',80,37000);

INSERT INTO employee_data VALUES(1009,'Name10',80,41000);

COMMIT;

END;

SELECT * FROM employee_data


ORDER BY salary DESC;

--query to find maximum salary from employee_data table

SELECT MAX(salary) FROM employee_data;

--query to find minimum salary from employee_data table

SELECT MIN(salary) FROM employee_data;

--query to find second maximum salary from employee_data table

SELECT MAX(salary)

FROM employee_data

WHERE salary NOT IN (SELECT MAX(salary)

FROM employee_data);

--query to select 5th maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= 5);


--query to select nth maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= &n);

--query to select all the details of the employee whose getting nth maximum salary

SELECT *

FROM (SELECT emp.*,

rownum rn

FROM (SELECT *

FROM employee_data

ORDER BY salary DESC) emp)

WHERE rn = 9;

--same query using row_numbr( ) function

SELECT *
FROM (SELECT emp.*,

row_number() over(ORDER BY salary) rank

FROM employee_data emp)

WHERE rank = 9;

--same query using rank( ) function

SELECT *

FROM (SELECT emp.*,

rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--same query using dense_rank( ) function

SELECT *

FROM (SELECT emp.*,

dense_rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--query to display display maximum salary in all the department

SELECT e.depno "Department id",


MAX(salary) "Maximum Salary"

FROM employee_data e

GROUP BY e.depno;

--query to display all the employees who are all getting salary more than average salary of the
company

SELECT e.* FROM employee_data e

WHERE salary > (SELECT AVG(salary) FROM employee_data);

--query to display all the employees who are all getting salary more than their department
average salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE department_id = OUT.department_id);

--query to display all the employees who are all getting salary more than their manager salary

SELECT employee_id,
first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE employee_id = OUT.manager_id);

Documented By : Murugappan Annamalai

Posted on : 23-Jan-15 16:34:00 IST.

Hope you have enjoyed this little article

Feed backs are always welcome :)

Posted 23rd January 2015 by Unknown

7 View comments

JAN

22

Why prefer COALESCE over NVL

Documented By : Nimish Garg


I prefer using "COALESCE" over "NVL" is some of the scenarios. Last week One of my friend
asked me what is the advantage of using "COALESCE" where we can simply use "NVL". I simply
gave him the reply from Oracle Docs i.e. NVL lets you replace null (returned as a blank) with a
string in the results of a query and COALESCE returns the first non-null expr in the expression list.
Oracle Database uses short-circuit evaluation with "COALESCE".

He replied that he knows the difference, he knows that "COALESCE" can take multiple arguments
and so on. He was more interested in understanding "short-circuit evaluation" of "COALESCE"
and the scenarios where I prefer using "COALESCE" over "NVL".

To make him understand I created following function which takes One second in every execution
and simply returns '--null--' and executed 2 very similar queries one with NVL and other with
COALESCE.

SQL> create or replace function f_null return varchar2

2 is

3 begin

4 dbms_lock.sleep(1);

5 return '--null--';

6 end;

7 /

Function created.

Following are the queries which I used to demonstrate that NVL evaluates both arguments even
if the second argument is not used and COALESCE uses short-circuit evaluation i.e. it only
evaluates the arguments only if they are needed.
SQL> select e.empno, e.ename ename, nvl(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.
Elapsed: 00:00:14.01

SQL> select e.empno, e.ename ename, coalesce(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.
Elapsed: 00:00:01.01

Here we can see easily that the first query with NVL took 14+ seconds, one second for each
record even if the "f_null" value was used only in one record. On the contrary as mentioned in
Oracle Documentation "COALESCE" uses its "short-circuit evaluation" and "f_null" was called
only once and so second query took only One Second. "COALESCE" is certainly use less resources
than NVL.

Posted 22nd January 2015 by Unknown

0 Add a comment

DEC

21

Constraints

It Enforce Rule On Table

We can create constraint at the time of Creating Table

1. Column Level Declaration

2. Table Level Declaration

1. We can provide own name.


Format : [part_of_project_name-table_name-column_name-constraint_type]

Example : gmind_emp_id_pk _uk _ck _f

2. system name name

Format : sys_cn

Example : SYS_C405323

We can create constraint after the table has been created

Types

Primary Key

Not allowed Null value

Not allowed you to enter duplicate value

Ex : Employee_id, Student_id

Unique Key

allowed Null value


Not allowed you to enter duplicate value

Ex : Contact_no, email

Foreign Key

It will allowed you to enter NULL and Duplicate value.

c1(pk) : 1 2 3

c2(f) : 1 1 2 3 4 Not allowed

Allowed you to enter duplicate value and null value

Not Null

It will not allowed you to enter null value

Check

You can check your own condition

Simple Table for understanding

------------------------------------
Duplicate NULL

------------------------------------

Primary Key X X

Unique Key X Allowed

Foreign Key Allowed Allowed

------------------------------------

creating table with all constraint type

Create table my_stu_details

S_id Number(2),

S_name Varchar2(30) Not Null, --SYS_Cn

s_mail Varchar2(30),

s_gender char(1),

s_did Number(3),

Constraint my_stu_sid_pk PRIMARY KEY (s_id),

constraint my_stu_mail_uk UNIQUE (s_mail) ,

Constraint my_stu_gen_ck CHECK (s_gender IN ('M', 'F', 'm', 'f')),

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

);
DESC my_stu_details;

------------------------------------

Name Type Nullable

------------------------------------

S_ID NUMBER(2)

S_NAME VARCHAR2(30)

S_MAIL VARCHAR2(30) Y

S_GENDER CHAR(1) Y

S_DID NUMBER(3) Y

------------------------------------

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name1' , 'name1@gmail.com' , 'm' , 60 );

Select * from my_stu_details;

Validating Primary Key


Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-00001: unique constraint (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (NULL, 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-01400: cannot insert NULL into (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (2 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

Validating NOT NULL Constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , NULL , 'name3@gmail.com' , 'F' , 80 );

ORA-01400: cannot insert NULL into ("HR"."MY_STU_DETAILS"."S_NAME")


Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , 'Name3' , 'name3@gmail.com' , 'F' , 80 );

Select * from my_stu_details;

Validating Unique Key Constraint

--Duplicate Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , 'name3@gmail.com' , 'F' , 80 );

ORA-00001: unique constraint (HR.MY_STU_MAIL_UK) violated

--Null Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , null , 'M' , 70 );


Select * from my_stu_details;

Validating Check constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'j' , 70 );

ORA-02290: check constraint (HR.MY_STU_GEN_CK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'M' , 70 );

Select * from my_stu_details;

Validating Foreign Key

Select * from Departments;

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)


values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 3 );

ORA-02291: integrity constraint (HR.MY_STU_DID_FK) violated - parent key not found

Departments table : parent table

my_stu_details : Child table

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

--------------------------------------------------------

s_id s_name s_mail s_gender s_did

--------------------------------------------------------

1 name1 name1@gmail.com m 60

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 M 70

5 Name5 name5@gmail.com M 70

6 Name6 name6@gmail.com F 90
--------------------------------------------------------

Deleting the Primary key value which is referred by Foreign Key

Select * from Departments;

DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID

------------------------------------------------------------

60 IT 103 1400 <---- Delete

-- don't execute this query

--Delete From Departments

--Where Department_id = 60;

1) ON DELETE SET NULL

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90
1 name1 name1@gmail.com m -

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

2) ON DELETE SET CASCADE

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

Syntax

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE CASCADE

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)


ON DELETE SET NULL

Constraint Related Data Dictionary Table information.

To view constraint Information

SELECT c.owner,

c.constraint_name,

c.constraint_type,

c.table_name,

c.r_constraint_name,

c.status

FROM user_constraints c

WHERE c.table_name = 'MY_STU_DETAILS';

------------------------------------------------------------------------------------

owner constraint_name constraint_type table_name r_constraint_name status

------------------------------------------------------------------------------------

HR SYS_C004023 C MY_STU_DETAILS ENABLED

HR MY_STU_GEN_CK C MY_STU_DETAILS ENABLED

HR MY_STU_SID_PK P MY_STU_DETAILS ENABLED

HR MY_STU_MAIL_UK U MY_STU_DETAILS ENABLED


HR MY_STU_DID_FK R MY_STU_DETAILS DEPT_ID_PK ENABLED

------------------------------------------------------------------------------------

To view constraint name with corresponding column name

SELECT * FROM user_cons_columns c

WHERE c.table_name = 'MY_STU_DETAILS';

-------------------------------------------------------------

owner constraint_name table_name column_name position

-------------------------------------------------------------

HR MY_STU_MAIL_UK MY_STU_DETAILS S_MAIL 1

HR MY_STU_SID_PK MY_STU_DETAILS S_ID 1

HR MY_STU_GEN_CK MY_STU_DETAILS S_GENDER

HR SYS_C004023 MY_STU_DETAILS S_NAME

HR MY_STU_DID_FK MY_STU_DETAILS S_DID 1

-------------------------------------------------------------

Creating Composite Primary Key

Creating Primary Key with more than one number of column


ALTER TABLE table_name

ADD CONSTRAINT constraint_name PRIMARY KEY(column1, column_2 , column3);

In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.

creating constraint after the table creation

ALTER TABLE table_name

ADD CONSTRAINT constraint_name CONSTRAINT_TYPE(column_name);

ALTER TABLE table_name

DROP CONSTRAINT constraint_name;

ALTER TABLE table_name

DROP PRIMARY KEY;

To drop related foreign key

ALTER TABLE table_name

DROP PRIMARY KEY CASCADE;


ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name;

Disable constraint with related foreign key constraint

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name CASCADE;

ALTER TABLE table_name

ENABLE CONSTRAINT constraint_name;

Interview Questions

What are all the type of constraint available in oracle?

Difference between PRIMARY KEY and UNIQUE key.

Difference between PRIMARY KEY ans FOREIGN KEY.

Difference between UNIQUE key and FOREIGN KEY.

Is it possible to create tow primary key in single table.

Write a syntax to create FOREIGN constraint.


How to create constraint after the table has been created?

How to enable and disable a constraint.

Which data dictionary table contains information about constraints?

Which Data Dictionary table contains information about constraint with corresponding column
name?

What is composite primary key?

Explain ON DELETE CASCADE and ON DELETE SET NULL option.

~Thanks For Reading~

Post your valuable feedback below

Posted 21st December 2014 by Unknown

1 View comments

DEC

listagg in Oracle 11g

Oracle 11gR2 listagg built-in function allows for many table columns to be displayed within a
single row, a non-first-normal form display

Syntax :
listagg(column_value,'delimiter') WITHIN GROUP(ORDER BY column_name)

--Example 1:

CREATE TABLE test_ins(empid NUMBER,product VARCHAR2(30));

BEGIN

INSERT INTO test_ins VALUES( 101,'pendrive');

INSERT INTO test_ins VALUES( 102,'toy');

INSERT INTO test_ins VALUES( 101,'ipod');

INSERT INTO test_ins VALUES( 102,'hat');

INSERT INTO test_ins VALUES( 103,'cpu');

INSERT INTO test_ins VALUES( 104,'pen');

INSERT INTO test_ins VALUES( 104,'car');

INSERT INTO test_ins VALUES( 104,'mat');

INSERT INTO test_ins VALUES( 105,'tv');

INSERT INTO test_ins VALUES( 106,'laptop');

commit;

END;

SELECT * FROM test_ins;

SELECT empid "Employee",


listagg(product,

',') within

GROUP (ORDER BY empid) "Products"

FROM test_ins

GROUP BY empid;

-->-- Result set --<--

DROP TABLE test_ins;

-->-- Example 2
select department_id "Department id", listagg(first_name,', ') WITHIN GROUP(ORDER BY
employee_id) "Employees"

FROM employees

WHERE department_id IN (10,20,30,60)

GROUP BY department_id;

-->-- Result set --<--

Posted 4th December 2014 by Unknown

0 Add a comment

NOV

Condition and Looping Statement

IF

IF ELSE

Multiple IF ELSE

LOOP

FOR LOOP

WHILE LOOP
create table test_udt(id NUMBER, salary NUMBER);

BEGIN

INSERT INTO test_udt VALUES(001,23000);

INSERT INTO test_udt VALUES(002,43000);

INSERT INTO test_udt VALUES(003,78000);

INSERT INTO test_udt VALUES(004,25000);

INSERT INTO test_udt VALUES(005,26000);

INSERT INTO test_udt VALUES(006,90000);

Commit;

END;

select * from test_udt;

IF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN
SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 1;

IF v_salary > 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

END IF;

commit;

END;

IF ELSE

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;
IF v_salary < 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

ELSE

UPDATE test_udt t

SET t.salary = v_salary+20007

WHERE t.id = v_id ;

END IF;

commit;

END;

--same example with less number of lines

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;
IF v_salary < 20000 THEN

v_salary := v_salary+10005;

ELSE

v_salary := v_salary+20007;

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

Multiple IF ELSIF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary
FROM test_udt

WHERE id = 3;

IF v_id = 1 THEN

v_salary := 1000;

dbms_output.put_line('1 inside');

ELSIF v_id = 2 THEN

v_salary := 2000;

dbms_output.put_line('2 inside');

ELSIF v_id = 3 THEN

v_salary := 3000;

dbms_output.put_line('3 inside');

ELSIF v_id = 4 THEN

v_salary := 4000;

dbms_output.put_line('4 inside');

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;


LOOP

--syntax

LOOP

--statements

--increment

--exit statement

END LOOP;

CREATE TABLE prod_details (pid VARCHAR2(3), pname VARCHAR2(30));

DECLARE

i NUMBER := 1;

x VARCHAR2(3);

BEGIN

LOOP

x := lpad(i,3,'0');

dbms_output.put_line('x value : '|| x);

INSERT INTO prod_details VALUES(i, 'Product '||i);

EXIT WHEN i >900;

i := i+1;
IF MOD(i,100) = 0 THEN

commit;

dbms_output.put_line('commit executed');

END IF;

END LOOP;

END;

SELECT * FROM prod_details ORDER BY 1;

DROP TABLE prod_details;

FOR LOOP

BEGIN

FOR I in 1..5

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

FOR LOOP - Reverse


BEGIN

FOR I in REVERSE 14..50

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

WHILE LOOP

DECLARE

i_val NUMBER:=0;

BEGIN

WHILE (i_val < 11)

LOOP

dbms_output.put_line('The value of I is '||i_val);

i_val := i_val + 1;

END LOOP;

END;

sample output:

The value of I is 0

The value of I is 1
The value of I is 2

The value of I is 3

The value of I is 4

The value of I is 5

The value of I is 6

The value of I is 7

The value of I is 8

The value of I is 9

The value of I is 10

Posted 8th November 2014 by Unknown

0 Add a comment

OCT

21

Bulk Collect

This is used for array fetches

With this you can retrieve multiple rows of data with a single round trip.

This reduces the number of context switches between the pl/sql and sql engines.

You can use bulk collect in both dynamic and static sql.

You can use bulk collect in select, fetch into and returning into clauses.

SQL engine automatically initializes and extends the collections you reference in the bulk
collect clause.
You can fetch into multiple collections with one column each.

You can use the limit clause of bulk collect to restrict the no of rows retrieved.

SELECT * FROM product_details;

-->-- Bulk collect in FETCH INTO --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;
/

-->-- Bulk collect in SELECT clause --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

BEGIN

SELECT * BULK COLLECT INTO dta FROM product_details;

FOR i IN dta.FIRST .. dta.LAST LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- LIMIT in Bulk collect --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN
OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta LIMIT 30;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Multiple fetches in INTO clause --<--

SELECT * FROM product_details;

DECLARE

TYPE alldata_typ1 IS TABLE OF product_details.p_id%TYPE;

TYPE alldata_typ2 IS TABLE OF product_details.p_name%TYPE;

dta1 alldata_typ1;

dta2 alldata_typ2;

CURSOR proddt_cur IS

SELECT p_id, p_name FROM product_details;

BEGIN
OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta1, dta2;

CLOSE proddt_cur;

FOR i IN dta1.FIRST .. dta1.COUNT LOOP

dbms_output.put_line('Department Id : ' || dta1(i));

END LOOP;

FOR i IN dta2.FIRST .. dta2.COUNT LOOP

dbms_output.put_line('Department Name : ' || dta2(i));

END LOOP;

END;

DROP TABLE dep_details;

DROP TABLE product_details;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21
Ref Cursor

This is unconstrained cursor which will return different types depends upon the user input.

Ref cursors cannot be closed implicitly.

Ref cursor with return type is called strong cursor.

Ref cursor without return type is called weak cursor.

You can declare ref cursor type in package spec as well as body.

You can declare ref cursor types in local subprograms or anonymous blocks.

CREATE OR REPLACE PROCEDURE ref_c_sp(dep_det_c IN OUT SYS_REFCURSOR)

AS

BEGIN

OPEN dep_det_c

FOR

SELECT * FROM dep_details d;

END;

DECLARE

dep_det_c SYS_REFCURSOR;

tab_data dep_details%ROWTYPE;

BEGIN
ref_c_sp(dep_det_c);

LOOP

FETCH dep_det_c INTO tab_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department Name : '|| tab_data.d_name);

END LOOP;

CLOSE dep_det_c;

END;

/*sample output*/

Department Name : Admin

Department Name : HR

Department Name : Sales

Department Name : Marketing

DROP PROCEDURE ref_c_sp;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT
21

Cursor

SQL Private work Area where the query get passed and executed.

Types

******

Implicit(SQL)

Explicit

-->-- advanced cursor types --<--

Parametrized Cursor

Ref Cursor

Implicit

********

ORACLE implicitly opens a cursor to process each SQL statement not associated with an
explicitly declared cursor.

PL/SQL lets you refer to the most recent implicit cursor as the SQL” cursor. So, although you
cannot use the OPEN,

FETCH, and CLOSE statements to control an implicit cursor, you can still use cursor attributes to
access information

about the most recently executed SQL statement.


Cursor Stages

**************

OPEN cursor_name

FETCH (with in loop)

CLOSE cursor_name

Explicit

The set of rows returned by a query can consist of zero, one, or multiple rows,

depending on how many rows meet your search criteria. When a query returns multiple rows,

you can explicitly define a cursor to process the rows. You use three commands to control the
cursor

Cursor Attributes

*****************

%FOUND

%NOTFOUND

%ISOPEN

%ROWCOUNT

%BULK_ROWCOUNT --<-- used to handle error while using bulk collection.

%BULK_EXCEPTIONS --<-- used to handle error while using bulk collection.

Cursor Declaration
DECLARE

CURSOR <cursor_name>

IS

<SELECT statement>

BEGIN

--> some stmt

END;

Cursor Loop

Loop

While Loop

For Loop

Cursor Clauses

Return

For update

Where current of

Bulk collect

-->-- creating table

create table product_details

p_id NUMBER,
p_name VARCHAR2(30),

p_order_dt DATE

);

-->-- Inserting data

BEGIN

FOR i IN 1 .. 75 LOOP

INSERT INTO product_details VALUES (i, 'prod_name_' || i, SYSDATE + i);

END LOOP;

commit;

END;

-->-- selecting data

SELECT * FROM product_details;

---------------------------------------------

p_id p_name p_order_dt

---------------------------------------------

1 prod_name_1 10/11/2014 3:48:32 PM

2 prod_name_2 10/12/2014 3:48:32 PM

3 prod_name_3 10/13/2014 3:48:32 PM


4 prod_name_4 10/14/2014 3:48:32 PM

5 prod_name_5 10/15/2014 3:48:32 PM

6 prod_name_6 10/16/2014 3:48:32 PM

7 prod_name_7 10/17/2014 3:48:32 PM

8 prod_name_8 10/18/2014 3:48:32 PM

9 prod_name_9 10/19/2014 3:48:32 PM

10 prod_name_10 10/20/2014 3:48:32 PM

11 prod_name_11 10/21/2014 3:48:32 PM

12 prod_name_12 10/22/2014 3:48:32 PM

13 prod_name_13 10/23/2014 3:48:32 PM

14 prod_name_14 10/24/2014 3:48:32 PM

15 prod_name_15 10/25/2014 3:48:32 PM

16 prod_name_16 10/26/2014 3:48:32 PM

17 prod_name_17 10/27/2014 3:48:32 PM

18 prod_name_18 10/28/2014 3:48:32 PM

19 prod_name_19 10/29/2014 3:48:32 PM

20 prod_name_20 10/30/2014 3:48:32 PM

---------------------------------------------

----------------------------------------------

Implicit Cursor

----------------------------------------------

--will update soon


----------------------------------------------

Explicit Cursor

----------------------------------------------

**********************************************

Processing cursor data by using LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND; --<-- if next record not found means control will
come out from the loop

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;
CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

dbms_output.put_line('Product id : ' || all_data.p_id ||


' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

EXIT WHEN prod_detail_cur%FOUND; --<-- if next record found means control will come
out from the loop

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;
EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor Already closed


DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

-->-- CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');


ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor closed

**********************************************

Processing cursor data by using WHILE LOOP

**********************************************

DECLARE
all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

OPEN prod_detail_cur;

FETCH prod_detail_cur

INTO all_data;

WHILE prod_detail_cur%FOUND LOOP

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

FETCH prod_detail_cur

INTO all_data;

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )


Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

************************************************************

Processing cursor data by using FOR LOOP - CURSOR FOR LOOP

************************************************************

DECLARE

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

FOR i IN prod_detail_cur

LOOP

dbms_output.put_line('Product id : ' || i.p_id ||

' Product Name : ' || i.p_name ||

' ( Orderd on : ' || TRIM(i.p_order_dt) || ' )');

END LOOP;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )


Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

Parameterized Cursor

*********************

This was used when you are going to use the cursor in more than one place with different
values for the same where clause.

Cursor parameters must be in mode.

Cursor parameters may have default values.

The scope of cursor parameter is within the select statement.

CREATE TABLE dep_details(d_id NUMBER,d_name VARCHAR2(30), location_id NUMBER);

BEGIN

INSRT INTO dep_details VALUES(001,'Admin',1010);

INSRT INTO dep_details VALUES(002,'HR',1010);

INSRT INTO dep_details VALUES(003,'Sales',1020);

INSRT INTO dep_details VALUES(004,'Marketing',1020);

commit;

END;
SELECT * FROM dep_details;

----------------------------

d_id d_name location_id

----------------------------

1 Admin 1010

2 HR 1010

3 Sales 1020

4 Marketing 1020

----------------------------

DECLARE

-->--Declaring parameterized cursor

CURSOR dep_det_c(p_location_id NUMBER) IS

SELECT * FROM dep_details d WHERE d.location_id = p_location_id;

all_data dep_details%ROWTYPE;

BEGIN

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

OPEN dep_det_c(1010);

LOOP

FETCH dep_det_c

INTO all_data;
EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

-->-- opening same cursor with different input value

OPEN dep_det_c(1020);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

END;

/*sample output*/
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 1 Department Name : Admin

Department id : 2 Department Name : HR

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 3 Department Name : Sales

Department id : 4 Department Name : Marketing

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Handling Exception

Error Handling in oracle

ERROR

Any departure from the expected behavior of the system or program,

which stops the working of the system is an error.

Types : compile time error

Run time error

EXCEPTION
Any error or problem which one can handle and continue to work normally.

Handling Exception

When exception is raised, control passes to the exception section of the block.

i.e. EXCEPTION

WHEN name_of_exception THEN

Types : Pre Defined Exceptions

User Defined Exceptions

Predefined Exception

*********************

Oracle has predefined several exceptions that correspond to the most common oracle errors.

------------------------------------------------------------------------

Exception Oracle Error SQL Code Value

------------------------------------------------------------------------

ZERO_DIVIDE ORA-01476 -1476

NO_DATA_FOUND ORA-01403 +100

DUP_VAL_ON_INDEX ORA-00001 -1

TOO_MANY_ROWS ORA-01422 -1422


VALUE_ERROR ORA-06502 -6502

CURSOR_ALREADY_OPEN ORA-06511 -6511

OTHERS

------------------------------------------------------------------------

-->-- ZERO_DIVIDE --<--

Your program attempts to divide a number by zero.

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN ZERO_DIVIDE THEN

dbms_output.put_line('Divisor is equal to zero');

END;

-->-- NO_DATA_FOUND --<--

Single row SELECT returned no rows or your program referenced a deleted element in a nested
table

or an uninitialized element in an associative array (index-by table).


CREATE TABLE test_tb(id NUMBER PRIMARY KEY);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN NO_DATA_FOUND THEN

dbms_output.put_line('There is no data inside the table');

END;

-->-- DUP_VAL_ON_INDEX --<--

A program attempted to insert duplicate values in a column that is constrained by a unique


index.

INSERT INTO test_tb VALUES (1);

INSERT INTO test_tb VALUES (2);

commit;

BEGIN

INSERT INTO test_tb VALUES (2);

EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN

dbms_output.put_line('Duplicate values are not allowed');

END;

-->-- TOO_MANY_ROWS --<--

Single row SELECT returned multiple rows.

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN TOO_MANY_ROWS THEN

dbms_output.put_line('Query returning more than one row');

END;

DROP TABLE test_tb;

-->-- VALUE_ERROR --<--

An arithmetic, conversion, truncation, or size constraint error occurred.


DECLARE

num1 NUMBER(2);

BEGIN

num1 := 345;

EXCEPTION

WHEN VALUE_ERROR THEN

dbms_output.put_line('check the size of the variable');

END;

-->-- CURSOR_ALREADY_OPEN --<--

A program attempted to open an already opened cursor.

CREATE TABLE emp(id NUMBER, name VARCHAR2(30));

BEGIN

INSERT INTO emp VALUES(1,'Name1');

INSERT INTO emp VALUES(2,'Name2');

INSERT INTO emp VALUES(3,'Name3');

INSERT INTO emp VALUES(4,'Name4');

COMMIT;

END;
SELECT * FROM emp;

DECLARE

cursor emp_c IS

SELECT * FROM emp;

all_data emp%ROWTYPE;

BEGIN

OPEN emp_c;

OPEN emp_c;

NULL;

CLOSE emp_c;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

END;

DROP TABLE emp;

-->-- OTHERS --<--

DECLARE

v_result NUMBER;
BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

WHEN OTHERS THEN

dbms_output.put_line('Some other error ' || SQLERRM);

END;

User Defined Exception

**********************

A user-defined exception is an error that is defined by the programmer.

User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,

exceptions have a type EXCEPTION and scope.

DECLARE

v_gender CHAR := '&gender';

gender_ex EXCEPTION;

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE gender_ex;
END IF;

dbms_output.put_line('Gender : '||v_gender);

EXCEPTION

WHEN gender_ex THEN

dbms_output.put_line('Please Enter valid gender');

END;

create table test_insert (id NUMBER, Name VARCHAR2(30));

DECLARE

abort_ex EXCEPTION;

BEGIN

FOR i IN 1..100

LOOP

BEGIN

IF mod(i,10)=0 THEN

RAISE abort_ex;

END IF;

INSERT INTO test_insert VALUES(i, 'Name'||i);

EXCEPTION

WHEN abort_ex THEN

NULL;

END;

END LOOP;
COMMIT;

END;

SELECT * FROM test_insert;

DROP TABLE test_insert;

SQLERRM and SQLCODE

********************

SQLCODE returns the current error code, and SQLERRM returns the current error message
text;

For user-defined exception SQLCODE returns 1 and SQLERRM returns “user-defined


exception”.

SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.

CREATE TABLE test_tb (id NUMBER);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

dbms_output.put_line(v_id);

EXCEPTION
WHEN OTHERS THEN

dbms_output.put_line('SQLERRM : ' || SQLERRM);

dbms_output.put_line('SQLCODE : ' || SQLCODE);

END;

/*sample output*/

SQLERRM : ORA-01403: no data found

SQLCODE : 100

DROP TABLE test_tb;

PRAGMA EXCEPTION_INIT

*********************

Using this you can associate a named exception with a particular oracle error.

This gives you the ability to trap this error specifically, rather than via an OTHERS handler.

Syntax:

PRAGMA EXCEPTION_INIT(exception_name, oracle_error_number);

DECLARE

v_result NUMBER;
PRAGMA EXCEPTION_INIT(Invalid, -1476);

BEGIN

SELECT 453 / 0 INTO v_result FROM dual;

dbms_output.put_line('Result : ' || v_result);

EXCEPTION

WHEN INVALID THEN

dbms_output.put_line('Invalid Exception');

END;

RAISE_APPLICATION_ERROR

************************

You can use this built-in function to create your own error messages, which can be more
descriptive than named exceptions.

Error Number :

Oracle Error Range : From -00000 to -19999

User Error Range : From -20000 to -20999

DECLARE

v_gender CHAR := '&gender';


BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE_APPLICATION_ERROR(-20003, 'Enter valid gender');

END IF;

dbms_output.put_line('Gender : ' || v_gender);

END;

Posted 21st October 2014 by Unknown

1 View comments

Loading

Dynamic Views theme. Powered by Blogger.Oracle sql & Pl/sql

search

Home Sql and pl/sql Sql Interview Questions

JUL

20

INLINE view in Oracle with 12c New Features

Named sub Query in FROM clause is call it as INLINE VIEW.


Oracle process a inline view faster than sub query

Inline View in Oracle

--Query to display all the employees who are all getting salary more than their department
average salary

SELECT First_name

, last_name

, salary

, department_id

FROM employees a , ( SELECT b.department_id

, AVG(b.salary) avg_sal

FROM employees b

GROUP BY b.department_id

)b

WHERE a.department_id = b.department_id

AND a.salary > b.avg_salary;

Display all the customer who have placed more number of orders by using INLINE view

CREATE TABLE customer_order_det_tb

( custm_id NUMBER ,

custm_nm VARCHAR2(30) ,
order_dt DATE DEFAULT SYSDATE ,

ttl_amt NUMBER(7,2)

);

BEGIN

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '11-Jul-15' , 45000.00);

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '14-Jul-15' , 27000.00);

INSERT INTO customer_order_det_tb VALUES(101, 'Raja' , '13-Jul-15' , 17000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 34000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 38000.00);

COMMIT;

END;

SELECT c.*

FROM customer_order_det_tb c;

--------------------------------------------

custm_id custm_nm order_dt ttl_amt

--------------------------------------------

100 Murugappan 7/11/2015 45000.00

100 Murugappan 7/14/2015 27000.00

101 Raja 7/13/2015 17000.00

102 Ramesh 7/15/2015 34000.00

102 Ramesh 7/15/2015 38000.00

--------------------------------------------
--Writing a Quer to display all the customer who have placed maximum number of order

--Query #1 for inline view

SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC;

--------------------------------

custm_id custm_nm total_odr

--------------------------------

100 Murugappan 2

102 Ramesh 2

101 Raja 1

--------------------------------

--Query #2 for inline view

SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm;

----------
total_odr

----------

----------

Inline view to find all the customers who have placed maximum number of orders

/****************************************

Syntax

SELECT * FROM <query1> x, <query2> y

WHERE contition;

****************************************/

SELECT query1.* FROM

( SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC

) query1,

( SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm

) query2

WHERE query1.total_odr = query2.total_odr;


-------------------------------

custm_id custm_nm total_odr

-------------------------------

100 Murugappan 2

102 Ramesh 2

-------------------------------

DROP TABLE customer_order_det_tb;

--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT

SELECT first_name, salary

FROM ( SELECT first_name, salary

FROM employees e

WHERE job_id NOT IN ('SALESMAN','PRESIDENT')

ORDER BY salary DESC

WHERE ROWNUM < 4;

New Oracle 12c Inline view Syntax


LATERAL clause for In-line views

Allows for columns in the inline view to be accessed!!

Example :

--in 11g

SELECT * FROM employees e, (

SELECT *

FROM departments d

WHERE e.department_id = d.department_id);

ORA-0090: "E"."DEPARTMENT_ID": Invalid Identifier

--in 12c

SELECT * FROM employees e, LATERAL(

SELECT *

FROM departments d

WHERE e.department_id = d.department_id

);

--in 11g

WITH t

AS
( SELECT LEVEL a

FROM dual

CONNECT BY LEVEL <= 30)

SELECT *

FROM t, (SELECT *

FROM employees

WHERE department_id = t.a

);

ORA-00904: "T"."A": invalid Identifier

--in 12c

WITH t

AS

(SELECT LEVEL a FROM dual CONNECT BY LEVEL <= 30)

SELECT * FROM t,

LATERAL(SELECT *

FROM employees

WHERE department_id = t.a);

Hope you have enjoyed this little article

Feed backs are always Welcome :) (:

Posted 20th July 2015 by Unknown


0 Add a comment

JAN

23

Salary Related Questions in Oracle

--creating table

CREATE TABLE employee_data

eid NUMBER(4),

ename VARCHAR2(30),

depno NUMBER(3),

salary NUMBER(8)

);

BEGIN

--Inserting records

INSERT INTO employee_data VALUES(1000,'Name01',90,30000);

INSERT INTO employee_data VALUES(1001,'Name02',90,6000);


INSERT INTO employee_data VALUES(1002,'Name03',90,23000);

INSERT INTO employee_data VALUES(1003,'Name04',60,35000);

INSERT INTO employee_data VALUES(1004,'Name05',60,60000);

INSERT INTO employee_data VALUES(1005,'Name06',60,30000);

INSERT INTO employee_data VALUES(1006,'Name07',80,36000);

INSERT INTO employee_data VALUES(1007,'Name08',80,29000);

INSERT INTO employee_data VALUES(1008,'Name09',80,37000);

INSERT INTO employee_data VALUES(1009,'Name10',80,41000);

COMMIT;

END;

SELECT * FROM employee_data

ORDER BY salary DESC;

--query to find maximum salary from employee_data table

SELECT MAX(salary) FROM employee_data;

--query to find minimum salary from employee_data table

SELECT MIN(salary) FROM employee_data;

--query to find second maximum salary from employee_data table


SELECT MAX(salary)

FROM employee_data

WHERE salary NOT IN (SELECT MAX(salary)

FROM employee_data);

--query to select 5th maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= 5);

--query to select nth maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= &n);


--query to select all the details of the employee whose getting nth maximum salary

SELECT *

FROM (SELECT emp.*,

rownum rn

FROM (SELECT *

FROM employee_data

ORDER BY salary DESC) emp)

WHERE rn = 9;

--same query using row_numbr( ) function

SELECT *

FROM (SELECT emp.*,

row_number() over(ORDER BY salary) rank

FROM employee_data emp)

WHERE rank = 9;

--same query using rank( ) function

SELECT *

FROM (SELECT emp.*,

rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)


WHERE rank = 4;

--same query using dense_rank( ) function

SELECT *

FROM (SELECT emp.*,

dense_rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--query to display display maximum salary in all the department

SELECT e.depno "Department id",

MAX(salary) "Maximum Salary"

FROM employee_data e

GROUP BY e.depno;

--query to display all the employees who are all getting salary more than average salary of the
company

SELECT e.* FROM employee_data e

WHERE salary > (SELECT AVG(salary) FROM employee_data);

--query to display all the employees who are all getting salary more than their department
average salary
SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE department_id = OUT.department_id);

--query to display all the employees who are all getting salary more than their manager salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE employee_id = OUT.manager_id);

Documented By : Murugappan Annamalai


Posted on : 23-Jan-15 16:34:00 IST.

Hope you have enjoyed this little article

Feed backs are always welcome :)

Posted 23rd January 2015 by Unknown

7 View comments

JAN

22

Why prefer COALESCE over NVL

Documented By : Nimish Garg

I prefer using "COALESCE" over "NVL" is some of the scenarios. Last week One of my friend
asked me what is the advantage of using "COALESCE" where we can simply use "NVL". I simply
gave him the reply from Oracle Docs i.e. NVL lets you replace null (returned as a blank) with a
string in the results of a query and COALESCE returns the first non-null expr in the expression list.
Oracle Database uses short-circuit evaluation with "COALESCE".

He replied that he knows the difference, he knows that "COALESCE" can take multiple arguments
and so on. He was more interested in understanding "short-circuit evaluation" of "COALESCE"
and the scenarios where I prefer using "COALESCE" over "NVL".

To make him understand I created following function which takes One second in every execution
and simply returns '--null--' and executed 2 very similar queries one with NVL and other with
COALESCE.
SQL> create or replace function f_null return varchar2

2 is

3 begin

4 dbms_lock.sleep(1);

5 return '--null--';

6 end;

7 /

Function created.

Following are the queries which I used to demonstrate that NVL evaluates both arguments even
if the second argument is not used and COALESCE uses short-circuit evaluation i.e. it only
evaluates the arguments only if they are needed.

SQL> select e.empno, e.ename ename, nvl(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE


7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.

Elapsed: 00:00:14.01

SQL> select e.empno, e.ename ename, coalesce(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE


7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--

14 rows selected.

Elapsed: 00:00:01.01

Here we can see easily that the first query with NVL took 14+ seconds, one second for each
record even if the "f_null" value was used only in one record. On the contrary as mentioned in
Oracle Documentation "COALESCE" uses its "short-circuit evaluation" and "f_null" was called
only once and so second query took only One Second. "COALESCE" is certainly use less resources
than NVL.

Posted 22nd January 2015 by Unknown

0 Add a comment

DEC

21
Constraints

It Enforce Rule On Table

We can create constraint at the time of Creating Table

1. Column Level Declaration

2. Table Level Declaration

1. We can provide own name.

Format : [part_of_project_name-table_name-column_name-constraint_type]

Example : gmind_emp_id_pk _uk _ck _f

2. system name name

Format : sys_cn

Example : SYS_C405323

We can create constraint after the table has been created

Types
Primary Key

Not allowed Null value

Not allowed you to enter duplicate value

Ex : Employee_id, Student_id

Unique Key

allowed Null value

Not allowed you to enter duplicate value

Ex : Contact_no, email

Foreign Key

It will allowed you to enter NULL and Duplicate value.

c1(pk) : 1 2 3

c2(f) : 1 1 2 3 4 Not allowed

Allowed you to enter duplicate value and null value


Not Null

It will not allowed you to enter null value

Check

You can check your own condition

Simple Table for understanding

------------------------------------

Duplicate NULL

------------------------------------

Primary Key X X

Unique Key X Allowed

Foreign Key Allowed Allowed

------------------------------------

creating table with all constraint type

Create table my_stu_details


(

S_id Number(2),

S_name Varchar2(30) Not Null, --SYS_Cn

s_mail Varchar2(30),

s_gender char(1),

s_did Number(3),

Constraint my_stu_sid_pk PRIMARY KEY (s_id),

constraint my_stu_mail_uk UNIQUE (s_mail) ,

Constraint my_stu_gen_ck CHECK (s_gender IN ('M', 'F', 'm', 'f')),

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

);

DESC my_stu_details;

------------------------------------

Name Type Nullable

------------------------------------

S_ID NUMBER(2)

S_NAME VARCHAR2(30)

S_MAIL VARCHAR2(30) Y

S_GENDER CHAR(1) Y

S_DID NUMBER(3) Y

------------------------------------
Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name1' , 'name1@gmail.com' , 'm' , 60 );

Select * from my_stu_details;

Validating Primary Key

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-00001: unique constraint (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (NULL, 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-01400: cannot insert NULL into (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (2 , 'name2' , 'name2@gmail.com' , 'F' , 90 );


Select * from my_stu_details;

Validating NOT NULL Constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , NULL , 'name3@gmail.com' , 'F' , 80 );

ORA-01400: cannot insert NULL into ("HR"."MY_STU_DETAILS"."S_NAME")

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , 'Name3' , 'name3@gmail.com' , 'F' , 80 );

Select * from my_stu_details;

Validating Unique Key Constraint

--Duplicate Check
Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , 'name3@gmail.com' , 'F' , 80 );

ORA-00001: unique constraint (HR.MY_STU_MAIL_UK) violated

--Null Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , null , 'M' , 70 );

Select * from my_stu_details;

Validating Check constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'j' , 70 );

ORA-02290: check constraint (HR.MY_STU_GEN_CK) violated


Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'M' , 70 );

Select * from my_stu_details;

Validating Foreign Key

Select * from Departments;

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 3 );

ORA-02291: integrity constraint (HR.MY_STU_DID_FK) violated - parent key not found

Departments table : parent table

my_stu_details : Child table

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 90 );


Select * from my_stu_details;

--------------------------------------------------------

s_id s_name s_mail s_gender s_did

--------------------------------------------------------

1 name1 name1@gmail.com m 60

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 M 70

5 Name5 name5@gmail.com M 70

6 Name6 name6@gmail.com F 90

--------------------------------------------------------

Deleting the Primary key value which is referred by Foreign Key

Select * from Departments;

DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID

------------------------------------------------------------

60 IT 103 1400 <---- Delete


-- don't execute this query

--Delete From Departments

--Where Department_id = 60;

1) ON DELETE SET NULL

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

1 name1 name1@gmail.com m -

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

2) ON DELETE SET CASCADE

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------
6 Name6 name6@gmail.com F 90

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

Syntax

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE CASCADE

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE SET NULL

Constraint Related Data Dictionary Table information.

To view constraint Information

SELECT c.owner,

c.constraint_name,

c.constraint_type,

c.table_name,
c.r_constraint_name,

c.status

FROM user_constraints c

WHERE c.table_name = 'MY_STU_DETAILS';

------------------------------------------------------------------------------------

owner constraint_name constraint_type table_name r_constraint_name status

------------------------------------------------------------------------------------

HR SYS_C004023 C MY_STU_DETAILS ENABLED

HR MY_STU_GEN_CK C MY_STU_DETAILS ENABLED

HR MY_STU_SID_PK P MY_STU_DETAILS ENABLED

HR MY_STU_MAIL_UK U MY_STU_DETAILS ENABLED

HR MY_STU_DID_FK R MY_STU_DETAILS DEPT_ID_PK ENABLED

------------------------------------------------------------------------------------

To view constraint name with corresponding column name

SELECT * FROM user_cons_columns c

WHERE c.table_name = 'MY_STU_DETAILS';

-------------------------------------------------------------

owner constraint_name table_name column_name position


-------------------------------------------------------------

HR MY_STU_MAIL_UK MY_STU_DETAILS S_MAIL 1

HR MY_STU_SID_PK MY_STU_DETAILS S_ID 1

HR MY_STU_GEN_CK MY_STU_DETAILS S_GENDER

HR SYS_C004023 MY_STU_DETAILS S_NAME

HR MY_STU_DID_FK MY_STU_DETAILS S_DID 1

-------------------------------------------------------------

Creating Composite Primary Key

Creating Primary Key with more than one number of column

ALTER TABLE table_name

ADD CONSTRAINT constraint_name PRIMARY KEY(column1, column_2 , column3);

In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.

creating constraint after the table creation

ALTER TABLE table_name

ADD CONSTRAINT constraint_name CONSTRAINT_TYPE(column_name);


ALTER TABLE table_name

DROP CONSTRAINT constraint_name;

ALTER TABLE table_name

DROP PRIMARY KEY;

To drop related foreign key

ALTER TABLE table_name

DROP PRIMARY KEY CASCADE;

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name;

Disable constraint with related foreign key constraint

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name CASCADE;

ALTER TABLE table_name


ENABLE CONSTRAINT constraint_name;

Interview Questions

What are all the type of constraint available in oracle?

Difference between PRIMARY KEY and UNIQUE key.

Difference between PRIMARY KEY ans FOREIGN KEY.

Difference between UNIQUE key and FOREIGN KEY.

Is it possible to create tow primary key in single table.

Write a syntax to create FOREIGN constraint.

How to create constraint after the table has been created?

How to enable and disable a constraint.

Which data dictionary table contains information about constraints?

Which Data Dictionary table contains information about constraint with corresponding column
name?

What is composite primary key?

Explain ON DELETE CASCADE and ON DELETE SET NULL option.

~Thanks For Reading~

Post your valuable feedback below


Posted 21st December 2014 by Unknown

1 View comments

DEC

listagg in Oracle 11g

Oracle 11gR2 listagg built-in function allows for many table columns to be displayed within a
single row, a non-first-normal form display

Syntax :

listagg(column_value,'delimiter') WITHIN GROUP(ORDER BY column_name)

--Example 1:

CREATE TABLE test_ins(empid NUMBER,product VARCHAR2(30));

BEGIN

INSERT INTO test_ins VALUES( 101,'pendrive');

INSERT INTO test_ins VALUES( 102,'toy');

INSERT INTO test_ins VALUES( 101,'ipod');

INSERT INTO test_ins VALUES( 102,'hat');


INSERT INTO test_ins VALUES( 103,'cpu');

INSERT INTO test_ins VALUES( 104,'pen');

INSERT INTO test_ins VALUES( 104,'car');

INSERT INTO test_ins VALUES( 104,'mat');

INSERT INTO test_ins VALUES( 105,'tv');

INSERT INTO test_ins VALUES( 106,'laptop');

commit;

END;

SELECT * FROM test_ins;

SELECT empid "Employee",

listagg(product,

',') within

GROUP (ORDER BY empid) "Products"

FROM test_ins

GROUP BY empid;

-->-- Result set --<--


DROP TABLE test_ins;

-->-- Example 2

select department_id "Department id", listagg(first_name,', ') WITHIN GROUP(ORDER BY


employee_id) "Employees"

FROM employees

WHERE department_id IN (10,20,30,60)

GROUP BY department_id;

-->-- Result set --<--

Posted 4th December 2014 by Unknown

0 Add a comment
NOV

Condition and Looping Statement

IF

IF ELSE

Multiple IF ELSE

LOOP

FOR LOOP

WHILE LOOP

create table test_udt(id NUMBER, salary NUMBER);

BEGIN

INSERT INTO test_udt VALUES(001,23000);

INSERT INTO test_udt VALUES(002,43000);

INSERT INTO test_udt VALUES(003,78000);

INSERT INTO test_udt VALUES(004,25000);

INSERT INTO test_udt VALUES(005,26000);

INSERT INTO test_udt VALUES(006,90000);

Commit;
END;

select * from test_udt;

IF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 1;

IF v_salary > 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

END IF;

commit;

END;
/

IF ELSE

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

ELSE

UPDATE test_udt t

SET t.salary = v_salary+20007

WHERE t.id = v_id ;

END IF;

commit;

END;

/
--same example with less number of lines

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

v_salary := v_salary+10005;

ELSE

v_salary := v_salary+20007;

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

/
select * from test_udt;

Multiple IF ELSIF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 3;

IF v_id = 1 THEN

v_salary := 1000;

dbms_output.put_line('1 inside');

ELSIF v_id = 2 THEN

v_salary := 2000;

dbms_output.put_line('2 inside');

ELSIF v_id = 3 THEN

v_salary := 3000;

dbms_output.put_line('3 inside');

ELSIF v_id = 4 THEN


v_salary := 4000;

dbms_output.put_line('4 inside');

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

LOOP

--syntax

LOOP

--statements

--increment

--exit statement

END LOOP;
CREATE TABLE prod_details (pid VARCHAR2(3), pname VARCHAR2(30));

DECLARE

i NUMBER := 1;

x VARCHAR2(3);

BEGIN

LOOP

x := lpad(i,3,'0');

dbms_output.put_line('x value : '|| x);

INSERT INTO prod_details VALUES(i, 'Product '||i);

EXIT WHEN i >900;

i := i+1;

IF MOD(i,100) = 0 THEN

commit;

dbms_output.put_line('commit executed');

END IF;

END LOOP;

END;

SELECT * FROM prod_details ORDER BY 1;

DROP TABLE prod_details;


FOR LOOP

BEGIN

FOR I in 1..5

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

FOR LOOP - Reverse

BEGIN

FOR I in REVERSE 14..50

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

WHILE LOOP

DECLARE

i_val NUMBER:=0;

BEGIN
WHILE (i_val < 11)

LOOP

dbms_output.put_line('The value of I is '||i_val);

i_val := i_val + 1;

END LOOP;

END;

sample output:

The value of I is 0

The value of I is 1

The value of I is 2

The value of I is 3

The value of I is 4

The value of I is 5

The value of I is 6

The value of I is 7

The value of I is 8

The value of I is 9

The value of I is 10

Posted 8th November 2014 by Unknown

0 Add a comment
OCT

21

Bulk Collect

This is used for array fetches

With this you can retrieve multiple rows of data with a single round trip.

This reduces the number of context switches between the pl/sql and sql engines.

You can use bulk collect in both dynamic and static sql.

You can use bulk collect in select, fetch into and returning into clauses.

SQL engine automatically initializes and extends the collections you reference in the bulk
collect clause.

You can fetch into multiple collections with one column each.

You can use the limit clause of bulk collect to restrict the no of rows retrieved.

SELECT * FROM product_details;

-->-- Bulk collect in FETCH INTO --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;
CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Bulk collect in SELECT clause --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

BEGIN

SELECT * BULK COLLECT INTO dta FROM product_details;

FOR i IN dta.FIRST .. dta.LAST LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;
END;

-->-- LIMIT in Bulk collect --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta LIMIT 30;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

/
-->-- Multiple fetches in INTO clause --<--

SELECT * FROM product_details;

DECLARE

TYPE alldata_typ1 IS TABLE OF product_details.p_id%TYPE;

TYPE alldata_typ2 IS TABLE OF product_details.p_name%TYPE;

dta1 alldata_typ1;

dta2 alldata_typ2;

CURSOR proddt_cur IS

SELECT p_id, p_name FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta1, dta2;

CLOSE proddt_cur;

FOR i IN dta1.FIRST .. dta1.COUNT LOOP

dbms_output.put_line('Department Id : ' || dta1(i));

END LOOP;

FOR i IN dta2.FIRST .. dta2.COUNT LOOP

dbms_output.put_line('Department Name : ' || dta2(i));

END LOOP;
END;

DROP TABLE dep_details;

DROP TABLE product_details;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Ref Cursor

This is unconstrained cursor which will return different types depends upon the user input.

Ref cursors cannot be closed implicitly.

Ref cursor with return type is called strong cursor.

Ref cursor without return type is called weak cursor.

You can declare ref cursor type in package spec as well as body.

You can declare ref cursor types in local subprograms or anonymous blocks.

CREATE OR REPLACE PROCEDURE ref_c_sp(dep_det_c IN OUT SYS_REFCURSOR)

AS
BEGIN

OPEN dep_det_c

FOR

SELECT * FROM dep_details d;

END;

DECLARE

dep_det_c SYS_REFCURSOR;

tab_data dep_details%ROWTYPE;

BEGIN

ref_c_sp(dep_det_c);

LOOP

FETCH dep_det_c INTO tab_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department Name : '|| tab_data.d_name);

END LOOP;

CLOSE dep_det_c;

END;

/*sample output*/
Department Name : Admin

Department Name : HR

Department Name : Sales

Department Name : Marketing

DROP PROCEDURE ref_c_sp;

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Cursor

SQL Private work Area where the query get passed and executed.

Types

******

Implicit(SQL)

Explicit

-->-- advanced cursor types --<--

Parametrized Cursor
Ref Cursor

Implicit

********

ORACLE implicitly opens a cursor to process each SQL statement not associated with an
explicitly declared cursor.

PL/SQL lets you refer to the most recent implicit cursor as the SQL” cursor. So, although you
cannot use the OPEN,

FETCH, and CLOSE statements to control an implicit cursor, you can still use cursor attributes to
access information

about the most recently executed SQL statement.

Cursor Stages

**************

OPEN cursor_name

FETCH (with in loop)

CLOSE cursor_name

Explicit

The set of rows returned by a query can consist of zero, one, or multiple rows,

depending on how many rows meet your search criteria. When a query returns multiple rows,

you can explicitly define a cursor to process the rows. You use three commands to control the
cursor
Cursor Attributes

*****************

%FOUND

%NOTFOUND

%ISOPEN

%ROWCOUNT

%BULK_ROWCOUNT --<-- used to handle error while using bulk collection.

%BULK_EXCEPTIONS --<-- used to handle error while using bulk collection.

Cursor Declaration

DECLARE

CURSOR <cursor_name>

IS

<SELECT statement>

BEGIN

--> some stmt

END;

Cursor Loop

Loop

While Loop
For Loop

Cursor Clauses

Return

For update

Where current of

Bulk collect

-->-- creating table

create table product_details

p_id NUMBER,

p_name VARCHAR2(30),

p_order_dt DATE

);

-->-- Inserting data

BEGIN

FOR i IN 1 .. 75 LOOP

INSERT INTO product_details VALUES (i, 'prod_name_' || i, SYSDATE + i);

END LOOP;

commit;
END;

-->-- selecting data

SELECT * FROM product_details;

---------------------------------------------

p_id p_name p_order_dt

---------------------------------------------

1 prod_name_1 10/11/2014 3:48:32 PM

2 prod_name_2 10/12/2014 3:48:32 PM

3 prod_name_3 10/13/2014 3:48:32 PM

4 prod_name_4 10/14/2014 3:48:32 PM

5 prod_name_5 10/15/2014 3:48:32 PM

6 prod_name_6 10/16/2014 3:48:32 PM

7 prod_name_7 10/17/2014 3:48:32 PM

8 prod_name_8 10/18/2014 3:48:32 PM

9 prod_name_9 10/19/2014 3:48:32 PM

10 prod_name_10 10/20/2014 3:48:32 PM

11 prod_name_11 10/21/2014 3:48:32 PM

12 prod_name_12 10/22/2014 3:48:32 PM

13 prod_name_13 10/23/2014 3:48:32 PM

14 prod_name_14 10/24/2014 3:48:32 PM

15 prod_name_15 10/25/2014 3:48:32 PM


16 prod_name_16 10/26/2014 3:48:32 PM

17 prod_name_17 10/27/2014 3:48:32 PM

18 prod_name_18 10/28/2014 3:48:32 PM

19 prod_name_19 10/29/2014 3:48:32 PM

20 prod_name_20 10/30/2014 3:48:32 PM

---------------------------------------------

----------------------------------------------

Implicit Cursor

----------------------------------------------

--will update soon

----------------------------------------------

Explicit Cursor

----------------------------------------------

**********************************************

Processing cursor data by using LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration
CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND; --<-- if next record not found means control will
come out from the loop

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )


DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

EXIT WHEN prod_detail_cur%FOUND; --<-- if next record found means control will come
out from the loop

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )


DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');


END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor Already closed

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;
LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

-->-- CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )


Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor closed

**********************************************

Processing cursor data by using WHILE LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

OPEN prod_detail_cur;

FETCH prod_detail_cur

INTO all_data;

WHILE prod_detail_cur%FOUND LOOP

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||


' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

FETCH prod_detail_cur

INTO all_data;

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

************************************************************

Processing cursor data by using FOR LOOP - CURSOR FOR LOOP

************************************************************

DECLARE

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN
FOR i IN prod_detail_cur

LOOP

dbms_output.put_line('Product id : ' || i.p_id ||

' Product Name : ' || i.p_name ||

' ( Orderd on : ' || TRIM(i.p_order_dt) || ' )');

END LOOP;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

Parameterized Cursor

*********************

This was used when you are going to use the cursor in more than one place with different
values for the same where clause.

Cursor parameters must be in mode.

Cursor parameters may have default values.


The scope of cursor parameter is within the select statement.

CREATE TABLE dep_details(d_id NUMBER,d_name VARCHAR2(30), location_id NUMBER);

BEGIN

INSRT INTO dep_details VALUES(001,'Admin',1010);

INSRT INTO dep_details VALUES(002,'HR',1010);

INSRT INTO dep_details VALUES(003,'Sales',1020);

INSRT INTO dep_details VALUES(004,'Marketing',1020);

commit;

END;

SELECT * FROM dep_details;

----------------------------

d_id d_name location_id

----------------------------

1 Admin 1010

2 HR 1010

3 Sales 1020

4 Marketing 1020

----------------------------
DECLARE

-->--Declaring parameterized cursor

CURSOR dep_det_c(p_location_id NUMBER) IS

SELECT * FROM dep_details d WHERE d.location_id = p_location_id;

all_data dep_details%ROWTYPE;

BEGIN

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

OPEN dep_det_c(1010);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

-->-- opening same cursor with different input value

OPEN dep_det_c(1020);

LOOP

FETCH dep_det_c
INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

END;

/*sample output*/

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 1 Department Name : Admin

Department id : 2 Department Name : HR

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 3 Department Name : Sales

Department id : 4 Department Name : Marketing

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Posted 21st October 2014 by Unknown

0 Add a comment
OCT

21

Handling Exception

Error Handling in oracle

ERROR

Any departure from the expected behavior of the system or program,

which stops the working of the system is an error.

Types : compile time error

Run time error

EXCEPTION

Any error or problem which one can handle and continue to work normally.

Handling Exception

When exception is raised, control passes to the exception section of the block.

i.e. EXCEPTION

WHEN name_of_exception THEN

Types : Pre Defined Exceptions

User Defined Exceptions


Predefined Exception

*********************

Oracle has predefined several exceptions that correspond to the most common oracle errors.

------------------------------------------------------------------------

Exception Oracle Error SQL Code Value

------------------------------------------------------------------------

ZERO_DIVIDE ORA-01476 -1476

NO_DATA_FOUND ORA-01403 +100

DUP_VAL_ON_INDEX ORA-00001 -1

TOO_MANY_ROWS ORA-01422 -1422

VALUE_ERROR ORA-06502 -6502

CURSOR_ALREADY_OPEN ORA-06511 -6511

OTHERS

------------------------------------------------------------------------

-->-- ZERO_DIVIDE --<--

Your program attempts to divide a number by zero.

DECLARE

v_result NUMBER;
BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN ZERO_DIVIDE THEN

dbms_output.put_line('Divisor is equal to zero');

END;

-->-- NO_DATA_FOUND --<--

Single row SELECT returned no rows or your program referenced a deleted element in a nested
table

or an uninitialized element in an associative array (index-by table).

CREATE TABLE test_tb(id NUMBER PRIMARY KEY);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN NO_DATA_FOUND THEN

dbms_output.put_line('There is no data inside the table');

END;
-->-- DUP_VAL_ON_INDEX --<--

A program attempted to insert duplicate values in a column that is constrained by a unique


index.

INSERT INTO test_tb VALUES (1);

INSERT INTO test_tb VALUES (2);

commit;

BEGIN

INSERT INTO test_tb VALUES (2);

EXCEPTION

WHEN DUP_VAL_ON_INDEX THEN

dbms_output.put_line('Duplicate values are not allowed');

END;

-->-- TOO_MANY_ROWS --<--

Single row SELECT returned multiple rows.

DECLARE

v_id NUMBER;
BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN TOO_MANY_ROWS THEN

dbms_output.put_line('Query returning more than one row');

END;

DROP TABLE test_tb;

-->-- VALUE_ERROR --<--

An arithmetic, conversion, truncation, or size constraint error occurred.

DECLARE

num1 NUMBER(2);

BEGIN

num1 := 345;

EXCEPTION

WHEN VALUE_ERROR THEN

dbms_output.put_line('check the size of the variable');

END;

-->-- CURSOR_ALREADY_OPEN --<--


A program attempted to open an already opened cursor.

CREATE TABLE emp(id NUMBER, name VARCHAR2(30));

BEGIN

INSERT INTO emp VALUES(1,'Name1');

INSERT INTO emp VALUES(2,'Name2');

INSERT INTO emp VALUES(3,'Name3');

INSERT INTO emp VALUES(4,'Name4');

COMMIT;

END;

SELECT * FROM emp;

DECLARE

cursor emp_c IS

SELECT * FROM emp;

all_data emp%ROWTYPE;

BEGIN

OPEN emp_c;

OPEN emp_c;

NULL;
CLOSE emp_c;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

END;

DROP TABLE emp;

-->-- OTHERS --<--

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

WHEN OTHERS THEN

dbms_output.put_line('Some other error ' || SQLERRM);

END;

User Defined Exception

**********************
A user-defined exception is an error that is defined by the programmer.

User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,

exceptions have a type EXCEPTION and scope.

DECLARE

v_gender CHAR := '&gender';

gender_ex EXCEPTION;

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE gender_ex;

END IF;

dbms_output.put_line('Gender : '||v_gender);

EXCEPTION

WHEN gender_ex THEN

dbms_output.put_line('Please Enter valid gender');

END;

create table test_insert (id NUMBER, Name VARCHAR2(30));

DECLARE

abort_ex EXCEPTION;
BEGIN

FOR i IN 1..100

LOOP

BEGIN

IF mod(i,10)=0 THEN

RAISE abort_ex;

END IF;

INSERT INTO test_insert VALUES(i, 'Name'||i);

EXCEPTION

WHEN abort_ex THEN

NULL;

END;

END LOOP;

COMMIT;

END;

SELECT * FROM test_insert;

DROP TABLE test_insert;

SQLERRM and SQLCODE

********************

SQLCODE returns the current error code, and SQLERRM returns the current error message
text;
For user-defined exception SQLCODE returns 1 and SQLERRM returns “user-defined
exception”.

SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.

CREATE TABLE test_tb (id NUMBER);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

dbms_output.put_line(v_id);

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('SQLERRM : ' || SQLERRM);

dbms_output.put_line('SQLCODE : ' || SQLCODE);

END;

/*sample output*/

SQLERRM : ORA-01403: no data found

SQLCODE : 100

DROP TABLE test_tb;


PRAGMA EXCEPTION_INIT

*********************

Using this you can associate a named exception with a particular oracle error.

This gives you the ability to trap this error specifically, rather than via an OTHERS handler.

Syntax:

PRAGMA EXCEPTION_INIT(exception_name, oracle_error_number);

DECLARE

v_result NUMBER;

PRAGMA EXCEPTION_INIT(Invalid, -1476);

BEGIN

SELECT 453 / 0 INTO v_result FROM dual;

dbms_output.put_line('Result : ' || v_result);

EXCEPTION

WHEN INVALID THEN

dbms_output.put_line('Invalid Exception');

END;

RAISE_APPLICATION_ERROR
************************

You can use this built-in function to create your own error messages, which can be more
descriptive than named exceptions.

Error Number :

Oracle Error Range : From -00000 to -19999

User Error Range : From -20000 to -20999

DECLARE

v_gender CHAR := '&gender';

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE_APPLICATION_ERROR(-20003, 'Enter valid gender');

END IF;

dbms_output.put_line('Gender : ' || v_gender);

END;

Posted 21st October 2014 by Unknown

1 View comments
Loading

Dynamic Views theme. Powered by Blogger.

Oracle sql & Pl/sql

search

Home Sql and pl/sql Sql Interview Questions

JUL

20

INLINE view in Oracle with 12c New Features

Named sub Query in FROM clause is call it as INLINE VIEW.

Oracle process a inline view faster than sub query

Inline View in Oracle

--Query to display all the employees who are all getting salary more than their department
average salary

SELECT First_name

, last_name

, salary

, department_id

FROM employees a , ( SELECT b.department_id


, AVG(b.salary) avg_sal

FROM employees b

GROUP BY b.department_id

)b

WHERE a.department_id = b.department_id

AND a.salary > b.avg_salary;

Display all the customer who have placed more number of orders by using INLINE view

CREATE TABLE customer_order_det_tb

( custm_id NUMBER ,

custm_nm VARCHAR2(30) ,

order_dt DATE DEFAULT SYSDATE ,

ttl_amt NUMBER(7,2)

);

BEGIN

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '11-Jul-15' , 45000.00);

INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '14-Jul-15' , 27000.00);

INSERT INTO customer_order_det_tb VALUES(101, 'Raja' , '13-Jul-15' , 17000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 34000.00);

INSERT INTO customer_order_det_tb VALUES(102, 'Ramesh' , '15-Jul-15' , 38000.00);

COMMIT;

END;
SELECT c.*

FROM customer_order_det_tb c;

--------------------------------------------

custm_id custm_nm order_dt ttl_amt

--------------------------------------------

100 Murugappan 7/11/2015 45000.00

100 Murugappan 7/14/2015 27000.00

101 Raja 7/13/2015 17000.00

102 Ramesh 7/15/2015 34000.00

102 Ramesh 7/15/2015 38000.00

--------------------------------------------

--Writing a Quer to display all the customer who have placed maximum number of order

--Query #1 for inline view

SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC;

--------------------------------
custm_id custm_nm total_odr

--------------------------------

100 Murugappan 2

102 Ramesh 2

101 Raja 1

--------------------------------

--Query #2 for inline view

SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm;

----------

total_odr

----------

----------

Inline view to find all the customers who have placed maximum number of orders

/****************************************

Syntax

SELECT * FROM <query1> x, <query2> y


WHERE contition;

****************************************/

SELECT query1.* FROM

( SELECT c.custm_id, c.custm_nm, COUNT(*) total_odr

FROM customer_order_det_tb c

GROUP BY c.custm_id,c.custm_nm

ORDER BY total_odr DESC

) query1,

( SELECT MAX(COUNT(*)) total_odr

FROM customer_order_det_tb cnt

GROUP BY cnt.custm_id, cnt.custm_nm

) query2

WHERE query1.total_odr = query2.total_odr;

-------------------------------

custm_id custm_nm total_odr

-------------------------------

100 Murugappan 2

102 Ramesh 2

-------------------------------

DROP TABLE customer_order_det_tb;

--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT
SELECT first_name, salary

FROM ( SELECT first_name, salary

FROM employees e

WHERE job_id NOT IN ('SALESMAN','PRESIDENT')

ORDER BY salary DESC

WHERE ROWNUM < 4;

New Oracle 12c Inline view Syntax

LATERAL clause for In-line views

Allows for columns in the inline view to be accessed!!

Example :

--in 11g

SELECT * FROM employees e, (

SELECT *

FROM departments d

WHERE e.department_id = d.department_id);


ORA-0090: "E"."DEPARTMENT_ID": Invalid Identifier

--in 12c

SELECT * FROM employees e, LATERAL(

SELECT *

FROM departments d

WHERE e.department_id = d.department_id

);

--in 11g

WITH t

AS

( SELECT LEVEL a

FROM dual

CONNECT BY LEVEL <= 30)

SELECT *

FROM t, (SELECT *

FROM employees

WHERE department_id = t.a

);

ORA-00904: "T"."A": invalid Identifier


--in 12c

WITH t

AS

(SELECT LEVEL a FROM dual CONNECT BY LEVEL <= 30)

SELECT * FROM t,

LATERAL(SELECT *

FROM employees

WHERE department_id = t.a);

Hope you have enjoyed this little article

Feed backs are always Welcome :) (:

Posted 20th July 2015 by Unknown

0 Add a comment

JAN

23

Salary Related Questions in Oracle

--creating table
CREATE TABLE employee_data

eid NUMBER(4),

ename VARCHAR2(30),

depno NUMBER(3),

salary NUMBER(8)

);

BEGIN

--Inserting records

INSERT INTO employee_data VALUES(1000,'Name01',90,30000);

INSERT INTO employee_data VALUES(1001,'Name02',90,6000);

INSERT INTO employee_data VALUES(1002,'Name03',90,23000);

INSERT INTO employee_data VALUES(1003,'Name04',60,35000);

INSERT INTO employee_data VALUES(1004,'Name05',60,60000);

INSERT INTO employee_data VALUES(1005,'Name06',60,30000);

INSERT INTO employee_data VALUES(1006,'Name07',80,36000);

INSERT INTO employee_data VALUES(1007,'Name08',80,29000);

INSERT INTO employee_data VALUES(1008,'Name09',80,37000);

INSERT INTO employee_data VALUES(1009,'Name10',80,41000);

COMMIT;

END;

/
SELECT * FROM employee_data

ORDER BY salary DESC;

--query to find maximum salary from employee_data table

SELECT MAX(salary) FROM employee_data;

--query to find minimum salary from employee_data table

SELECT MIN(salary) FROM employee_data;

--query to find second maximum salary from employee_data table

SELECT MAX(salary)

FROM employee_data

WHERE salary NOT IN (SELECT MAX(salary)

FROM employee_data);

--query to select 5th maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary


FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= 5);

--query to select nth maximum salary

SELECT MIN(salary)

FROM (SELECT salary

FROM (SELECT salary

FROM employee_data

ORDER BY salary DESC)

WHERE rownum <= &n);

--query to select all the details of the employee whose getting nth maximum salary

SELECT *

FROM (SELECT emp.*,

rownum rn

FROM (SELECT *

FROM employee_data

ORDER BY salary DESC) emp)

WHERE rn = 9;
--same query using row_numbr( ) function

SELECT *

FROM (SELECT emp.*,

row_number() over(ORDER BY salary) rank

FROM employee_data emp)

WHERE rank = 9;

--same query using rank( ) function

SELECT *

FROM (SELECT emp.*,

rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;

--same query using dense_rank( ) function

SELECT *

FROM (SELECT emp.*,

dense_rank() over(ORDER BY salary DESC) rank

FROM employee_data emp)

WHERE rank = 4;
--query to display display maximum salary in all the department

SELECT e.depno "Department id",

MAX(salary) "Maximum Salary"

FROM employee_data e

GROUP BY e.depno;

--query to display all the employees who are all getting salary more than average salary of the
company

SELECT e.* FROM employee_data e

WHERE salary > (SELECT AVG(salary) FROM employee_data);

--query to display all the employees who are all getting salary more than their department
average salary

SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE department_id = OUT.department_id);

--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,

first_name,

salary

FROM employees OUT

WHERE salary > (SELECT AVG(salary)

FROM employees

WHERE employee_id = OUT.manager_id);

Documented By : Murugappan Annamalai

Posted on : 23-Jan-15 16:34:00 IST.

Hope you have enjoyed this little article

Feed backs are always welcome :)

Posted 23rd January 2015 by Unknown

7 View comments

JAN

22
Why prefer COALESCE over NVL

Documented By : Nimish Garg

I prefer using "COALESCE" over "NVL" is some of the scenarios. Last week One of my friend
asked me what is the advantage of using "COALESCE" where we can simply use "NVL". I simply
gave him the reply from Oracle Docs i.e. NVL lets you replace null (returned as a blank) with a
string in the results of a query and COALESCE returns the first non-null expr in the expression list.
Oracle Database uses short-circuit evaluation with "COALESCE".

He replied that he knows the difference, he knows that "COALESCE" can take multiple arguments
and so on. He was more interested in understanding "short-circuit evaluation" of "COALESCE"
and the scenarios where I prefer using "COALESCE" over "NVL".

To make him understand I created following function which takes One second in every execution
and simply returns '--null--' and executed 2 very similar queries one with NVL and other with
COALESCE.

SQL> create or replace function f_null return varchar2

2 is

3 begin

4 dbms_lock.sleep(1);

5 return '--null--';

6 end;

7 /

Function created.
Following are the queries which I used to demonstrate that NVL evaluates both arguments even
if the second argument is not used and COALESCE uses short-circuit evaluation i.e. it only
evaluates the arguments only if they are needed.

SQL> select e.empno, e.ename ename, nvl(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--


14 rows selected.

Elapsed: 00:00:14.01

SQL> select e.empno, e.ename ename, coalesce(m.ename,f_null) mname

2 from scott.emp e, scott.emp m

3 where e.mgr = m.empno(+);

EMPNO ENAME MNAME

---------- ---------- ----------

7902 FORD JONES

7788 SCOTT JONES

7900 JAMES BLAKE

7844 TURNER BLAKE

7654 MARTIN BLAKE

7521 WARD BLAKE

7499 ALLEN BLAKE

7934 MILLER CLARK

7876 ADAMS SCOTT

7782 CLARK KING

7698 BLAKE KING

7566 JONES KING

7369 SMITH FORD

7839 KING --null--


14 rows selected.

Elapsed: 00:00:01.01

Here we can see easily that the first query with NVL took 14+ seconds, one second for each
record even if the "f_null" value was used only in one record. On the contrary as mentioned in
Oracle Documentation "COALESCE" uses its "short-circuit evaluation" and "f_null" was called
only once and so second query took only One Second. "COALESCE" is certainly use less resources
than NVL.

Posted 22nd January 2015 by Unknown

0 Add a comment

DEC

21

Constraints

It Enforce Rule On Table

We can create constraint at the time of Creating Table

1. Column Level Declaration

2. Table Level Declaration


1. We can provide own name.

Format : [part_of_project_name-table_name-column_name-constraint_type]

Example : gmind_emp_id_pk _uk _ck _f

2. system name name

Format : sys_cn

Example : SYS_C405323

We can create constraint after the table has been created

Types

Primary Key

Not allowed Null value

Not allowed you to enter duplicate value

Ex : Employee_id, Student_id

Unique Key
allowed Null value

Not allowed you to enter duplicate value

Ex : Contact_no, email

Foreign Key

It will allowed you to enter NULL and Duplicate value.

c1(pk) : 1 2 3

c2(f) : 1 1 2 3 4 Not allowed

Allowed you to enter duplicate value and null value

Not Null

It will not allowed you to enter null value

Check

You can check your own condition

Simple Table for understanding


------------------------------------

Duplicate NULL

------------------------------------

Primary Key X X

Unique Key X Allowed

Foreign Key Allowed Allowed

------------------------------------

creating table with all constraint type

Create table my_stu_details

S_id Number(2),

S_name Varchar2(30) Not Null, --SYS_Cn

s_mail Varchar2(30),

s_gender char(1),

s_did Number(3),

Constraint my_stu_sid_pk PRIMARY KEY (s_id),

constraint my_stu_mail_uk UNIQUE (s_mail) ,

Constraint my_stu_gen_ck CHECK (s_gender IN ('M', 'F', 'm', 'f')),

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

);
DESC my_stu_details;

------------------------------------

Name Type Nullable

------------------------------------

S_ID NUMBER(2)

S_NAME VARCHAR2(30)

S_MAIL VARCHAR2(30) Y

S_GENDER CHAR(1) Y

S_DID NUMBER(3) Y

------------------------------------

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name1' , 'name1@gmail.com' , 'm' , 60 );

Select * from my_stu_details;

Validating Primary Key


Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (1 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-00001: unique constraint (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (NULL, 'name2' , 'name2@gmail.com' , 'F' , 90 );

ORA-01400: cannot insert NULL into (HR.MY_STU_SID_PK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (2 , 'name2' , 'name2@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

Validating NOT NULL Constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , NULL , 'name3@gmail.com' , 'F' , 80 );


ORA-01400: cannot insert NULL into ("HR"."MY_STU_DETAILS"."S_NAME")

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (3 , 'Name3' , 'name3@gmail.com' , 'F' , 80 );

Select * from my_stu_details;

Validating Unique Key Constraint

--Duplicate Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , 'name3@gmail.com' , 'F' , 80 );

ORA-00001: unique constraint (HR.MY_STU_MAIL_UK) violated

--Null Check

Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)

values (4 , 'Name4' , null , 'M' , 70 );


Select * from my_stu_details;

Validating Check constraint

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'j' , 70 );

ORA-02290: check constraint (HR.MY_STU_GEN_CK) violated

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (5 , 'Name5' , 'name5@gmail.com' , 'M' , 70 );

Select * from my_stu_details;

Validating Foreign Key

Select * from Departments;


Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 3 );

ORA-02291: integrity constraint (HR.MY_STU_DID_FK) violated - parent key not found

Departments table : parent table

my_stu_details : Child table

Insert into my_stu_details (s_id, s_name , s_mail , s_gender , s_did)

values (6 , 'Name6' , 'name6@gmail.com' , 'F' , 90 );

Select * from my_stu_details;

--------------------------------------------------------

s_id s_name s_mail s_gender s_did

--------------------------------------------------------

1 name1 name1@gmail.com m 60

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 M 70
5 Name5 name5@gmail.com M 70

6 Name6 name6@gmail.com F 90

--------------------------------------------------------

Deleting the Primary key value which is referred by Foreign Key

Select * from Departments;

DEPARTMENT_ID DEPARTMENT_NAME MANAGER_ID LOCATION_ID

------------------------------------------------------------

60 IT 103 1400 <---- Delete

-- don't execute this query

--Delete From Departments

--Where Department_id = 60;

1) ON DELETE SET NULL

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID


-------------------------------------------------

6 Name6 name6@gmail.com F 90

1 name1 name1@gmail.com m -

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

2) ON DELETE SET CASCADE

-------------------------------------------------

S_ID S_NAME S_MAIL S_GENDER S_DID

-------------------------------------------------

6 Name6 name6@gmail.com F 90

2 name2 name2@gmail.com F 90

3 Name3 name3@gmail.com F 80

4 Name4 - M 70

5 Name5 name5@gmail.com M 70

-------------------------------------------------

Syntax

Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE CASCADE
Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)

ON DELETE SET NULL

Constraint Related Data Dictionary Table information.

To view constraint Information

SELECT c.owner,

c.constraint_name,

c.constraint_type,

c.table_name,

c.r_constraint_name,

c.status

FROM user_constraints c

WHERE c.table_name = 'MY_STU_DETAILS';

------------------------------------------------------------------------------------

owner constraint_name constraint_type table_name r_constraint_name status

------------------------------------------------------------------------------------

HR SYS_C004023 C MY_STU_DETAILS ENABLED

HR MY_STU_GEN_CK C MY_STU_DETAILS ENABLED


HR MY_STU_SID_PK P MY_STU_DETAILS ENABLED

HR MY_STU_MAIL_UK U MY_STU_DETAILS ENABLED

HR MY_STU_DID_FK R MY_STU_DETAILS DEPT_ID_PK ENABLED

------------------------------------------------------------------------------------

To view constraint name with corresponding column name

SELECT * FROM user_cons_columns c

WHERE c.table_name = 'MY_STU_DETAILS';

-------------------------------------------------------------

owner constraint_name table_name column_name position

-------------------------------------------------------------

HR MY_STU_MAIL_UK MY_STU_DETAILS S_MAIL 1

HR MY_STU_SID_PK MY_STU_DETAILS S_ID 1

HR MY_STU_GEN_CK MY_STU_DETAILS S_GENDER

HR SYS_C004023 MY_STU_DETAILS S_NAME

HR MY_STU_DID_FK MY_STU_DETAILS S_DID 1

-------------------------------------------------------------

Creating Composite Primary Key


Creating Primary Key with more than one number of column

ALTER TABLE table_name

ADD CONSTRAINT constraint_name PRIMARY KEY(column1, column_2 , column3);

In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.

creating constraint after the table creation

ALTER TABLE table_name

ADD CONSTRAINT constraint_name CONSTRAINT_TYPE(column_name);

ALTER TABLE table_name

DROP CONSTRAINT constraint_name;

ALTER TABLE table_name

DROP PRIMARY KEY;

To drop related foreign key


ALTER TABLE table_name

DROP PRIMARY KEY CASCADE;

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name;

Disable constraint with related foreign key constraint

ALTER TABLE table_name

DISABLE CONSTRAINT constraint_name CASCADE;

ALTER TABLE table_name

ENABLE CONSTRAINT constraint_name;

Interview Questions

What are all the type of constraint available in oracle?

Difference between PRIMARY KEY and UNIQUE key.

Difference between PRIMARY KEY ans FOREIGN KEY.

Difference between UNIQUE key and FOREIGN KEY.


Is it possible to create tow primary key in single table.

Write a syntax to create FOREIGN constraint.

How to create constraint after the table has been created?

How to enable and disable a constraint.

Which data dictionary table contains information about constraints?

Which Data Dictionary table contains information about constraint with corresponding column
name?

What is composite primary key?

Explain ON DELETE CASCADE and ON DELETE SET NULL option.

~Thanks For Reading~

Post your valuable feedback below

Posted 21st December 2014 by Unknown

1 View comments

DEC

listagg in Oracle 11g

Oracle 11gR2 listagg built-in function allows for many table columns to be displayed within a
single row, a non-first-normal form display
Syntax :

listagg(column_value,'delimiter') WITHIN GROUP(ORDER BY column_name)

--Example 1:

CREATE TABLE test_ins(empid NUMBER,product VARCHAR2(30));

BEGIN

INSERT INTO test_ins VALUES( 101,'pendrive');

INSERT INTO test_ins VALUES( 102,'toy');

INSERT INTO test_ins VALUES( 101,'ipod');

INSERT INTO test_ins VALUES( 102,'hat');

INSERT INTO test_ins VALUES( 103,'cpu');

INSERT INTO test_ins VALUES( 104,'pen');

INSERT INTO test_ins VALUES( 104,'car');

INSERT INTO test_ins VALUES( 104,'mat');

INSERT INTO test_ins VALUES( 105,'tv');

INSERT INTO test_ins VALUES( 106,'laptop');

commit;

END;

SELECT * FROM test_ins;


SELECT empid "Employee",

listagg(product,

',') within

GROUP (ORDER BY empid) "Products"

FROM test_ins

GROUP BY empid;

-->-- Result set --<--

DROP TABLE test_ins;


-->-- Example 2

select department_id "Department id", listagg(first_name,', ') WITHIN GROUP(ORDER BY


employee_id) "Employees"

FROM employees

WHERE department_id IN (10,20,30,60)

GROUP BY department_id;

-->-- Result set --<--

Posted 4th December 2014 by Unknown

0 Add a comment

NOV

Condition and Looping Statement

IF

IF ELSE

Multiple IF ELSE

LOOP
FOR LOOP

WHILE LOOP

create table test_udt(id NUMBER, salary NUMBER);

BEGIN

INSERT INTO test_udt VALUES(001,23000);

INSERT INTO test_udt VALUES(002,43000);

INSERT INTO test_udt VALUES(003,78000);

INSERT INTO test_udt VALUES(004,25000);

INSERT INTO test_udt VALUES(005,26000);

INSERT INTO test_udt VALUES(006,90000);

Commit;

END;

select * from test_udt;

IF

DECLARE

v_salary NUMBER;
v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 1;

IF v_salary > 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

END IF;

commit;

END;

IF ELSE

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary
FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

UPDATE test_udt t

SET t.salary = v_salary+10005

WHERE t.id = v_id ;

ELSE

UPDATE test_udt t

SET t.salary = v_salary+20007

WHERE t.id = v_id ;

END IF;

commit;

END;

--same example with less number of lines

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN

SELECT id,salary

INTO v_id,v_salary
FROM test_udt

WHERE id = 2;

IF v_salary < 20000 THEN

v_salary := v_salary+10005;

ELSE

v_salary := v_salary+20007;

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

select * from test_udt;

Multiple IF ELSIF

DECLARE

v_salary NUMBER;

v_id NUMBER;

BEGIN
SELECT id,salary

INTO v_id,v_salary

FROM test_udt

WHERE id = 3;

IF v_id = 1 THEN

v_salary := 1000;

dbms_output.put_line('1 inside');

ELSIF v_id = 2 THEN

v_salary := 2000;

dbms_output.put_line('2 inside');

ELSIF v_id = 3 THEN

v_salary := 3000;

dbms_output.put_line('3 inside');

ELSIF v_id = 4 THEN

v_salary := 4000;

dbms_output.put_line('4 inside');

END IF;

UPDATE test_udt t

SET t.salary = v_salary

WHERE t.id = v_id ;

commit;

END;

/
select * from test_udt;

LOOP

--syntax

LOOP

--statements

--increment

--exit statement

END LOOP;

CREATE TABLE prod_details (pid VARCHAR2(3), pname VARCHAR2(30));

DECLARE

i NUMBER := 1;

x VARCHAR2(3);

BEGIN

LOOP

x := lpad(i,3,'0');

dbms_output.put_line('x value : '|| x);

INSERT INTO prod_details VALUES(i, 'Product '||i);


EXIT WHEN i >900;

i := i+1;

IF MOD(i,100) = 0 THEN

commit;

dbms_output.put_line('commit executed');

END IF;

END LOOP;

END;

SELECT * FROM prod_details ORDER BY 1;

DROP TABLE prod_details;

FOR LOOP

BEGIN

FOR I in 1..5

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

/
FOR LOOP - Reverse

BEGIN

FOR I in REVERSE 14..50

LOOP

Dbms_output.put_line('The value of i : '||i);

END LOOP;

END;

WHILE LOOP

DECLARE

i_val NUMBER:=0;

BEGIN

WHILE (i_val < 11)

LOOP

dbms_output.put_line('The value of I is '||i_val);

i_val := i_val + 1;

END LOOP;

END;

sample output:
The value of I is 0

The value of I is 1

The value of I is 2

The value of I is 3

The value of I is 4

The value of I is 5

The value of I is 6

The value of I is 7

The value of I is 8

The value of I is 9

The value of I is 10

Posted 8th November 2014 by Unknown

0 Add a comment

OCT

21

Bulk Collect

This is used for array fetches

With this you can retrieve multiple rows of data with a single round trip.

This reduces the number of context switches between the pl/sql and sql engines.

You can use bulk collect in both dynamic and static sql.
You can use bulk collect in select, fetch into and returning into clauses.

SQL engine automatically initializes and extends the collections you reference in the bulk
collect clause.

You can fetch into multiple collections with one column each.

You can use the limit clause of bulk collect to restrict the no of rows retrieved.

SELECT * FROM product_details;

-->-- Bulk collect in FETCH INTO --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS

SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);


END LOOP;

END;

-->-- Bulk collect in SELECT clause --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

BEGIN

SELECT * BULK COLLECT INTO dta FROM product_details;

FOR i IN dta.FIRST .. dta.LAST LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- LIMIT in Bulk collect --<--

DECLARE

TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;

dta alldata_typ;

CURSOR proddt_cur IS
SELECT * FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta LIMIT 30;

CLOSE proddt_cur;

FOR i IN dta.FIRST .. dta.COUNT LOOP

dbms_output.put_line(dta(i).p_name || ' department id is ' || dta(i).p_id);

END LOOP;

END;

-->-- Multiple fetches in INTO clause --<--

SELECT * FROM product_details;

DECLARE

TYPE alldata_typ1 IS TABLE OF product_details.p_id%TYPE;

TYPE alldata_typ2 IS TABLE OF product_details.p_name%TYPE;

dta1 alldata_typ1;

dta2 alldata_typ2;

CURSOR proddt_cur IS
SELECT p_id, p_name FROM product_details;

BEGIN

OPEN proddt_cur;

FETCH proddt_cur BULK COLLECT

INTO dta1, dta2;

CLOSE proddt_cur;

FOR i IN dta1.FIRST .. dta1.COUNT LOOP

dbms_output.put_line('Department Id : ' || dta1(i));

END LOOP;

FOR i IN dta2.FIRST .. dta2.COUNT LOOP

dbms_output.put_line('Department Name : ' || dta2(i));

END LOOP;

END;

DROP TABLE dep_details;

DROP TABLE product_details;

Posted 21st October 2014 by Unknown

0 Add a comment
OCT

21

Ref Cursor

This is unconstrained cursor which will return different types depends upon the user input.

Ref cursors cannot be closed implicitly.

Ref cursor with return type is called strong cursor.

Ref cursor without return type is called weak cursor.

You can declare ref cursor type in package spec as well as body.

You can declare ref cursor types in local subprograms or anonymous blocks.

CREATE OR REPLACE PROCEDURE ref_c_sp(dep_det_c IN OUT SYS_REFCURSOR)

AS

BEGIN

OPEN dep_det_c

FOR

SELECT * FROM dep_details d;

END;

DECLARE

dep_det_c SYS_REFCURSOR;
tab_data dep_details%ROWTYPE;

BEGIN

ref_c_sp(dep_det_c);

LOOP

FETCH dep_det_c INTO tab_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department Name : '|| tab_data.d_name);

END LOOP;

CLOSE dep_det_c;

END;

/*sample output*/

Department Name : Admin

Department Name : HR

Department Name : Sales

Department Name : Marketing

DROP PROCEDURE ref_c_sp;

Posted 21st October 2014 by Unknown


0 Add a comment

OCT

21

Cursor

SQL Private work Area where the query get passed and executed.

Types

******

Implicit(SQL)

Explicit

-->-- advanced cursor types --<--

Parametrized Cursor

Ref Cursor

Implicit

********

ORACLE implicitly opens a cursor to process each SQL statement not associated with an
explicitly declared cursor.

PL/SQL lets you refer to the most recent implicit cursor as the SQL” cursor. So, although you
cannot use the OPEN,

FETCH, and CLOSE statements to control an implicit cursor, you can still use cursor attributes to
access information
about the most recently executed SQL statement.

Cursor Stages

**************

OPEN cursor_name

FETCH (with in loop)

CLOSE cursor_name

Explicit

The set of rows returned by a query can consist of zero, one, or multiple rows,

depending on how many rows meet your search criteria. When a query returns multiple rows,

you can explicitly define a cursor to process the rows. You use three commands to control the
cursor

Cursor Attributes

*****************

%FOUND

%NOTFOUND

%ISOPEN

%ROWCOUNT

%BULK_ROWCOUNT --<-- used to handle error while using bulk collection.

%BULK_EXCEPTIONS --<-- used to handle error while using bulk collection.


Cursor Declaration

DECLARE

CURSOR <cursor_name>

IS

<SELECT statement>

BEGIN

--> some stmt

END;

Cursor Loop

Loop

While Loop

For Loop

Cursor Clauses

Return

For update

Where current of

Bulk collect

-->-- creating table

create table product_details


(

p_id NUMBER,

p_name VARCHAR2(30),

p_order_dt DATE

);

-->-- Inserting data

BEGIN

FOR i IN 1 .. 75 LOOP

INSERT INTO product_details VALUES (i, 'prod_name_' || i, SYSDATE + i);

END LOOP;

commit;

END;

-->-- selecting data

SELECT * FROM product_details;

---------------------------------------------

p_id p_name p_order_dt

---------------------------------------------

1 prod_name_1 10/11/2014 3:48:32 PM


2 prod_name_2 10/12/2014 3:48:32 PM

3 prod_name_3 10/13/2014 3:48:32 PM

4 prod_name_4 10/14/2014 3:48:32 PM

5 prod_name_5 10/15/2014 3:48:32 PM

6 prod_name_6 10/16/2014 3:48:32 PM

7 prod_name_7 10/17/2014 3:48:32 PM

8 prod_name_8 10/18/2014 3:48:32 PM

9 prod_name_9 10/19/2014 3:48:32 PM

10 prod_name_10 10/20/2014 3:48:32 PM

11 prod_name_11 10/21/2014 3:48:32 PM

12 prod_name_12 10/22/2014 3:48:32 PM

13 prod_name_13 10/23/2014 3:48:32 PM

14 prod_name_14 10/24/2014 3:48:32 PM

15 prod_name_15 10/25/2014 3:48:32 PM

16 prod_name_16 10/26/2014 3:48:32 PM

17 prod_name_17 10/27/2014 3:48:32 PM

18 prod_name_18 10/28/2014 3:48:32 PM

19 prod_name_19 10/29/2014 3:48:32 PM

20 prod_name_20 10/30/2014 3:48:32 PM

---------------------------------------------

----------------------------------------------

Implicit Cursor

----------------------------------------------
--will update soon

----------------------------------------------

Explicit Cursor

----------------------------------------------

**********************************************

Processing cursor data by using LOOP

**********************************************

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND; --<-- if next record not found means control will
come out from the loop

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||


' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur
INTO all_data;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

EXIT WHEN prod_detail_cur%FOUND; --<-- if next record found means control will come
out from the loop

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP
FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN

CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )


Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor Already closed

DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details

WHERE ROWNUM <=5;

BEGIN

OPEN prod_detail_cur;

LOOP

FETCH prod_detail_cur

INTO all_data;

EXIT WHEN prod_detail_cur%NOTFOUND;

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

END LOOP;

-->-- CLOSE prod_detail_cur;

IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;

dbms_output.put_line('prod_detail_cur cursor closed');

ELSE

dbms_output.put_line('prod_detail_cur cursor Already closed');

END IF;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

prod_detail_cur cursor closed

**********************************************

Processing cursor data by using WHILE LOOP

**********************************************
DECLARE

all_data product_details%ROWTYPE;

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

OPEN prod_detail_cur;

FETCH prod_detail_cur

INTO all_data;

WHILE prod_detail_cur%FOUND LOOP

dbms_output.put_line('Product id : ' || all_data.p_id ||

' Product Name : ' || all_data.p_name ||

' ( Orderd on : ' || TRIM(all_data.p_order_dt) || ' )');

FETCH prod_detail_cur

INTO all_data;

END LOOP;

CLOSE prod_detail_cur;

END;

/*sample output*/

Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )


Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

************************************************************

Processing cursor data by using FOR LOOP - CURSOR FOR LOOP

************************************************************

DECLARE

--cursor declaration

CURSOR prod_detail_cur IS

SELECT * FROM product_details WHERE ROWNUM <= 5;

BEGIN

FOR i IN prod_detail_cur

LOOP

dbms_output.put_line('Product id : ' || i.p_id ||

' Product Name : ' || i.p_name ||

' ( Orderd on : ' || TRIM(i.p_order_dt) || ' )');

END LOOP;

END;

/*sample output*/
Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-OCT-14 )

Product id : 2 Product Name : prod_name_2 ( Orderd on : 12-OCT-14 )

Product id : 3 Product Name : prod_name_3 ( Orderd on : 13-OCT-14 )

Product id : 4 Product Name : prod_name_4 ( Orderd on : 14-OCT-14 )

Product id : 5 Product Name : prod_name_5 ( Orderd on : 15-OCT-14 )

Parameterized Cursor

*********************

This was used when you are going to use the cursor in more than one place with different
values for the same where clause.

Cursor parameters must be in mode.

Cursor parameters may have default values.

The scope of cursor parameter is within the select statement.

CREATE TABLE dep_details(d_id NUMBER,d_name VARCHAR2(30), location_id NUMBER);

BEGIN

INSRT INTO dep_details VALUES(001,'Admin',1010);

INSRT INTO dep_details VALUES(002,'HR',1010);

INSRT INTO dep_details VALUES(003,'Sales',1020);

INSRT INTO dep_details VALUES(004,'Marketing',1020);


commit;

END;

SELECT * FROM dep_details;

----------------------------

d_id d_name location_id

----------------------------

1 Admin 1010

2 HR 1010

3 Sales 1020

4 Marketing 1020

----------------------------

DECLARE

-->--Declaring parameterized cursor

CURSOR dep_det_c(p_location_id NUMBER) IS

SELECT * FROM dep_details d WHERE d.location_id = p_location_id;

all_data dep_details%ROWTYPE;

BEGIN

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

OPEN dep_det_c(1010);

LOOP
FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

-->-- opening same cursor with different input value

OPEN dep_det_c(1020);

LOOP

FETCH dep_det_c

INTO all_data;

EXIT WHEN dep_det_c%NOTFOUND;

dbms_output.put_line('Department id : ' || all_data.d_id ||

' Department Name : ' || all_data.d_name);

END LOOP;

CLOSE dep_det_c;

dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');

END;

/
/*sample output*/

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 1 Department Name : Admin

Department id : 2 Department Name : HR

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Department id : 3 Department Name : Sales

Department id : 4 Department Name : Marketing

-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-

Posted 21st October 2014 by Unknown

0 Add a comment

OCT

21

Handling Exception

Error Handling in oracle

ERROR

Any departure from the expected behavior of the system or program,

which stops the working of the system is an error.

Types : compile time error


Run time error

EXCEPTION

Any error or problem which one can handle and continue to work normally.

Handling Exception

When exception is raised, control passes to the exception section of the block.

i.e. EXCEPTION

WHEN name_of_exception THEN

Types : Pre Defined Exceptions

User Defined Exceptions

Predefined Exception

*********************

Oracle has predefined several exceptions that correspond to the most common oracle errors.

------------------------------------------------------------------------

Exception Oracle Error SQL Code Value

------------------------------------------------------------------------

ZERO_DIVIDE ORA-01476 -1476

NO_DATA_FOUND ORA-01403 +100


DUP_VAL_ON_INDEX ORA-00001 -1

TOO_MANY_ROWS ORA-01422 -1422

VALUE_ERROR ORA-06502 -6502

CURSOR_ALREADY_OPEN ORA-06511 -6511

OTHERS

------------------------------------------------------------------------

-->-- ZERO_DIVIDE --<--

Your program attempts to divide a number by zero.

DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN ZERO_DIVIDE THEN

dbms_output.put_line('Divisor is equal to zero');

END;

-->-- NO_DATA_FOUND --<--

Single row SELECT returned no rows or your program referenced a deleted element in a nested
table
or an uninitialized element in an associative array (index-by table).

CREATE TABLE test_tb(id NUMBER PRIMARY KEY);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN NO_DATA_FOUND THEN

dbms_output.put_line('There is no data inside the table');

END;

-->-- DUP_VAL_ON_INDEX --<--

A program attempted to insert duplicate values in a column that is constrained by a unique


index.

INSERT INTO test_tb VALUES (1);

INSERT INTO test_tb VALUES (2);

commit;

BEGIN
INSERT INTO test_tb VALUES (2);

EXCEPTION

WHEN DUP_VAL_ON_INDEX THEN

dbms_output.put_line('Duplicate values are not allowed');

END;

-->-- TOO_MANY_ROWS --<--

Single row SELECT returned multiple rows.

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;

EXCEPTION

WHEN TOO_MANY_ROWS THEN

dbms_output.put_line('Query returning more than one row');

END;

DROP TABLE test_tb;

-->-- VALUE_ERROR --<--


An arithmetic, conversion, truncation, or size constraint error occurred.

DECLARE

num1 NUMBER(2);

BEGIN

num1 := 345;

EXCEPTION

WHEN VALUE_ERROR THEN

dbms_output.put_line('check the size of the variable');

END;

-->-- CURSOR_ALREADY_OPEN --<--

A program attempted to open an already opened cursor.

CREATE TABLE emp(id NUMBER, name VARCHAR2(30));

BEGIN

INSERT INTO emp VALUES(1,'Name1');

INSERT INTO emp VALUES(2,'Name2');

INSERT INTO emp VALUES(3,'Name3');

INSERT INTO emp VALUES(4,'Name4');


COMMIT;

END;

SELECT * FROM emp;

DECLARE

cursor emp_c IS

SELECT * FROM emp;

all_data emp%ROWTYPE;

BEGIN

OPEN emp_c;

OPEN emp_c;

NULL;

CLOSE emp_c;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

END;

DROP TABLE emp;

-->-- OTHERS --<--


DECLARE

v_result NUMBER;

BEGIN

SELECT 23 / 0 INTO v_result FROM dual;

EXCEPTION

WHEN CURSOR_ALREADY_OPEN THEN

dbms_output.put_line('Cursor already opened');

WHEN OTHERS THEN

dbms_output.put_line('Some other error ' || SQLERRM);

END;

User Defined Exception

**********************

A user-defined exception is an error that is defined by the programmer.

User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,

exceptions have a type EXCEPTION and scope.

DECLARE

v_gender CHAR := '&gender';

gender_ex EXCEPTION;

BEGIN
IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE gender_ex;

END IF;

dbms_output.put_line('Gender : '||v_gender);

EXCEPTION

WHEN gender_ex THEN

dbms_output.put_line('Please Enter valid gender');

END;

create table test_insert (id NUMBER, Name VARCHAR2(30));

DECLARE

abort_ex EXCEPTION;

BEGIN

FOR i IN 1..100

LOOP

BEGIN

IF mod(i,10)=0 THEN

RAISE abort_ex;

END IF;

INSERT INTO test_insert VALUES(i, 'Name'||i);

EXCEPTION

WHEN abort_ex THEN

NULL;
END;

END LOOP;

COMMIT;

END;

SELECT * FROM test_insert;

DROP TABLE test_insert;

SQLERRM and SQLCODE

********************

SQLCODE returns the current error code, and SQLERRM returns the current error message
text;

For user-defined exception SQLCODE returns 1 and SQLERRM returns “user-defined


exception”.

SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.

CREATE TABLE test_tb (id NUMBER);

DECLARE

v_id NUMBER;

BEGIN

SELECT id INTO v_id FROM test_tb;


dbms_output.put_line(v_id);

EXCEPTION

WHEN OTHERS THEN

dbms_output.put_line('SQLERRM : ' || SQLERRM);

dbms_output.put_line('SQLCODE : ' || SQLCODE);

END;

/*sample output*/

SQLERRM : ORA-01403: no data found

SQLCODE : 100

DROP TABLE test_tb;

PRAGMA EXCEPTION_INIT

*********************

Using this you can associate a named exception with a particular oracle error.

This gives you the ability to trap this error specifically, rather than via an OTHERS handler.

Syntax:

PRAGMA EXCEPTION_INIT(exception_name, oracle_error_number);


DECLARE

v_result NUMBER;

PRAGMA EXCEPTION_INIT(Invalid, -1476);

BEGIN

SELECT 453 / 0 INTO v_result FROM dual;

dbms_output.put_line('Result : ' || v_result);

EXCEPTION

WHEN INVALID THEN

dbms_output.put_line('Invalid Exception');

END;

RAISE_APPLICATION_ERROR

************************

You can use this built-in function to create your own error messages, which can be more
descriptive than named exceptions.

Error Number :

Oracle Error Range : From -00000 to -19999

User Error Range : From -20000 to -20999


DECLARE

v_gender CHAR := '&gender';

BEGIN

IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN

RAISE_APPLICATION_ERROR(-20003, 'Enter valid gender');

END IF;

dbms_output.put_line('Gender : ' || v_gender);

END;

Posted 21st October 2014 by Unknown

1 View comments

Loading

Dynamic Views theme. Powered by Blogger.

Vous aimerez peut-être aussi