Escolar Documentos
Profissional Documentos
Cultura Documentos
search
JUL
20
--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
, AVG(b.salary) avg_sal
FROM employees b
GROUP BY b.department_id
)b
WHERE a.department_id = b.department_id
Display all the customer who have placed more number of orders by using INLINE view
( custm_id NUMBER ,
custm_nm VARCHAR2(30) ,
ttl_amt NUMBER(7,2)
);
BEGIN
COMMIT;
END;
SELECT c.*
FROM customer_order_det_tb c;
--------------------------------------------
--------------------------------------------
--------------------------------------------
--Writing a Quer to display all the customer who have placed maximum number of order
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
--------------------------------
--------------------------------
100 Murugappan 2
102 Ramesh 2
101 Raja 1
--------------------------------
----------
total_odr
----------
----------
Inline view to find all the customers who have placed maximum number of orders
/****************************************
Syntax
WHERE contition;
****************************************/
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
) query1,
) query2
-------------------------------
-------------------------------
100 Murugappan 2
102 Ramesh 2
-------------------------------
--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT
Example :
--in 11g
SELECT *
FROM departments d
--in 12c
SELECT * FROM employees e, LATERAL(
SELECT *
FROM departments d
);
--in 11g
WITH t
AS
( SELECT LEVEL a
FROM dual
SELECT *
FROM t, (SELECT *
FROM employees
);
--in 12c
WITH t
AS
LATERAL(SELECT *
FROM employees
0 Add a comment
JAN
23
--creating table
eid NUMBER(4),
ename VARCHAR2(30),
depno NUMBER(3),
salary NUMBER(8)
);
BEGIN
--Inserting records
COMMIT;
END;
SELECT MAX(salary)
FROM employee_data
FROM employee_data);
SELECT MIN(salary)
FROM employee_data
SELECT MIN(salary)
FROM employee_data
--query to select all the details of the employee whose getting nth maximum salary
SELECT *
rownum rn
FROM (SELECT *
FROM employee_data
WHERE rn = 9;
SELECT *
WHERE rank = 9;
SELECT *
WHERE rank = 4;
SELECT *
WHERE rank = 4;
GROUP BY e.depno;
--query to display all the employees who are all getting salary more than average salary of the
company
--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
--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,
first_name,
salary
FROM employees
7 View comments
JAN
22
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.
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
14 rows selected.
Elapsed: 00:00:14.01
SQL> select e.empno, e.ename ename, coalesce(m.ename,f_null) mname
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.
0 Add a comment
DEC
21
Constraints
Format : sys_cn
Example : SYS_C405323
Types
Primary Key
Ex : Employee_id, Student_id
Unique Key
Foreign Key
c1(pk) : 1 2 3
Not Null
Check
------------------------------------
Duplicate NULL
------------------------------------
Primary Key X X
------------------------------------
S_id Number(2),
s_mail Varchar2(30),
s_gender char(1),
s_did Number(3),
);
DESC my_stu_details;
------------------------------------
------------------------------------
S_ID NUMBER(2)
S_NAME VARCHAR2(30)
S_MAIL VARCHAR2(30) Y
S_GENDER CHAR(1) Y
S_DID NUMBER(3) Y
------------------------------------
--Duplicate Check
--Null Check
--------------------------------------------------------
--------------------------------------------------------
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
------------------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
-------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
ON DELETE CASCADE
SELECT c.owner,
c.constraint_name,
c.constraint_type,
c.table_name,
c.r_constraint_name,
c.status
FROM user_constraints c
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.
Interview Questions
Which Data Dictionary table contains information about constraint with corresponding column
name?
1 View comments
DEC
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:
BEGIN
commit;
END;
listagg(product,
',') within
FROM test_ins
GROUP BY empid;
-->-- Example 2
GROUP BY department_id;
0 Add a comment
NOV
IF
IF ELSE
Multiple IF ELSE
LOOP
FOR LOOP
WHILE LOOP
create table test_udt(id NUMBER, salary NUMBER);
BEGIN
Commit;
END;
IF
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 1;
UPDATE test_udt t
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
ELSE
UPDATE test_udt t
END IF;
commit;
END;
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
commit;
END;
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');
v_salary := 2000;
dbms_output.put_line('2 inside');
v_salary := 3000;
dbms_output.put_line('3 inside');
v_salary := 4000;
dbms_output.put_line('4 inside');
END IF;
UPDATE test_udt t
commit;
END;
--syntax
LOOP
--statements
--increment
--exit statement
END LOOP;
DECLARE
i NUMBER := 1;
x VARCHAR2(3);
BEGIN
LOOP
x := lpad(i,3,'0');
i := i+1;
IF MOD(i,100) = 0 THEN
commit;
dbms_output.put_line('commit executed');
END IF;
END LOOP;
END;
FOR LOOP
BEGIN
FOR I in 1..5
LOOP
END LOOP;
END;
BEGIN
FOR I in REVERSE 14..50
LOOP
END LOOP;
END;
WHILE LOOP
DECLARE
i_val NUMBER:=0;
BEGIN
LOOP
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
0 Add a comment
OCT
21
Bulk Collect
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.
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
INTO dta;
CLOSE proddt_cur;
END LOOP;
END;
/
-->-- Bulk collect in SELECT clause --<--
DECLARE
dta alldata_typ;
BEGIN
END LOOP;
END;
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
FETCH proddt_cur BULK COLLECT
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta1 alldata_typ1;
dta2 alldata_typ2;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
FETCH proddt_cur BULK COLLECT
CLOSE proddt_cur;
END LOOP;
END LOOP;
END;
0 Add a comment
OCT
21
Ref Cursor
This is unconstrained cursor which will return different types depends upon the user input.
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.
AS
BEGIN
OPEN dep_det_c
FOR
END;
DECLARE
dep_det_c SYS_REFCURSOR;
tab_data dep_details%ROWTYPE;
BEGIN
ref_c_sp(dep_det_c);
LOOP
END LOOP;
CLOSE dep_det_c;
END;
/*sample output*/
Department Name : HR
0 Add a comment
OCT
21
Cursor
SQL Private work Area where the query get passed and executed.
Types
******
Implicit(SQL)
Explicit
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
Cursor Stages
**************
OPEN cursor_name
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
Cursor Declaration
DECLARE
CURSOR <cursor_name>
IS
<SELECT statement>
BEGIN
END;
Cursor Loop
Loop
While Loop
For Loop
Cursor Clauses
Return
For update
Where current of
Bulk collect
p_id NUMBER,
p_name VARCHAR2(30),
p_order_dt DATE
);
BEGIN
FOR i IN 1 .. 75 LOOP
END LOOP;
commit;
END;
---------------------------------------------
---------------------------------------------
---------------------------------------------
----------------------------------------------
Implicit Cursor
----------------------------------------------
Explicit Cursor
----------------------------------------------
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
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
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
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*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
dbms_output.put_line('prod_detail_cur cursor Already closed');
END IF;
END;
/*sample output*/
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
FETCH prod_detail_cur
INTO all_data;
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
************************************************************
DECLARE
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
FOR i IN prod_detail_cur
LOOP
END LOOP;
END;
/*sample output*/
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.
BEGIN
commit;
END;
SELECT * FROM dep_details;
----------------------------
----------------------------
1 Admin 1010
2 HR 1010
3 Sales 1020
4 Marketing 1020
----------------------------
DECLARE
all_data dep_details%ROWTYPE;
BEGIN
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1010);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1020);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
END;
/*sample output*/
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
Department id : 1 Department Name : Admin
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
0 Add a comment
OCT
21
Handling Exception
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
Predefined Exception
*********************
Oracle has predefined several exceptions that correspond to the most common oracle errors.
------------------------------------------------------------------------
------------------------------------------------------------------------
DUP_VAL_ON_INDEX ORA-00001 -1
OTHERS
------------------------------------------------------------------------
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
Single row SELECT returned no rows or your program referenced a deleted element in a nested
table
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
commit;
BEGIN
EXCEPTION
END;
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
num1 NUMBER(2);
BEGIN
num1 := 345;
EXCEPTION
END;
BEGIN
COMMIT;
END;
SELECT * FROM emp;
DECLARE
cursor emp_c IS
all_data emp%ROWTYPE;
BEGIN
OPEN emp_c;
OPEN emp_c;
NULL;
CLOSE emp_c;
EXCEPTION
END;
DECLARE
v_result NUMBER;
BEGIN
SELECT 23 / 0 INTO v_result FROM dual;
EXCEPTION
END;
**********************
User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,
DECLARE
gender_ex EXCEPTION;
BEGIN
RAISE gender_ex;
END IF;
dbms_output.put_line('Gender : '||v_gender);
EXCEPTION
END;
DECLARE
abort_ex EXCEPTION;
BEGIN
FOR i IN 1..100
LOOP
BEGIN
IF mod(i,10)=0 THEN
RAISE abort_ex;
END IF;
EXCEPTION
NULL;
END;
END LOOP;
COMMIT;
END;
********************
SQLCODE returns the current error code, and SQLERRM returns the current error message
text;
SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.
DECLARE
v_id NUMBER;
BEGIN
dbms_output.put_line(v_id);
EXCEPTION
END;
/*sample output*/
SQLCODE : 100
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:
DECLARE
v_result NUMBER;
EXCEPTION
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 :
DECLARE
BEGIN
IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN
END IF;
END;
1 View comments
Loading
search
JUL
20
--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
, AVG(b.salary) avg_sal
FROM employees b
GROUP BY b.department_id
)b
Display all the customer who have placed more number of orders by using INLINE view
( custm_id NUMBER ,
custm_nm VARCHAR2(30) ,
order_dt DATE DEFAULT SYSDATE ,
ttl_amt NUMBER(7,2)
);
BEGIN
COMMIT;
END;
SELECT c.*
FROM customer_order_det_tb c;
--------------------------------------------
--------------------------------------------
--------------------------------------------
--Writing a Quer to display all the customer who have placed maximum number of order
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
--------------------------------
--------------------------------
100 Murugappan 2
102 Ramesh 2
101 Raja 1
--------------------------------
----------
total_odr
----------
----------
Inline view to find all the customers who have placed maximum number of orders
/****************************************
Syntax
WHERE contition;
****************************************/
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
) query1,
) query2
-------------------------------
100 Murugappan 2
102 Ramesh 2
-------------------------------
--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT
FROM employees e
Example :
--in 11g
SELECT *
FROM departments d
--in 12c
SELECT *
FROM departments d
);
--in 11g
WITH t
AS
( SELECT LEVEL a
FROM dual
SELECT *
FROM t, (SELECT *
FROM employees
);
--in 12c
WITH t
AS
SELECT * FROM t,
LATERAL(SELECT *
FROM employees
JAN
23
--creating table
eid NUMBER(4),
ename VARCHAR2(30),
depno NUMBER(3),
salary NUMBER(8)
);
BEGIN
--Inserting records
COMMIT;
END;
FROM employee_data
FROM employee_data);
SELECT MIN(salary)
FROM employee_data
SELECT MIN(salary)
FROM employee_data
SELECT *
rownum rn
FROM (SELECT *
FROM employee_data
WHERE rn = 9;
SELECT *
WHERE rank = 9;
SELECT *
SELECT *
WHERE rank = 4;
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
--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
--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,
first_name,
salary
FROM employees
7 View comments
JAN
22
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.
14 rows selected.
Elapsed: 00:00:14.01
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.
0 Add a comment
DEC
21
Constraints
Format : [part_of_project_name-table_name-column_name-constraint_type]
Format : sys_cn
Example : SYS_C405323
Types
Primary Key
Ex : Employee_id, Student_id
Unique Key
Ex : Contact_no, email
Foreign Key
c1(pk) : 1 2 3
Check
------------------------------------
Duplicate NULL
------------------------------------
Primary Key X X
------------------------------------
S_id Number(2),
s_mail Varchar2(30),
s_gender char(1),
s_did Number(3),
);
DESC my_stu_details;
------------------------------------
------------------------------------
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)
--Duplicate Check
Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)
--Null Check
--------------------------------------------------------
--------------------------------------------------------
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
--------------------------------------------------------
------------------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
-------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
ON DELETE CASCADE
SELECT c.owner,
c.constraint_name,
c.constraint_type,
c.table_name,
c.r_constraint_name,
c.status
FROM user_constraints c
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.
Interview Questions
Which Data Dictionary table contains information about constraint with corresponding column
name?
1 View comments
DEC
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 :
--Example 1:
BEGIN
commit;
END;
listagg(product,
',') within
FROM test_ins
GROUP BY empid;
-->-- Example 2
FROM employees
GROUP BY department_id;
0 Add a comment
NOV
IF
IF ELSE
Multiple IF ELSE
LOOP
FOR LOOP
WHILE LOOP
BEGIN
Commit;
END;
IF
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 1;
UPDATE test_udt t
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;
UPDATE test_udt t
ELSE
UPDATE test_udt t
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;
v_salary := v_salary+10005;
ELSE
v_salary := v_salary+20007;
END IF;
UPDATE test_udt t
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');
v_salary := 2000;
dbms_output.put_line('2 inside');
v_salary := 3000;
dbms_output.put_line('3 inside');
dbms_output.put_line('4 inside');
END IF;
UPDATE test_udt t
commit;
END;
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');
i := i+1;
IF MOD(i,100) = 0 THEN
commit;
dbms_output.put_line('commit executed');
END IF;
END LOOP;
END;
BEGIN
FOR I in 1..5
LOOP
END LOOP;
END;
BEGIN
LOOP
END LOOP;
END;
WHILE LOOP
DECLARE
i_val NUMBER:=0;
BEGIN
WHILE (i_val < 11)
LOOP
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
0 Add a comment
OCT
21
Bulk Collect
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.
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
INTO dta;
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta alldata_typ;
BEGIN
END LOOP;
END;
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END;
/
-->-- Multiple fetches in INTO clause --<--
DECLARE
dta1 alldata_typ1;
dta2 alldata_typ2;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END LOOP;
END;
0 Add a comment
OCT
21
Ref Cursor
This is unconstrained cursor which will return different types depends upon the user input.
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.
AS
BEGIN
OPEN dep_det_c
FOR
END;
DECLARE
dep_det_c SYS_REFCURSOR;
tab_data dep_details%ROWTYPE;
BEGIN
ref_c_sp(dep_det_c);
LOOP
END LOOP;
CLOSE dep_det_c;
END;
/*sample output*/
Department Name : Admin
Department Name : HR
0 Add a comment
OCT
21
Cursor
SQL Private work Area where the query get passed and executed.
Types
******
Implicit(SQL)
Explicit
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
Cursor Stages
**************
OPEN cursor_name
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
Cursor Declaration
DECLARE
CURSOR <cursor_name>
IS
<SELECT statement>
BEGIN
END;
Cursor Loop
Loop
While Loop
For Loop
Cursor Clauses
Return
For update
Where current of
Bulk collect
p_id NUMBER,
p_name VARCHAR2(30),
p_order_dt DATE
);
BEGIN
FOR i IN 1 .. 75 LOOP
END LOOP;
commit;
END;
---------------------------------------------
---------------------------------------------
---------------------------------------------
----------------------------------------------
Implicit Cursor
----------------------------------------------
----------------------------------------------
Explicit Cursor
----------------------------------------------
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
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
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
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*/
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
FETCH prod_detail_cur
INTO all_data;
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
************************************************************
************************************************************
DECLARE
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
FOR i IN prod_detail_cur
LOOP
END LOOP;
END;
/*sample output*/
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.
BEGIN
commit;
END;
----------------------------
----------------------------
1 Admin 1010
2 HR 1010
3 Sales 1020
4 Marketing 1020
----------------------------
DECLARE
all_data dep_details%ROWTYPE;
BEGIN
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1010);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1020);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
END;
/*sample output*/
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
0 Add a comment
OCT
21
Handling Exception
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
*********************
Oracle has predefined several exceptions that correspond to the most common oracle errors.
------------------------------------------------------------------------
------------------------------------------------------------------------
DUP_VAL_ON_INDEX ORA-00001 -1
OTHERS
------------------------------------------------------------------------
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
Single row SELECT returned no rows or your program referenced a deleted element in a nested
table
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
-->-- DUP_VAL_ON_INDEX --<--
commit;
BEGIN
EXCEPTION
END;
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
DECLARE
num1 NUMBER(2);
BEGIN
num1 := 345;
EXCEPTION
END;
BEGIN
COMMIT;
END;
DECLARE
cursor emp_c IS
all_data emp%ROWTYPE;
BEGIN
OPEN emp_c;
OPEN emp_c;
NULL;
CLOSE emp_c;
EXCEPTION
END;
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
**********************
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,
DECLARE
gender_ex EXCEPTION;
BEGIN
RAISE gender_ex;
END IF;
dbms_output.put_line('Gender : '||v_gender);
EXCEPTION
END;
DECLARE
abort_ex EXCEPTION;
BEGIN
FOR i IN 1..100
LOOP
BEGIN
IF mod(i,10)=0 THEN
RAISE abort_ex;
END IF;
EXCEPTION
NULL;
END;
END LOOP;
COMMIT;
END;
********************
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.
DECLARE
v_id NUMBER;
BEGIN
dbms_output.put_line(v_id);
EXCEPTION
END;
/*sample output*/
SQLCODE : 100
*********************
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:
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
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 :
DECLARE
BEGIN
END IF;
END;
1 View comments
Loading
search
JUL
20
--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 b
GROUP BY b.department_id
)b
Display all the customer who have placed more number of orders by using INLINE view
( custm_id NUMBER ,
custm_nm VARCHAR2(30) ,
ttl_amt NUMBER(7,2)
);
BEGIN
COMMIT;
END;
SELECT c.*
FROM customer_order_det_tb c;
--------------------------------------------
--------------------------------------------
--------------------------------------------
--Writing a Quer to display all the customer who have placed maximum number of order
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
--------------------------------
custm_id custm_nm total_odr
--------------------------------
100 Murugappan 2
102 Ramesh 2
101 Raja 1
--------------------------------
----------
total_odr
----------
----------
Inline view to find all the customers who have placed maximum number of orders
/****************************************
Syntax
****************************************/
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
) query1,
) query2
-------------------------------
-------------------------------
100 Murugappan 2
102 Ramesh 2
-------------------------------
--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 employees e
Example :
--in 11g
SELECT *
FROM departments d
--in 12c
SELECT *
FROM departments d
);
--in 11g
WITH t
AS
( SELECT LEVEL a
FROM dual
SELECT *
FROM t, (SELECT *
FROM employees
);
WITH t
AS
SELECT * FROM t,
LATERAL(SELECT *
FROM employees
0 Add a comment
JAN
23
--creating table
CREATE TABLE employee_data
eid NUMBER(4),
ename VARCHAR2(30),
depno NUMBER(3),
salary NUMBER(8)
);
BEGIN
--Inserting records
COMMIT;
END;
/
SELECT * FROM employee_data
SELECT MAX(salary)
FROM employee_data
FROM employee_data);
SELECT MIN(salary)
SELECT MIN(salary)
FROM employee_data
--query to select all the details of the employee whose getting nth maximum salary
SELECT *
rownum rn
FROM (SELECT *
FROM employee_data
WHERE rn = 9;
--same query using row_numbr( ) function
SELECT *
WHERE rank = 9;
SELECT *
WHERE rank = 4;
SELECT *
WHERE rank = 4;
--query to display display maximum salary in all the department
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
--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
--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,
first_name,
salary
FROM employees
7 View comments
JAN
22
Why prefer COALESCE over NVL
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.
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.
Elapsed: 00:00:14.01
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.
0 Add a comment
DEC
21
Constraints
Format : [part_of_project_name-table_name-column_name-constraint_type]
Format : sys_cn
Example : SYS_C405323
Types
Primary Key
Ex : Employee_id, Student_id
Unique Key
Ex : Contact_no, email
Foreign Key
c1(pk) : 1 2 3
Not Null
Check
Duplicate NULL
------------------------------------
Primary Key X X
------------------------------------
S_id Number(2),
s_mail Varchar2(30),
s_gender char(1),
s_did Number(3),
DESC my_stu_details;
------------------------------------
------------------------------------
S_ID NUMBER(2)
S_NAME VARCHAR2(30)
S_MAIL VARCHAR2(30) Y
S_GENDER CHAR(1) Y
S_DID NUMBER(3) Y
------------------------------------
--Duplicate Check
--Null Check
--------------------------------------------------------
--------------------------------------------------------
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
--------------------------------------------------------
------------------------------------------------------------
-------------------------------------------------
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
-------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
SELECT c.owner,
c.constraint_name,
c.constraint_type,
c.table_name,
c.r_constraint_name,
c.status
FROM user_constraints c
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.
Interview Questions
Which Data Dictionary table contains information about constraint with corresponding column
name?
1 View comments
DEC
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 :
--Example 1:
BEGIN
commit;
END;
SELECT * FROM test_ins;
listagg(product,
',') within
FROM test_ins
GROUP BY empid;
FROM employees
GROUP BY department_id;
0 Add a comment
NOV
IF
IF ELSE
Multiple IF ELSE
LOOP
FOR LOOP
WHILE LOOP
BEGIN
Commit;
END;
IF
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 1;
UPDATE test_udt t
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;
UPDATE test_udt t
ELSE
UPDATE test_udt t
END IF;
commit;
END;
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 2;
v_salary := v_salary+10005;
ELSE
v_salary := v_salary+20007;
END IF;
UPDATE test_udt t
commit;
END;
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');
v_salary := 2000;
dbms_output.put_line('2 inside');
v_salary := 3000;
dbms_output.put_line('3 inside');
v_salary := 4000;
dbms_output.put_line('4 inside');
END IF;
UPDATE test_udt t
commit;
END;
/
LOOP
--syntax
LOOP
--statements
--increment
--exit statement
END LOOP;
DECLARE
i NUMBER := 1;
x VARCHAR2(3);
BEGIN
LOOP
x := lpad(i,3,'0');
i := i+1;
IF MOD(i,100) = 0 THEN
commit;
dbms_output.put_line('commit executed');
END IF;
END LOOP;
END;
FOR LOOP
BEGIN
FOR I in 1..5
LOOP
END LOOP;
END;
/
FOR LOOP - Reverse
BEGIN
LOOP
END LOOP;
END;
WHILE LOOP
DECLARE
i_val NUMBER:=0;
BEGIN
LOOP
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
0 Add a comment
OCT
21
Bulk Collect
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.
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
INTO dta;
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta alldata_typ;
BEGIN
END LOOP;
END;
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta1 alldata_typ1;
dta2 alldata_typ2;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END LOOP;
END;
OCT
21
Ref Cursor
This is unconstrained cursor which will return different types depends upon the user input.
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.
AS
BEGIN
OPEN dep_det_c
FOR
END;
DECLARE
dep_det_c SYS_REFCURSOR;
tab_data dep_details%ROWTYPE;
BEGIN
ref_c_sp(dep_det_c);
LOOP
END LOOP;
CLOSE dep_det_c;
END;
/*sample output*/
Department Name : HR
OCT
21
Cursor
SQL Private work Area where the query get passed and executed.
Types
******
Implicit(SQL)
Explicit
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
Cursor Stages
**************
OPEN cursor_name
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
Cursor Declaration
DECLARE
CURSOR <cursor_name>
IS
<SELECT statement>
BEGIN
END;
Cursor Loop
Loop
While Loop
For Loop
Cursor Clauses
Return
For update
Where current of
Bulk collect
p_id NUMBER,
p_name VARCHAR2(30),
p_order_dt DATE
);
BEGIN
FOR i IN 1 .. 75 LOOP
END LOOP;
commit;
END;
---------------------------------------------
---------------------------------------------
----------------------------------------------
Implicit Cursor
----------------------------------------------
----------------------------------------------
Explicit Cursor
----------------------------------------------
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
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 ||
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
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*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
FETCH prod_detail_cur
INTO all_data;
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 )
************************************************************
************************************************************
DECLARE
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
FOR i IN prod_detail_cur
LOOP
END LOOP;
END;
/*sample output*/
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.
BEGIN
commit;
END;
----------------------------
----------------------------
1 Admin 1010
2 HR 1010
3 Sales 1020
4 Marketing 1020
----------------------------
DECLARE
all_data dep_details%ROWTYPE;
BEGIN
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1010);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1020);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
END;
/
/*sample output*/
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
0 Add a comment
OCT
21
Handling Exception
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
Predefined Exception
*********************
Oracle has predefined several exceptions that correspond to the most common oracle errors.
------------------------------------------------------------------------
------------------------------------------------------------------------
ZERO_DIVIDE ORA-01476 -1476
DUP_VAL_ON_INDEX ORA-00001 -1
OTHERS
------------------------------------------------------------------------
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
BEGIN
EXCEPTION
END;
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
DECLARE
num1 NUMBER(2);
BEGIN
num1 := 345;
EXCEPTION
END;
BEGIN
COMMIT;
END;
DECLARE
cursor emp_c IS
all_data emp%ROWTYPE;
BEGIN
OPEN emp_c;
OPEN emp_c;
NULL;
CLOSE emp_c;
EXCEPTION
END;
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
**********************
User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,
DECLARE
v_gender CHAR := '&gender';
gender_ex EXCEPTION;
BEGIN
RAISE gender_ex;
END IF;
dbms_output.put_line('Gender : '||v_gender);
EXCEPTION
END;
DECLARE
abort_ex EXCEPTION;
BEGIN
FOR i IN 1..100
LOOP
BEGIN
IF mod(i,10)=0 THEN
RAISE abort_ex;
END IF;
NULL;
END;
END LOOP;
COMMIT;
END;
********************
SQLCODE returns the current error code, and SQLERRM returns the current error message
text;
SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.
DECLARE
v_id NUMBER;
BEGIN
dbms_output.put_line(v_id);
EXCEPTION
END;
/*sample output*/
SQLCODE : 100
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;
BEGIN
EXCEPTION
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 :
DECLARE
BEGIN
END IF;
END;
1 View comments
Loading
search
20
--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
, AVG(b.salary) avg_sal
FROM employees b
GROUP BY b.department_id
)b
( custm_id NUMBER ,
custm_nm VARCHAR2(30) ,
ttl_amt NUMBER(7,2)
);
BEGIN
COMMIT;
END;
SELECT c.*
FROM customer_order_det_tb c;
--------------------------------------------
--------------------------------------------
100 Murugappan 7/11/2015 45000.00
--------------------------------------------
--Writing a Quer to display all the customer who have placed maximum number of order
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
--------------------------------
--------------------------------
100 Murugappan 2
102 Ramesh 2
101 Raja 1
--------------------------------
----------
total_odr
----------
----------
Inline view to find all the customers who have placed maximum number of orders
/****************************************
Syntax
WHERE contition;
****************************************/
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
) query2
-------------------------------
-------------------------------
100 Murugappan 2
102 Ramesh 2
-------------------------------
--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT
FROM employees e
)
WHERE ROWNUM < 4;
Example :
--in 11g
SELECT *
FROM departments d
--in 12c
SELECT *
FROM departments d
--in 11g
WITH t
AS
( SELECT LEVEL a
FROM dual
SELECT *
FROM t, (SELECT *
FROM employees
);
--in 12c
WITH t
AS
SELECT * FROM t,
LATERAL(SELECT *
FROM employees
0 Add a comment
JAN
23
--creating table
eid NUMBER(4),
ename VARCHAR2(30),
depno NUMBER(3),
salary NUMBER(8)
);
BEGIN
--Inserting records
COMMIT;
END;
SELECT MAX(salary)
FROM employee_data
FROM employee_data);
SELECT MIN(salary)
FROM employee_data
SELECT MIN(salary)
FROM (SELECT salary
FROM employee_data
--query to select all the details of the employee whose getting nth maximum salary
SELECT *
rownum rn
FROM (SELECT *
FROM employee_data
WHERE rn = 9;
SELECT *
WHERE rank = 9;
--same query using rank( ) function
SELECT *
WHERE rank = 4;
SELECT *
WHERE rank = 4;
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
--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
--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,
first_name,
salary
FROM employees
7 View comments
JAN
22
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.
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.
14 rows selected.
Elapsed: 00:00:14.01
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.
DEC
21
Constraints
Format : [part_of_project_name-table_name-column_name-constraint_type]
Example : SYS_C405323
Types
Primary Key
Ex : Employee_id, Student_id
Unique Key
Ex : Contact_no, email
Foreign Key
Not Null
Check
------------------------------------
Duplicate NULL
------------------------------------
Primary Key X X
------------------------------------
creating table with all constraint type
S_id Number(2),
s_mail Varchar2(30),
s_gender char(1),
s_did Number(3),
);
DESC my_stu_details;
------------------------------------
------------------------------------
S_ID NUMBER(2)
S_NAME VARCHAR2(30)
S_MAIL VARCHAR2(30) Y
S_GENDER CHAR(1) Y
S_DID NUMBER(3) Y
------------------------------------
--Duplicate Check
--Null Check
--------------------------------------------------------
--------------------------------------------------------
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
--------------------------------------------------------
------------------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
-------------------------------------------------
-------------------------------------------------
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
ON DELETE CASCADE
SELECT c.owner,
c.constraint_name,
c.constraint_type,
c.table_name,
c.r_constraint_name,
c.status
FROM user_constraints c
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
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
Interview Questions
Which Data Dictionary table contains information about constraint with corresponding column
name?
1 View comments
good
Reply
DEC
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:
BEGIN
commit;
END;
listagg(product,
',') within
FROM test_ins
GROUP BY empid;
-->-- Example 2
GROUP BY department_id;
0 Add a comment
NOV
IF
IF ELSE
Multiple IF ELSE
LOOP
FOR LOOP
WHILE LOOP
create table test_udt(id NUMBER, salary NUMBER);
BEGIN
Commit;
END;
IF
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 1;
UPDATE test_udt t
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
ELSE
UPDATE test_udt t
END IF;
commit;
END;
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
commit;
END;
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');
v_salary := 2000;
dbms_output.put_line('2 inside');
v_salary := 3000;
dbms_output.put_line('3 inside');
v_salary := 4000;
dbms_output.put_line('4 inside');
END IF;
UPDATE test_udt t
commit;
END;
--syntax
LOOP
--statements
--increment
--exit statement
END LOOP;
DECLARE
i NUMBER := 1;
x VARCHAR2(3);
BEGIN
LOOP
x := lpad(i,3,'0');
i := i+1;
IF MOD(i,100) = 0 THEN
commit;
dbms_output.put_line('commit executed');
END IF;
END LOOP;
END;
FOR LOOP
BEGIN
FOR I in 1..5
LOOP
END LOOP;
END;
BEGIN
FOR I in REVERSE 14..50
LOOP
END LOOP;
END;
WHILE LOOP
DECLARE
i_val NUMBER:=0;
BEGIN
LOOP
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
0 Add a comment
OCT
21
Bulk Collect
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.
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
INTO dta;
CLOSE proddt_cur;
END LOOP;
END;
/
-->-- Bulk collect in SELECT clause --<--
DECLARE
dta alldata_typ;
BEGIN
END LOOP;
END;
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
FETCH proddt_cur BULK COLLECT
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta1 alldata_typ1;
dta2 alldata_typ2;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
FETCH proddt_cur BULK COLLECT
CLOSE proddt_cur;
END LOOP;
END LOOP;
END;
0 Add a comment
OCT
21
Ref Cursor
This is unconstrained cursor which will return different types depends upon the user input.
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.
AS
BEGIN
OPEN dep_det_c
FOR
END;
DECLARE
dep_det_c SYS_REFCURSOR;
tab_data dep_details%ROWTYPE;
BEGIN
ref_c_sp(dep_det_c);
LOOP
END LOOP;
CLOSE dep_det_c;
END;
/*sample output*/
Department Name : HR
0 Add a comment
OCT
21
Cursor
SQL Private work Area where the query get passed and executed.
Types
******
Implicit(SQL)
Explicit
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
Cursor Stages
**************
OPEN cursor_name
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
Cursor Declaration
DECLARE
CURSOR <cursor_name>
IS
<SELECT statement>
BEGIN
END;
Cursor Loop
Loop
While Loop
For Loop
Cursor Clauses
Return
For update
Where current of
Bulk collect
p_id NUMBER,
p_name VARCHAR2(30),
p_order_dt DATE
);
BEGIN
FOR i IN 1 .. 75 LOOP
END LOOP;
commit;
END;
---------------------------------------------
---------------------------------------------
---------------------------------------------
----------------------------------------------
Implicit Cursor
----------------------------------------------
Explicit Cursor
----------------------------------------------
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
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
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
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*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
dbms_output.put_line('prod_detail_cur cursor Already closed');
END IF;
END;
/*sample output*/
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
FETCH prod_detail_cur
INTO all_data;
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
************************************************************
DECLARE
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
FOR i IN prod_detail_cur
LOOP
END LOOP;
END;
/*sample output*/
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.
BEGIN
commit;
END;
SELECT * FROM dep_details;
----------------------------
----------------------------
1 Admin 1010
2 HR 1010
3 Sales 1020
4 Marketing 1020
----------------------------
DECLARE
all_data dep_details%ROWTYPE;
BEGIN
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1010);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1020);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
END;
/*sample output*/
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
Department id : 1 Department Name : Admin
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
0 Add a comment
OCT
21
Handling Exception
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
Predefined Exception
*********************
Oracle has predefined several exceptions that correspond to the most common oracle errors.
------------------------------------------------------------------------
------------------------------------------------------------------------
DUP_VAL_ON_INDEX ORA-00001 -1
OTHERS
------------------------------------------------------------------------
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
Single row SELECT returned no rows or your program referenced a deleted element in a nested
table
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
commit;
BEGIN
EXCEPTION
END;
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
num1 NUMBER(2);
BEGIN
num1 := 345;
EXCEPTION
END;
BEGIN
COMMIT;
END;
SELECT * FROM emp;
DECLARE
cursor emp_c IS
all_data emp%ROWTYPE;
BEGIN
OPEN emp_c;
OPEN emp_c;
NULL;
CLOSE emp_c;
EXCEPTION
END;
DECLARE
v_result NUMBER;
BEGIN
SELECT 23 / 0 INTO v_result FROM dual;
EXCEPTION
END;
**********************
User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,
DECLARE
gender_ex EXCEPTION;
BEGIN
RAISE gender_ex;
END IF;
dbms_output.put_line('Gender : '||v_gender);
EXCEPTION
END;
DECLARE
abort_ex EXCEPTION;
BEGIN
FOR i IN 1..100
LOOP
BEGIN
IF mod(i,10)=0 THEN
RAISE abort_ex;
END IF;
EXCEPTION
NULL;
END;
END LOOP;
COMMIT;
END;
********************
SQLCODE returns the current error code, and SQLERRM returns the current error message
text;
SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.
DECLARE
v_id NUMBER;
BEGIN
dbms_output.put_line(v_id);
EXCEPTION
END;
/*sample output*/
SQLCODE : 100
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:
DECLARE
v_result NUMBER;
EXCEPTION
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 :
DECLARE
BEGIN
IF v_gender NOT IN ('M', 'F', 'm', 'f') THEN
END IF;
END;
1 View comments
Loading
search
JUL
20
--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
, AVG(b.salary) avg_sal
FROM employees b
GROUP BY b.department_id
)b
Display all the customer who have placed more number of orders by using INLINE view
( custm_id NUMBER ,
custm_nm VARCHAR2(30) ,
order_dt DATE DEFAULT SYSDATE ,
ttl_amt NUMBER(7,2)
);
BEGIN
COMMIT;
END;
SELECT c.*
FROM customer_order_det_tb c;
--------------------------------------------
--------------------------------------------
--------------------------------------------
--Writing a Quer to display all the customer who have placed maximum number of order
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
--------------------------------
--------------------------------
100 Murugappan 2
102 Ramesh 2
101 Raja 1
--------------------------------
----------
total_odr
----------
----------
Inline view to find all the customers who have placed maximum number of orders
/****************************************
Syntax
WHERE contition;
****************************************/
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
) query1,
) query2
-------------------------------
100 Murugappan 2
102 Ramesh 2
-------------------------------
--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT
FROM employees e
Example :
--in 11g
SELECT *
FROM departments d
--in 12c
SELECT *
FROM departments d
);
--in 11g
WITH t
AS
( SELECT LEVEL a
FROM dual
SELECT *
FROM t, (SELECT *
FROM employees
);
--in 12c
WITH t
AS
SELECT * FROM t,
LATERAL(SELECT *
FROM employees
JAN
23
--creating table
eid NUMBER(4),
ename VARCHAR2(30),
depno NUMBER(3),
salary NUMBER(8)
);
BEGIN
--Inserting records
COMMIT;
END;
FROM employee_data
FROM employee_data);
SELECT MIN(salary)
FROM employee_data
SELECT MIN(salary)
FROM employee_data
SELECT *
rownum rn
FROM (SELECT *
FROM employee_data
WHERE rn = 9;
SELECT *
WHERE rank = 9;
SELECT *
SELECT *
WHERE rank = 4;
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
--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
--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,
first_name,
salary
FROM employees
7 View comments
JAN
22
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.
14 rows selected.
Elapsed: 00:00:14.01
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.
0 Add a comment
DEC
21
Constraints
Format : [part_of_project_name-table_name-column_name-constraint_type]
Format : sys_cn
Example : SYS_C405323
Primary Key
Ex : Employee_id, Student_id
Unique Key
Ex : Contact_no, email
Foreign Key
c1(pk) : 1 2 3
Not Null
Check
------------------------------------
Duplicate NULL
------------------------------------
Primary Key X X
------------------------------------
S_id Number(2),
s_mail Varchar2(30),
s_gender char(1),
s_did Number(3),
);
DESC my_stu_details;
------------------------------------
------------------------------------
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)
--Duplicate Check
Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)
--Null Check
--------------------------------------------------------
--------------------------------------------------------
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
--------------------------------------------------------
------------------------------------------------------------
60 IT 103 1400 <---- Delete
-------------------------------------------------
-------------------------------------------------
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
-------------------------------------------------
-------------------------------------------------
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
ON DELETE CASCADE
SELECT c.owner,
c.constraint_name,
c.constraint_type,
c.table_name,
c.r_constraint_name,
c.status
FROM user_constraints c
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
-------------------------------------------------------------
owner constraint_name table_name column_name position
-------------------------------------------------------------
-------------------------------------------------------------
In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.
Interview Questions
Which Data Dictionary table contains information about constraint with corresponding column
name?
1 View comments
good
Reply
DEC
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 :
--Example 1:
CREATE TABLE test_ins(empid NUMBER,product VARCHAR2(30));
BEGIN
commit;
END;
listagg(product,
',') within
FROM test_ins
GROUP BY empid;
-->-- Result set --<--
-->-- Example 2
FROM employees
GROUP BY department_id;
0 Add a comment
NOV
IF
IF ELSE
Multiple IF ELSE
LOOP
FOR LOOP
WHILE LOOP
Commit;
END;
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
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;
UPDATE test_udt t
UPDATE test_udt t
END IF;
commit;
END;
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 2;
v_salary := v_salary+10005;
ELSE
v_salary := v_salary+20007;
END IF;
UPDATE test_udt t
commit;
END;
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');
v_salary := 2000;
dbms_output.put_line('2 inside');
v_salary := 3000;
dbms_output.put_line('3 inside');
v_salary := 4000;
dbms_output.put_line('4 inside');
END IF;
UPDATE test_udt t
commit;
END;
LOOP
--syntax
LOOP
--statements
--increment
--exit statement
END LOOP;
DECLARE
i NUMBER := 1;
x VARCHAR2(3);
BEGIN
LOOP
x := lpad(i,3,'0');
i := i+1;
IF MOD(i,100) = 0 THEN
commit;
dbms_output.put_line('commit executed');
END IF;
END LOOP;
END;
FOR LOOP
BEGIN
FOR I in 1..5
LOOP
END LOOP;
END;
BEGIN
LOOP
END LOOP;
END;
WHILE LOOP
DECLARE
i_val NUMBER:=0;
BEGIN
LOOP
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
0 Add a comment
OCT
21
Bulk Collect
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;
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
INTO dta;
CLOSE proddt_cur;
END LOOP;
END;
dta alldata_typ;
BEGIN
END LOOP;
END;
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
FOR i IN dta.FIRST .. dta.COUNT LOOP
END LOOP;
END;
DECLARE
dta1 alldata_typ1;
dta2 alldata_typ2;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
FOR i IN dta1.FIRST .. dta1.COUNT LOOP
END LOOP;
END LOOP;
END;
0 Add a comment
OCT
21
Ref Cursor
This is unconstrained cursor which will return different types depends upon the user input.
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.
AS
BEGIN
OPEN dep_det_c
FOR
END;
DECLARE
dep_det_c SYS_REFCURSOR;
tab_data dep_details%ROWTYPE;
BEGIN
ref_c_sp(dep_det_c);
LOOP
END LOOP;
CLOSE dep_det_c;
END;
/*sample output*/
Department Name : HR
0 Add a comment
OCT
21
Cursor
SQL Private work Area where the query get passed and executed.
Types
******
Implicit(SQL)
Explicit
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
Cursor Stages
**************
OPEN 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
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
p_id NUMBER,
p_name VARCHAR2(30),
p_order_dt DATE
);
-->-- Inserting data
BEGIN
FOR i IN 1 .. 75 LOOP
END LOOP;
commit;
END;
---------------------------------------------
---------------------------------------------
---------------------------------------------
----------------------------------------------
Implicit Cursor
----------------------------------------------
----------------------------------------------
Explicit Cursor
----------------------------------------------
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
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
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
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
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*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
FETCH prod_detail_cur
INTO all_data;
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
************************************************************
DECLARE
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
FOR i IN prod_detail_cur
LOOP
END LOOP;
END;
/*sample output*/
*********************
This was used when you are going to use the cursor in more than one place with different
values for the same where clause.
BEGIN
commit;
END;
----------------------------
1 Admin 1010
2 HR 1010
3 Sales 1020
4 Marketing 1020
----------------------------
DECLARE
all_data dep_details%ROWTYPE;
BEGIN
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1010);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1020);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
END;
/*sample output*/
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
0 Add a comment
OCT
21
Handling Exception
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
Predefined Exception
*********************
Oracle has predefined several exceptions that correspond to the most common oracle errors.
------------------------------------------------------------------------
------------------------------------------------------------------------
DUP_VAL_ON_INDEX ORA-00001 -1
OTHERS
------------------------------------------------------------------------
-->-- ZERO_DIVIDE --<--
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
Single row SELECT returned no rows or your program referenced a deleted element in a nested
table
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
commit;
BEGIN
EXCEPTION
END;
-->-- TOO_MANY_ROWS --<--
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
DECLARE
num1 NUMBER(2);
BEGIN
num1 := 345;
EXCEPTION
END;
BEGIN
COMMIT;
END;
DECLARE
cursor emp_c IS
all_data emp%ROWTYPE;
BEGIN
OPEN emp_c;
OPEN emp_c;
NULL;
CLOSE emp_c;
EXCEPTION
END;
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
**********************
User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,
DECLARE
gender_ex EXCEPTION;
BEGIN
RAISE gender_ex;
END IF;
dbms_output.put_line('Gender : '||v_gender);
EXCEPTION
DECLARE
abort_ex EXCEPTION;
BEGIN
FOR i IN 1..100
LOOP
BEGIN
IF mod(i,10)=0 THEN
RAISE abort_ex;
END IF;
EXCEPTION
NULL;
END;
END LOOP;
COMMIT;
END;
********************
SQLCODE returns the current error code, and SQLERRM returns the current error message
text;
SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.
DECLARE
v_id NUMBER;
BEGIN
dbms_output.put_line(v_id);
EXCEPTION
END;
/*sample output*/
SQLCODE : 100
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:
DECLARE
v_result NUMBER;
BEGIN
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 :
DECLARE
BEGIN
END IF;
1 View comments
Loading
search
JUL
20
SELECT First_name
, last_name
, salary
, department_id
, AVG(b.salary) avg_sal
FROM employees b
GROUP BY b.department_id
)b
Display all the customer who have placed more number of orders by using INLINE view
( custm_id NUMBER ,
custm_nm VARCHAR2(30) ,
ttl_amt NUMBER(7,2)
);
BEGIN
INSERT INTO customer_order_det_tb VALUES(100, 'Murugappan', '11-Jul-15' , 45000.00);
COMMIT;
END;
SELECT c.*
FROM customer_order_det_tb c;
--------------------------------------------
--------------------------------------------
--------------------------------------------
--Writing a Quer to display all the customer who have placed maximum number of order
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
--------------------------------
--------------------------------
100 Murugappan 2
102 Ramesh 2
101 Raja 1
--------------------------------
----------
total_odr
----------
----------
Inline view to find all the customers who have placed maximum number of orders
/****************************************
Syntax
WHERE contition;
****************************************/
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
) query1,
) query2
-------------------------------
-------------------------------
100 Murugappan 2
102 Ramesh 2
-------------------------------
--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT
FROM employees e
Example :
--in 11g
SELECT *
FROM departments d
--in 12c
SELECT *
FROM departments d
);
--in 11g
WITH t
AS
( SELECT LEVEL a
FROM dual
SELECT *
FROM t, (SELECT *
FROM employees
);
--in 12c
WITH t
AS
SELECT * FROM t,
LATERAL(SELECT *
FROM employees
0 Add a comment
JAN
23
eid NUMBER(4),
ename VARCHAR2(30),
depno NUMBER(3),
salary NUMBER(8)
);
BEGIN
--Inserting records
COMMIT;
END;
SELECT MAX(salary)
FROM employee_data
SELECT MIN(salary)
FROM employee_data
SELECT MIN(salary)
FROM employee_data
--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
WHERE rn = 9;
SELECT *
WHERE rank = 9;
SELECT *
WHERE rank = 4;
WHERE rank = 4;
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
--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
--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,
first_name,
salary
FROM employees
7 View comments
JAN
22
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.
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.
14 rows selected.
Elapsed: 00:00:14.01
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.
0 Add a comment
DEC
21
Constraints
Format : [part_of_project_name-table_name-column_name-constraint_type]
Format : sys_cn
Example : SYS_C405323
Types
Primary Key
Ex : Employee_id, Student_id
Unique Key
Ex : Contact_no, email
Foreign Key
c1(pk) : 1 2 3
Not Null
It will not allowed you to enter null value
Check
------------------------------------
Duplicate NULL
------------------------------------
Primary Key X X
------------------------------------
S_id Number(2),
s_gender char(1),
s_did Number(3),
);
DESC my_stu_details;
------------------------------------
------------------------------------
S_ID NUMBER(2)
S_NAME VARCHAR2(30)
S_MAIL VARCHAR2(30) Y
S_GENDER CHAR(1) Y
S_DID NUMBER(3) Y
------------------------------------
--Duplicate Check
--Null Check
--------------------------------------------------------
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
--------------------------------------------------------
------------------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
-------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
ON DELETE CASCADE
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';
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.
Which Data Dictionary table contains information about constraint with corresponding column
name?
good
Reply
DEC
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 :
--Example 1:
BEGIN
commit;
END;
listagg(product,
',') within
FROM test_ins
GROUP BY empid;
-->-- Example 2
FROM employees
GROUP BY department_id;
0 Add a comment
NOV
IF
IF ELSE
Multiple IF ELSE
LOOP
FOR LOOP
WHILE LOOP
BEGIN
Commit;
END;
IF
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 1;
UPDATE test_udt t
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;
UPDATE test_udt t
ELSE
UPDATE test_udt t
commit;
END;
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 2;
v_salary := v_salary+10005;
ELSE
v_salary := v_salary+20007;
END IF;
UPDATE test_udt t
commit;
END;
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');
v_salary := 2000;
dbms_output.put_line('2 inside');
ELSIF v_id = 3 THEN
v_salary := 3000;
dbms_output.put_line('3 inside');
v_salary := 4000;
dbms_output.put_line('4 inside');
END IF;
UPDATE test_udt t
commit;
END;
LOOP
--syntax
LOOP
--statements
--increment
--exit statement
END LOOP;
DECLARE
i NUMBER := 1;
x VARCHAR2(3);
BEGIN
LOOP
x := lpad(i,3,'0');
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;
FOR LOOP
BEGIN
FOR I in 1..5
LOOP
END LOOP;
END;
BEGIN
LOOP
END LOOP;
END;
WHILE LOOP
DECLARE
i_val NUMBER:=0;
BEGIN
LOOP
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
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.
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
INTO dta;
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta alldata_typ;
BEGIN
END LOOP;
END;
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta1 alldata_typ1;
dta2 alldata_typ2;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
FOR i IN dta2.FIRST .. dta2.COUNT LOOP
END LOOP;
END;
0 Add a comment
OCT
21
Ref Cursor
This is unconstrained cursor which will return different types depends upon the user input.
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.
AS
BEGIN
OPEN dep_det_c
FOR
END;
DECLARE
dep_det_c SYS_REFCURSOR;
tab_data dep_details%ROWTYPE;
BEGIN
ref_c_sp(dep_det_c);
LOOP
END LOOP;
CLOSE dep_det_c;
END;
/*sample output*/
Department Name : HR
0 Add a comment
OCT
21
Cursor
SQL Private work Area where the query get passed and executed.
Types
******
Implicit(SQL)
Explicit
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
Cursor Stages
**************
OPEN cursor_name
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
Cursor Declaration
DECLARE
CURSOR <cursor_name>
IS
<SELECT statement>
BEGIN
END;
/
Cursor Loop
Loop
While Loop
For Loop
Cursor Clauses
Return
For update
Where current of
Bulk collect
p_id NUMBER,
p_name VARCHAR2(30),
p_order_dt DATE
);
BEGIN
FOR i IN 1 .. 75 LOOP
END LOOP;
commit;
END;
---------------------------------------------
---------------------------------------------
---------------------------------------------
----------------------------------------------
Implicit Cursor
----------------------------------------------
----------------------------------------------
Explicit Cursor
----------------------------------------------
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
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
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
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*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
SELECT * FROM product_details
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
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
BEGIN
OPEN prod_detail_cur;
FETCH prod_detail_cur
INTO all_data;
WHILE prod_detail_cur%FOUND LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
************************************************************
************************************************************
DECLARE
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
FOR i IN prod_detail_cur
LOOP
END LOOP;
END;
/*sample output*/
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.
BEGIN
commit;
END;
----------------------------
----------------------------
1 Admin 1010
2 HR 1010
3 Sales 1020
4 Marketing 1020
----------------------------
DECLARE
all_data dep_details%ROWTYPE;
BEGIN
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1010);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
END;
/*sample output*/
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
OCT
21
Handling Exception
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
Predefined Exception
*********************
Oracle has predefined several exceptions that correspond to the most common oracle errors.
------------------------------------------------------------------------
------------------------------------------------------------------------
DUP_VAL_ON_INDEX ORA-00001 -1
OTHERS
------------------------------------------------------------------------
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
Single row SELECT returned no rows or your program referenced a deleted element in a nested
table
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
WHEN NO_DATA_FOUND THEN
END;
commit;
BEGIN
EXCEPTION
END;
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
DECLARE
num1 NUMBER(2);
BEGIN
num1 := 345;
EXCEPTION
BEGIN
COMMIT;
END;
DECLARE
cursor emp_c IS
all_data emp%ROWTYPE;
BEGIN
OPEN emp_c;
OPEN emp_c;
NULL;
CLOSE emp_c;
EXCEPTION
END;
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
User Defined Exception
**********************
User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,
DECLARE
gender_ex EXCEPTION;
BEGIN
RAISE gender_ex;
END IF;
dbms_output.put_line('Gender : '||v_gender);
EXCEPTION
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;
EXCEPTION
NULL;
END;
END LOOP;
COMMIT;
END;
********************
SQLCODE returns the current error code, and SQLERRM returns the current error message
text;
SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.
DECLARE
v_id NUMBER;
BEGIN
dbms_output.put_line(v_id);
EXCEPTION
END;
/*sample output*/
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:
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
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 :
DECLARE
BEGIN
END IF;
END;
Posted 21st October 2014 by Unknown
1 View comments
Loading
search
JUL
20
--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
, AVG(b.salary) avg_sal
FROM employees b
GROUP BY b.department_id
)b
Display all the customer who have placed more number of orders by using INLINE view
( custm_id NUMBER ,
custm_nm VARCHAR2(30) ,
ttl_amt NUMBER(7,2)
);
BEGIN
COMMIT;
END;
SELECT c.*
FROM customer_order_det_tb c;
--------------------------------------------
--------------------------------------------
--------------------------------------------
--Writing a Quer to display all the customer who have placed maximum number of order
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
--------------------------------
--------------------------------
100 Murugappan 2
102 Ramesh 2
101 Raja 1
--------------------------------
----------
total_odr
----------
----------
Inline view to find all the customers who have placed maximum number of orders
/****************************************
Syntax
WHERE contition;
****************************************/
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
) query1,
) query2
-------------------------------
-------------------------------
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
FROM employees e
Example :
--in 11g
FROM departments d
--in 12c
SELECT *
FROM departments d
);
--in 11g
WITH t
AS
( SELECT LEVEL a
FROM dual
SELECT *
FROM t, (SELECT *
FROM employees
--in 12c
WITH t
AS
SELECT * FROM t,
LATERAL(SELECT *
FROM employees
0 Add a comment
JAN
23
eid NUMBER(4),
ename VARCHAR2(30),
depno NUMBER(3),
salary NUMBER(8)
);
BEGIN
--Inserting records
COMMIT;
END;
SELECT MAX(salary)
FROM employee_data
FROM employee_data);
FROM employee_data
SELECT MIN(salary)
FROM employee_data
--query to select all the details of the employee whose getting nth maximum salary
SELECT *
rownum rn
FROM (SELECT *
FROM employee_data
WHERE rn = 9;
SELECT *
WHERE rank = 9;
SELECT *
WHERE rank = 4;
SELECT *
WHERE rank = 4;
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
--query to display all the employees who are all getting salary more than their department
average salary
SELECT employee_id,
first_name,
salary
--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,
first_name,
salary
FROM employees
JAN
22
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.
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.
14 rows selected.
Elapsed: 00:00:14.01
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.
0 Add a comment
DEC
21
Constraints
Format : [part_of_project_name-table_name-column_name-constraint_type]
Format : sys_cn
Example : SYS_C405323
Types
Primary Key
Not allowed Null value
Ex : Employee_id, Student_id
Unique Key
Ex : Contact_no, email
Foreign Key
c1(pk) : 1 2 3
Not Null
Check
You can check your own condition
------------------------------------
Duplicate NULL
------------------------------------
Primary Key X X
------------------------------------
S_id Number(2),
s_mail Varchar2(30),
s_gender char(1),
s_did Number(3),
Constraint my_stu_sid_pk PRIMARY KEY (s_id),
);
DESC my_stu_details;
------------------------------------
------------------------------------
S_ID NUMBER(2)
S_NAME VARCHAR2(30)
S_MAIL VARCHAR2(30) Y
S_GENDER CHAR(1) Y
S_DID NUMBER(3) Y
------------------------------------
--Duplicate Check
--------------------------------------------------------
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
--------------------------------------------------------
------------------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
-------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
ON DELETE CASCADE
SELECT c.owner,
c.constraint_name,
c.constraint_type,
c.table_name,
c.r_constraint_name,
c.status
FROM user_constraints c
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.
Interview Questions
What are all the type of constraint available in oracle?
Which Data Dictionary table contains information about constraint with corresponding column
name?
1 View comments
UnknownMay 22, 2017 at 12:39 AM
good
Reply
DEC
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 :
--Example 1:
BEGIN
commit;
END;
listagg(product,
',') within
FROM test_ins
GROUP BY empid;
-->-- Example 2
FROM employees
GROUP BY department_id;
0 Add a comment
NOV
IF
IF ELSE
Multiple IF ELSE
LOOP
FOR LOOP
WHILE LOOP
BEGIN
END;
IF
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 1;
UPDATE test_udt t
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;
UPDATE test_udt t
ELSE
UPDATE test_udt t
END IF;
commit;
END;
/
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 2;
v_salary := v_salary+10005;
ELSE
v_salary := v_salary+20007;
END IF;
UPDATE test_udt t
commit;
END;
/
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');
v_salary := 2000;
dbms_output.put_line('2 inside');
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
commit;
END;
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');
i := i+1;
IF MOD(i,100) = 0 THEN
commit;
dbms_output.put_line('commit executed');
END IF;
END LOOP;
END;
BEGIN
FOR I in 1..5
LOOP
END LOOP;
END;
BEGIN
LOOP
END LOOP;
END;
WHILE LOOP
DECLARE
i_val NUMBER:=0;
BEGIN
LOOP
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
OCT
21
Bulk Collect
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.
DECLARE
TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
INTO dta;
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta alldata_typ;
BEGIN
END LOOP;
END;
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END;
/
-->-- Multiple fetches in INTO clause --<--
DECLARE
dta1 alldata_typ1;
dta2 alldata_typ2;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END;
0 Add a comment
OCT
21
Ref Cursor
This is unconstrained cursor which will return different types depends upon the user input.
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
END;
DECLARE
dep_det_c SYS_REFCURSOR;
tab_data dep_details%ROWTYPE;
BEGIN
ref_c_sp(dep_det_c);
LOOP
END LOOP;
CLOSE dep_det_c;
END;
/*sample output*/
Department Name : HR
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
Cursor Stages
**************
OPEN cursor_name
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
Cursor Declaration
DECLARE
CURSOR <cursor_name>
IS
<SELECT statement>
BEGIN
END;
Cursor Loop
Loop
While Loop
For Loop
Cursor Clauses
Return
For update
Where current of
Bulk collect
p_id NUMBER,
p_name VARCHAR2(30),
p_order_dt DATE
);
BEGIN
FOR i IN 1 .. 75 LOOP
END LOOP;
commit;
END;
---------------------------------------------
---------------------------------------------
---------------------------------------------
----------------------------------------------
Implicit Cursor
----------------------------------------------
----------------------------------------------
Explicit Cursor
----------------------------------------------
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
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
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
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*/
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
dbms_output.put_line('prod_detail_cur cursor Already closed');
END IF;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
FETCH prod_detail_cur
INTO all_data;
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
************************************************************
************************************************************
DECLARE
--cursor declaration
CURSOR prod_detail_cur IS
FOR i IN prod_detail_cur
LOOP
END LOOP;
END;
/*sample output*/
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.
BEGIN
commit;
END;
----------------------------
----------------------------
1 Admin 1010
2 HR 1010
3 Sales 1020
4 Marketing 1020
----------------------------
DECLARE
all_data dep_details%ROWTYPE;
BEGIN
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1010);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1020);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
END;
/*sample output*/
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
0 Add a comment
OCT
21
Handling Exception
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
*********************
Oracle has predefined several exceptions that correspond to the most common oracle errors.
------------------------------------------------------------------------
------------------------------------------------------------------------
DUP_VAL_ON_INDEX ORA-00001 -1
OTHERS
------------------------------------------------------------------------
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
Single row SELECT returned no rows or your program referenced a deleted element in a nested
table
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
-->-- DUP_VAL_ON_INDEX --<--
commit;
BEGIN
EXCEPTION
END;
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
DECLARE
num1 NUMBER(2);
BEGIN
num1 := 345;
EXCEPTION
END;
-->-- CURSOR_ALREADY_OPEN --<--
BEGIN
COMMIT;
END;
DECLARE
cursor emp_c IS
all_data emp%ROWTYPE;
BEGIN
OPEN emp_c;
OPEN emp_c;
NULL;
CLOSE emp_c;
EXCEPTION
END;
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,
DECLARE
gender_ex EXCEPTION;
BEGIN
RAISE gender_ex;
END IF;
dbms_output.put_line('Gender : '||v_gender);
EXCEPTION
END;
DECLARE
abort_ex EXCEPTION;
BEGIN
FOR i IN 1..100
LOOP
BEGIN
IF mod(i,10)=0 THEN
RAISE abort_ex;
END IF;
EXCEPTION
NULL;
END;
END LOOP;
COMMIT;
END;
********************
SQLCODE returns the current error code, and SQLERRM returns the current error message
text;
SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.
DECLARE
v_id NUMBER;
BEGIN
dbms_output.put_line(v_id);
EXCEPTION
END;
/*sample output*/
SQLCODE : 100
*********************
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:
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
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 :
DECLARE
BEGIN
END IF;
END;
1 View comments
Loading
search
JUL
20
--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
Display all the customer who have placed more number of orders by using INLINE view
( custm_id NUMBER ,
custm_nm VARCHAR2(30) ,
ttl_amt NUMBER(7,2)
);
BEGIN
COMMIT;
END;
SELECT c.*
FROM customer_order_det_tb c;
--------------------------------------------
--------------------------------------------
--------------------------------------------
--Writing a Quer to display all the customer who have placed maximum number of order
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
--------------------------------
100 Murugappan 2
102 Ramesh 2
101 Raja 1
--------------------------------
----------
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;
****************************************/
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
) query1,
) query2
-------------------------------
-------------------------------
100 Murugappan 2
102 Ramesh 2
-------------------------------
FROM employees e
Example :
--in 11g
SELECT *
FROM departments d
--in 12c
SELECT *
FROM departments d
);
--in 11g
WITH t
AS
( SELECT LEVEL a
FROM dual
SELECT *
FROM t, (SELECT *
FROM employees
);
WITH t
AS
SELECT * FROM t,
LATERAL(SELECT *
FROM employees
0 Add a comment
JAN
23
--creating table
CREATE TABLE employee_data
eid NUMBER(4),
ename VARCHAR2(30),
depno NUMBER(3),
salary NUMBER(8)
);
BEGIN
--Inserting records
COMMIT;
END;
/
SELECT MAX(salary)
FROM employee_data
FROM employee_data);
SELECT MIN(salary)
FROM employee_data
SELECT MIN(salary)
FROM employee_data
--query to select all the details of the employee whose getting nth maximum salary
SELECT *
rownum rn
FROM (SELECT *
FROM employee_data
WHERE rn = 9;
--same query using row_numbr( ) function
SELECT *
WHERE rank = 9;
SELECT *
WHERE rank = 4;
SELECT *
WHERE rank = 4;
--query to display display maximum salary in all the department
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
--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
SELECT employee_id,
first_name,
salary
FROM employees
7 View comments
JAN
22
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.
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.
Elapsed: 00:00:14.01
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.
0 Add a comment
DEC
21
Constraints
Format : [part_of_project_name-table_name-column_name-constraint_type]
Format : sys_cn
Example : SYS_C405323
Types
Primary Key
Ex : Employee_id, Student_id
Unique Key
Ex : Contact_no, email
Foreign Key
c1(pk) : 1 2 3
Not Null
Check
------------------------------------
Duplicate NULL
------------------------------------
Primary Key X X
------------------------------------
S_id Number(2),
s_mail Varchar2(30),
s_gender char(1),
s_did Number(3),
);
DESC my_stu_details;
------------------------------------
------------------------------------
S_ID NUMBER(2)
S_NAME VARCHAR2(30)
S_MAIL VARCHAR2(30) Y
S_GENDER CHAR(1) Y
S_DID NUMBER(3) Y
------------------------------------
--Duplicate Check
--Null Check
Insert into 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
--------------------------------------------------------
------------------------------------------------------------
-------------------------------------------------
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
-------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
SELECT c.owner,
c.constraint_name,
c.constraint_type,
c.table_name,
c.r_constraint_name,
c.status
FROM user_constraints c
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
HR SYS_C004023 C MY_STU_DETAILS ENABLED
------------------------------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
Creating Composite Primary Key
In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.
Interview Questions
Which Data Dictionary table contains information about constraint with corresponding column
name?
1 View comments
good
Reply
DEC
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 :
--Example 1:
BEGIN
commit;
END;
listagg(product,
',') within
FROM test_ins
GROUP BY empid;
-->-- Example 2
FROM employees
GROUP BY department_id;
0 Add a comment
NOV
8
Condition and Looping Statement
IF
IF ELSE
Multiple IF ELSE
LOOP
FOR LOOP
WHILE LOOP
BEGIN
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;
UPDATE test_udt t
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;
UPDATE test_udt t
ELSE
UPDATE test_udt t
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;
v_salary := v_salary+10005;
ELSE
v_salary := v_salary+20007;
END IF;
UPDATE test_udt t
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');
v_salary := 2000;
dbms_output.put_line('2 inside');
v_salary := 3000;
dbms_output.put_line('3 inside');
v_salary := 4000;
dbms_output.put_line('4 inside');
END IF;
UPDATE test_udt t
commit;
END;
LOOP
--syntax
LOOP
--statements
--increment
--exit statement
END LOOP;
i NUMBER := 1;
x VARCHAR2(3);
BEGIN
LOOP
x := lpad(i,3,'0');
i := i+1;
IF MOD(i,100) = 0 THEN
commit;
dbms_output.put_line('commit executed');
END IF;
END LOOP;
END;
FOR LOOP
BEGIN
FOR I in 1..5
LOOP
END LOOP;
END;
BEGIN
LOOP
END LOOP;
END;
WHILE LOOP
DECLARE
i_val NUMBER:=0;
BEGIN
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
0 Add a comment
OCT
21
Bulk Collect
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.
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
SELECT * FROM product_details;
BEGIN
OPEN proddt_cur;
INTO dta;
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta alldata_typ;
BEGIN
END LOOP;
END;
-->-- LIMIT in Bulk collect --<--
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta1 alldata_typ1;
dta2 alldata_typ2;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END LOOP;
END;
/
0 Add a comment
OCT
21
Ref Cursor
This is unconstrained cursor which will return different types depends upon the user input.
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.
AS
BEGIN
OPEN dep_det_c
FOR
END;
DECLARE
dep_det_c SYS_REFCURSOR;
tab_data dep_details%ROWTYPE;
BEGIN
ref_c_sp(dep_det_c);
LOOP
END LOOP;
CLOSE dep_det_c;
END;
/*sample output*/
0 Add a comment
OCT
21
Cursor
SQL Private work Area where the query get passed and executed.
Types
******
Implicit(SQL)
Explicit
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
Cursor Stages
**************
OPEN cursor_name
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
Cursor Declaration
DECLARE
CURSOR <cursor_name>
IS
<SELECT statement>
BEGIN
END;
Cursor Loop
Loop
While Loop
For Loop
Cursor Clauses
Return
For update
Where current of
Bulk collect
p_id NUMBER,
p_name VARCHAR2(30),
p_order_dt DATE
);
BEGIN
FOR i IN 1 .. 75 LOOP
END LOOP;
commit;
END;
-->-- selecting data
---------------------------------------------
---------------------------------------------
---------------------------------------------
----------------------------------------------
Implicit Cursor
----------------------------------------------
----------------------------------------------
Explicit Cursor
----------------------------------------------
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
SELECT * FROM product_details
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
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
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*/
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
FETCH prod_detail_cur
INTO all_data;
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
************************************************************
************************************************************
DECLARE
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
FOR i IN prod_detail_cur
LOOP
END LOOP;
END;
/*sample output*/
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.
BEGIN
commit;
END;
----------------------------
----------------------------
1 Admin 1010
2 HR 1010
3 Sales 1020
4 Marketing 1020
----------------------------
DECLARE
all_data dep_details%ROWTYPE;
BEGIN
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1010);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1020);
LOOP
FETCH dep_det_c
INTO all_data;
EXIT WHEN dep_det_c%NOTFOUND;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
END;
/*sample output*/
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
0 Add a comment
OCT
21
Handling Exception
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
*********************
Oracle has predefined several exceptions that correspond to the most common oracle errors.
------------------------------------------------------------------------
------------------------------------------------------------------------
DUP_VAL_ON_INDEX ORA-00001 -1
OTHERS
------------------------------------------------------------------------
DECLARE
v_result NUMBER;
BEGIN
SELECT 23 / 0 INTO v_result FROM dual;
EXCEPTION
END;
Single row SELECT returned no rows or your program referenced a deleted element in a nested
table
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
-->-- DUP_VAL_ON_INDEX --<--
commit;
BEGIN
EXCEPTION
END;
DECLARE
v_id NUMBER;
BEGIN
SELECT id INTO v_id FROM test_tb;
EXCEPTION
END;
DECLARE
num1 NUMBER(2);
BEGIN
num1 := 345;
EXCEPTION
END;
BEGIN
COMMIT;
END;
DECLARE
cursor emp_c IS
all_data emp%ROWTYPE;
BEGIN
OPEN emp_c;
OPEN emp_c;
NULL;
CLOSE emp_c;
EXCEPTION
END;
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
**********************
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,
DECLARE
gender_ex EXCEPTION;
BEGIN
RAISE gender_ex;
END IF;
dbms_output.put_line('Gender : '||v_gender);
EXCEPTION
END;
DECLARE
abort_ex EXCEPTION;
BEGIN
FOR i IN 1..100
LOOP
BEGIN
IF mod(i,10)=0 THEN
RAISE abort_ex;
END IF;
EXCEPTION
NULL;
END;
END LOOP;
COMMIT;
END;
********************
SQLCODE returns the current error code, and SQLERRM returns the current error message
text;
SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.
DECLARE
v_id NUMBER;
BEGIN
dbms_output.put_line(v_id);
EXCEPTION
END;
/*sample output*/
SQLCODE : 100
*********************
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:
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
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 :
DECLARE
BEGIN
END IF;
END;
1 View comments
Loading
search
JUL
20
--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
, AVG(b.salary) avg_sal
FROM employees b
GROUP BY b.department_id
)b
Display all the customer who have placed more number of orders by using INLINE view
( custm_id NUMBER ,
custm_nm VARCHAR2(30) ,
ttl_amt NUMBER(7,2)
);
BEGIN
COMMIT;
END;
SELECT c.*
FROM customer_order_det_tb c;
--------------------------------------------
--------------------------------------------
--------------------------------------------
--Writing a Quer to display all the customer who have placed maximum number of order
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
--------------------------------
100 Murugappan 2
102 Ramesh 2
101 Raja 1
--------------------------------
----------
total_odr
----------
----------
Inline view to find all the customers who have placed maximum number of orders
/****************************************
Syntax
WHERE contition;
****************************************/
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
) query1,
) query2
-------------------------------
-------------------------------
100 Murugappan 2
102 Ramesh 2
-------------------------------
--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 employees e
Example :
--in 11g
SELECT *
FROM departments d
SELECT *
FROM departments d
);
--in 11g
WITH t
AS
( SELECT LEVEL a
FROM dual
SELECT *
FROM t, (SELECT *
FROM employees
);
--in 12c
WITH t
AS
SELECT * FROM t,
LATERAL(SELECT *
FROM employees
0 Add a comment
JAN
23
--creating table
eid NUMBER(4),
ename VARCHAR2(30),
depno NUMBER(3),
salary NUMBER(8)
);
BEGIN
--Inserting records
COMMIT;
END;
/
SELECT * FROM employee_data
SELECT MAX(salary)
FROM employee_data
FROM employee_data);
SELECT MIN(salary)
FROM employee_data
ORDER BY salary DESC)
SELECT MIN(salary)
FROM employee_data
--query to select all the details of the employee whose getting nth maximum salary
SELECT *
rownum rn
FROM (SELECT *
FROM employee_data
WHERE rn = 9;
WHERE rank = 9;
SELECT *
WHERE rank = 4;
SELECT *
WHERE rank = 4;
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
--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
--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,
first_name,
salary
FROM employees
7 View comments
JAN
22
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.
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.
14 rows selected.
Elapsed: 00:00:14.01
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.
0 Add a comment
DEC
21
Constraints
Format : [part_of_project_name-table_name-column_name-constraint_type]
Format : sys_cn
Example : SYS_C405323
Types
Primary Key
Ex : Employee_id, Student_id
Unique Key
allowed Null value
Ex : Contact_no, email
Foreign Key
c1(pk) : 1 2 3
Not Null
Check
Duplicate NULL
------------------------------------
Primary Key X X
------------------------------------
S_id Number(2),
s_mail Varchar2(30),
s_gender char(1),
s_did Number(3),
);
DESC my_stu_details;
------------------------------------
------------------------------------
S_ID NUMBER(2)
S_NAME VARCHAR2(30)
S_MAIL VARCHAR2(30) Y
S_GENDER CHAR(1) Y
S_DID NUMBER(3) Y
------------------------------------
--Duplicate Check
--Null Check
--------------------------------------------------------
--------------------------------------------------------
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
--------------------------------------------------------
------------------------------------------------------------
-------------------------------------------------
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
-------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
ON DELETE CASCADE
Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)
SELECT c.owner,
c.constraint_name,
c.constraint_type,
c.table_name,
c.r_constraint_name,
c.status
FROM user_constraints c
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.
Interview Questions
Which Data Dictionary table contains information about constraint with corresponding column
name?
1 View comments
good
Reply
DEC
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 :
--Example 1:
BEGIN
commit;
END;
listagg(product,
',') within
FROM test_ins
GROUP BY empid;
-->-- Example 2
FROM employees
GROUP BY department_id;
0 Add a comment
NOV
IF ELSE
Multiple IF ELSE
LOOP
FOR LOOP
WHILE LOOP
BEGIN
Commit;
END;
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 1;
UPDATE test_udt t
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;
UPDATE test_udt t
ELSE
UPDATE test_udt t
END IF;
commit;
END;
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 2;
v_salary := v_salary+10005;
ELSE
v_salary := v_salary+20007;
END IF;
UPDATE test_udt t
commit;
END;
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');
v_salary := 2000;
dbms_output.put_line('2 inside');
v_salary := 3000;
dbms_output.put_line('3 inside');
v_salary := 4000;
dbms_output.put_line('4 inside');
END IF;
UPDATE test_udt t
commit;
END;
LOOP
--syntax
LOOP
--statements
--increment
--exit statement
END LOOP;
DECLARE
i NUMBER := 1;
x VARCHAR2(3);
BEGIN
LOOP
x := lpad(i,3,'0');
i := i+1;
IF MOD(i,100) = 0 THEN
commit;
dbms_output.put_line('commit executed');
END IF;
END LOOP;
END;
FOR LOOP
BEGIN
FOR I in 1..5
LOOP
END LOOP;
END;
BEGIN
LOOP
END LOOP;
END;
WHILE LOOP
DECLARE
i_val NUMBER:=0;
BEGIN
LOOP
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
0 Add a comment
OCT
21
Bulk Collect
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.
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
INTO dta;
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta alldata_typ;
BEGIN
END LOOP;
END;
-->-- LIMIT in Bulk collect --<--
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END;
dta1 alldata_typ1;
dta2 alldata_typ2;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END LOOP;
END;
/
DROP TABLE dep_details;
0 Add a comment
OCT
21
Ref Cursor
This is unconstrained cursor which will return different types depends upon the user input.
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.
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
END LOOP;
CLOSE dep_det_c;
END;
/*sample output*/
Department Name : HR
0 Add a comment
OCT
21
Cursor
SQL Private work Area where the query get passed and executed.
Types
******
Implicit(SQL)
Explicit
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
Cursor Stages
**************
OPEN cursor_name
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
Cursor Declaration
DECLARE
CURSOR <cursor_name>
IS
<SELECT statement>
BEGIN
END;
Cursor Loop
Loop
While Loop
For Loop
Cursor Clauses
Return
For update
Where current of
Bulk collect
p_id NUMBER,
p_name VARCHAR2(30),
p_order_dt DATE
);
BEGIN
FOR i IN 1 .. 75 LOOP
END LOOP;
commit;
END;
-->-- selecting data
---------------------------------------------
---------------------------------------------
---------------------------------------------
----------------------------------------------
Implicit Cursor
----------------------------------------------
----------------------------------------------
Explicit Cursor
----------------------------------------------
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
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
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
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*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
EXIT WHEN prod_detail_cur%NOTFOUND;
END LOOP;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
FETCH prod_detail_cur
INTO all_data;
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
************************************************************
************************************************************
DECLARE
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
FOR i IN prod_detail_cur
LOOP
END LOOP;
END;
/*sample output*/
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.
BEGIN
commit;
END;
----------------------------
----------------------------
1 Admin 1010
2 HR 1010
3 Sales 1020
4 Marketing 1020
----------------------------
DECLARE
all_data dep_details%ROWTYPE;
BEGIN
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1010);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1020);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
END;
/*sample output*/
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
0 Add a comment
OCT
21
Handling Exception
Error Handling in oracle
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
Predefined Exception
*********************
Oracle has predefined several exceptions that correspond to the most common oracle errors.
------------------------------------------------------------------------
------------------------------------------------------------------------
DUP_VAL_ON_INDEX ORA-00001 -1
OTHERS
------------------------------------------------------------------------
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
WHEN ZERO_DIVIDE THEN
END;
Single row SELECT returned no rows or your program referenced a deleted element in a nested
table
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
commit;
BEGIN
EXCEPTION
END;
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
WHEN TOO_MANY_ROWS THEN
END;
DECLARE
num1 NUMBER(2);
BEGIN
num1 := 345;
EXCEPTION
END;
BEGIN
COMMIT;
END;
DECLARE
cursor emp_c IS
all_data emp%ROWTYPE;
BEGIN
OPEN emp_c;
OPEN emp_c;
NULL;
CLOSE emp_c;
EXCEPTION
END;
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
**********************
DECLARE
gender_ex EXCEPTION;
BEGIN
RAISE gender_ex;
END IF;
dbms_output.put_line('Gender : '||v_gender);
EXCEPTION
END;
DECLARE
abort_ex EXCEPTION;
BEGIN
FOR i IN 1..100
LOOP
BEGIN
IF mod(i,10)=0 THEN
RAISE abort_ex;
END IF;
EXCEPTION
NULL;
END;
END LOOP;
COMMIT;
END;
********************
SQLCODE returns the current error code, and SQLERRM returns the current error message
text;
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
dbms_output.put_line(v_id);
EXCEPTION
END;
/*sample output*/
SQLCODE : 100
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:
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
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 :
DECLARE
BEGIN
END IF;
END;
1 View comments
Loading
Dynamic Views theme. Powered by Blogger.
search
JUL
20
--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
, AVG(b.salary) avg_sal
FROM employees b
GROUP BY b.department_id
)b
Display all the customer who have placed more number of orders by using INLINE view
( custm_id NUMBER ,
custm_nm VARCHAR2(30) ,
ttl_amt NUMBER(7,2)
);
BEGIN
COMMIT;
END;
SELECT c.*
FROM customer_order_det_tb c;
--------------------------------------------
--------------------------------------------
--------------------------------------------
--Writing a Quer to display all the customer who have placed maximum number of order
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
--------------------------------
--------------------------------
100 Murugappan 2
102 Ramesh 2
101 Raja 1
--------------------------------
----------
total_odr
----------
----------
Inline view to find all the customers who have placed maximum number of orders
/****************************************
Syntax
WHERE contition;
****************************************/
SELECT query1.* FROM
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
) query1,
) query2
-------------------------------
-------------------------------
100 Murugappan 2
102 Ramesh 2
-------------------------------
--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT
FROM employees e
Example :
--in 11g
SELECT *
FROM departments d
SELECT *
FROM departments d
);
--in 11g
WITH t
AS
( SELECT LEVEL a
FROM dual
SELECT *
FROM t, (SELECT *
FROM employees
);
--in 12c
WITH t
AS
(SELECT LEVEL a FROM dual CONNECT BY LEVEL <= 30)
SELECT * FROM t,
LATERAL(SELECT *
FROM employees
0 Add a comment
JAN
23
--creating table
eid NUMBER(4),
ename VARCHAR2(30),
depno NUMBER(3),
salary NUMBER(8)
);
BEGIN
--Inserting records
COMMIT;
END;
SELECT MAX(salary)
FROM employee_data
FROM employee_data);
SELECT MIN(salary)
FROM employee_data
SELECT MIN(salary)
FROM employee_data
--query to select all the details of the employee whose getting nth maximum salary
SELECT *
rownum rn
FROM (SELECT *
FROM employee_data
WHERE rn = 9;
SELECT *
FROM (SELECT emp.*,
WHERE rank = 9;
SELECT *
WHERE rank = 4;
SELECT *
WHERE rank = 4;
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
--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
--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,
first_name,
salary
FROM employees
7 View comments
JAN
22
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.
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
14 rows selected.
Elapsed: 00:00:14.01
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.
0 Add a comment
DEC
21
Constraints
Format : [part_of_project_name-table_name-column_name-constraint_type]
Format : sys_cn
Example : SYS_C405323
Types
Primary Key
Ex : Employee_id, Student_id
Unique Key
allowed Null value
Ex : Contact_no, email
Foreign Key
c1(pk) : 1 2 3
Not Null
Check
Duplicate NULL
------------------------------------
Primary Key X X
------------------------------------
S_id Number(2),
s_mail Varchar2(30),
s_gender char(1),
s_did Number(3),
);
DESC my_stu_details;
------------------------------------
------------------------------------
S_ID NUMBER(2)
S_NAME VARCHAR2(30)
S_MAIL VARCHAR2(30) Y
S_GENDER CHAR(1) Y
S_DID NUMBER(3) Y
------------------------------------
--Duplicate Check
--Null Check
--------------------------------------------------------
--------------------------------------------------------
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
--------------------------------------------------------
------------------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
-------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
ON DELETE CASCADE
Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)
SELECT c.owner,
c.constraint_name,
c.constraint_type,
c.table_name,
c.r_constraint_name,
c.status
FROM user_constraints c
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.
Interview Questions
Which Data Dictionary table contains information about constraint with corresponding column
name?
1 View comments
good
Reply
DEC
4
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 :
--Example 1:
BEGIN
END;
listagg(product,
',') within
FROM test_ins
GROUP BY empid;
-->-- Example 2
FROM employees
GROUP BY department_id;
0 Add a comment
NOV
IF ELSE
Multiple IF ELSE
LOOP
FOR LOOP
WHILE LOOP
BEGIN
Commit;
END;
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 1;
UPDATE test_udt t
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;
UPDATE test_udt t
ELSE
UPDATE test_udt t
END IF;
commit;
END;
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 2;
v_salary := v_salary+10005;
ELSE
v_salary := v_salary+20007;
END IF;
UPDATE test_udt t
commit;
END;
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');
v_salary := 2000;
dbms_output.put_line('2 inside');
v_salary := 3000;
dbms_output.put_line('3 inside');
v_salary := 4000;
dbms_output.put_line('4 inside');
END IF;
UPDATE test_udt t
SET t.salary = v_salary
commit;
END;
LOOP
--syntax
LOOP
--statements
--increment
--exit statement
END LOOP;
DECLARE
i NUMBER := 1;
x VARCHAR2(3);
BEGIN
LOOP
x := lpad(i,3,'0');
i := i+1;
IF MOD(i,100) = 0 THEN
commit;
dbms_output.put_line('commit executed');
END IF;
END LOOP;
END;
FOR LOOP
BEGIN
FOR I in 1..5
LOOP
Dbms_output.put_line('The value of i : '||i);
END LOOP;
END;
BEGIN
LOOP
END LOOP;
END;
WHILE LOOP
DECLARE
i_val NUMBER:=0;
BEGIN
LOOP
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
0 Add a comment
OCT
21
Bulk Collect
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.
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
FETCH proddt_cur BULK COLLECT
INTO dta;
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta alldata_typ;
BEGIN
END LOOP;
END;
-->-- LIMIT in Bulk collect --<--
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END;
dta1 alldata_typ1;
dta2 alldata_typ2;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END LOOP;
END;
/
DROP TABLE dep_details;
0 Add a comment
OCT
21
Ref Cursor
This is unconstrained cursor which will return different types depends upon the user input.
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.
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
END LOOP;
CLOSE dep_det_c;
END;
/*sample output*/
Department Name : HR
0 Add a comment
OCT
21
Cursor
SQL Private work Area where the query get passed and executed.
Types
******
Implicit(SQL)
Explicit
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
Cursor Stages
**************
OPEN cursor_name
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
Cursor Declaration
DECLARE
CURSOR <cursor_name>
IS
<SELECT statement>
BEGIN
END;
Cursor Loop
Loop
While Loop
For Loop
Cursor Clauses
Return
For update
Where current of
Bulk collect
p_id NUMBER,
p_name VARCHAR2(30),
p_order_dt DATE
);
BEGIN
FOR i IN 1 .. 75 LOOP
END LOOP;
commit;
END;
-->-- selecting data
---------------------------------------------
---------------------------------------------
---------------------------------------------
----------------------------------------------
Implicit Cursor
----------------------------------------------
----------------------------------------------
Explicit Cursor
----------------------------------------------
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
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
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
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*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
EXIT WHEN prod_detail_cur%NOTFOUND;
END LOOP;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
FETCH prod_detail_cur
INTO all_data;
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
************************************************************
************************************************************
DECLARE
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
FOR i IN prod_detail_cur
LOOP
END LOOP;
END;
/*sample output*/
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.
BEGIN
commit;
END;
----------------------------
----------------------------
1 Admin 1010
2 HR 1010
3 Sales 1020
4 Marketing 1020
----------------------------
DECLARE
all_data dep_details%ROWTYPE;
BEGIN
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1010);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1020);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
END;
/*sample output*/
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
0 Add a comment
OCT
21
Handling Exception
Error Handling in oracle
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
Predefined Exception
*********************
Oracle has predefined several exceptions that correspond to the most common oracle errors.
------------------------------------------------------------------------
------------------------------------------------------------------------
DUP_VAL_ON_INDEX ORA-00001 -1
OTHERS
------------------------------------------------------------------------
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
WHEN ZERO_DIVIDE THEN
END;
Single row SELECT returned no rows or your program referenced a deleted element in a nested
table
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
commit;
BEGIN
EXCEPTION
END;
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
WHEN TOO_MANY_ROWS THEN
END;
DECLARE
num1 NUMBER(2);
BEGIN
num1 := 345;
EXCEPTION
END;
BEGIN
COMMIT;
END;
DECLARE
cursor emp_c IS
all_data emp%ROWTYPE;
BEGIN
OPEN emp_c;
OPEN emp_c;
NULL;
CLOSE emp_c;
EXCEPTION
END;
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
**********************
DECLARE
gender_ex EXCEPTION;
BEGIN
RAISE gender_ex;
END IF;
dbms_output.put_line('Gender : '||v_gender);
EXCEPTION
END;
DECLARE
abort_ex EXCEPTION;
BEGIN
FOR i IN 1..100
LOOP
BEGIN
IF mod(i,10)=0 THEN
RAISE abort_ex;
END IF;
EXCEPTION
NULL;
END;
END LOOP;
COMMIT;
END;
********************
SQLCODE returns the current error code, and SQLERRM returns the current error message
text;
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
dbms_output.put_line(v_id);
EXCEPTION
END;
/*sample output*/
SQLCODE : 100
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:
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
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 :
DECLARE
BEGIN
END IF;
END;
1 View comments
Loading
Dynamic Views theme. Powered by Blogger.
search
JUL
20
--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
, AVG(b.salary) avg_sal
FROM employees b
GROUP BY b.department_id
)b
Display all the customer who have placed more number of orders by using INLINE view
( custm_id NUMBER ,
custm_nm VARCHAR2(30) ,
ttl_amt NUMBER(7,2)
);
BEGIN
COMMIT;
END;
SELECT c.*
FROM customer_order_det_tb c;
--------------------------------------------
--------------------------------------------
--------------------------------------------
--Writing a Quer to display all the customer who have placed maximum number of order
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
--------------------------------
--------------------------------
100 Murugappan 2
102 Ramesh 2
101 Raja 1
--------------------------------
----------
total_odr
----------
----------
Inline view to find all the customers who have placed maximum number of orders
/****************************************
Syntax
WHERE contition;
****************************************/
SELECT query1.* FROM
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
) query1,
) query2
-------------------------------
-------------------------------
100 Murugappan 2
102 Ramesh 2
-------------------------------
--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT
FROM employees e
Example :
--in 11g
SELECT *
FROM departments d
SELECT *
FROM departments d
);
--in 11g
WITH t
AS
( SELECT LEVEL a
FROM dual
SELECT *
FROM t, (SELECT *
FROM employees
);
--in 12c
WITH t
AS
(SELECT LEVEL a FROM dual CONNECT BY LEVEL <= 30)
SELECT * FROM t,
LATERAL(SELECT *
FROM employees
0 Add a comment
JAN
23
--creating table
eid NUMBER(4),
ename VARCHAR2(30),
depno NUMBER(3),
salary NUMBER(8)
);
BEGIN
--Inserting records
COMMIT;
END;
SELECT MAX(salary)
FROM employee_data
FROM employee_data);
SELECT MIN(salary)
FROM employee_data
SELECT MIN(salary)
FROM employee_data
--query to select all the details of the employee whose getting nth maximum salary
SELECT *
rownum rn
FROM (SELECT *
FROM employee_data
WHERE rn = 9;
SELECT *
FROM (SELECT emp.*,
WHERE rank = 9;
SELECT *
WHERE rank = 4;
SELECT *
WHERE rank = 4;
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
--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
--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,
first_name,
salary
FROM employees
7 View comments
JAN
22
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.
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
14 rows selected.
Elapsed: 00:00:14.01
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.
0 Add a comment
DEC
21
Constraints
Format : [part_of_project_name-table_name-column_name-constraint_type]
Format : sys_cn
Example : SYS_C405323
Types
Primary Key
Ex : Employee_id, Student_id
Unique Key
allowed Null value
Ex : Contact_no, email
Foreign Key
c1(pk) : 1 2 3
Not Null
Check
Duplicate NULL
------------------------------------
Primary Key X X
------------------------------------
S_id Number(2),
s_mail Varchar2(30),
s_gender char(1),
s_did Number(3),
);
DESC my_stu_details;
------------------------------------
------------------------------------
S_ID NUMBER(2)
S_NAME VARCHAR2(30)
S_MAIL VARCHAR2(30) Y
S_GENDER CHAR(1) Y
S_DID NUMBER(3) Y
------------------------------------
--Duplicate Check
--Null Check
--------------------------------------------------------
--------------------------------------------------------
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
--------------------------------------------------------
------------------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
-------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
ON DELETE CASCADE
Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)
SELECT c.owner,
c.constraint_name,
c.constraint_type,
c.table_name,
c.r_constraint_name,
c.status
FROM user_constraints c
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.
Interview Questions
Which Data Dictionary table contains information about constraint with corresponding column
name?
1 View comments
good
Reply
DEC
4
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 :
--Example 1:
BEGIN
END;
listagg(product,
',') within
FROM test_ins
GROUP BY empid;
-->-- Example 2
FROM employees
GROUP BY department_id;
0 Add a comment
NOV
IF ELSE
Multiple IF ELSE
LOOP
FOR LOOP
WHILE LOOP
BEGIN
Commit;
END;
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 1;
UPDATE test_udt t
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;
UPDATE test_udt t
ELSE
UPDATE test_udt t
END IF;
commit;
END;
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 2;
v_salary := v_salary+10005;
ELSE
v_salary := v_salary+20007;
END IF;
UPDATE test_udt t
commit;
END;
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');
v_salary := 2000;
dbms_output.put_line('2 inside');
v_salary := 3000;
dbms_output.put_line('3 inside');
v_salary := 4000;
dbms_output.put_line('4 inside');
END IF;
UPDATE test_udt t
SET t.salary = v_salary
commit;
END;
LOOP
--syntax
LOOP
--statements
--increment
--exit statement
END LOOP;
DECLARE
i NUMBER := 1;
x VARCHAR2(3);
BEGIN
LOOP
x := lpad(i,3,'0');
i := i+1;
IF MOD(i,100) = 0 THEN
commit;
dbms_output.put_line('commit executed');
END IF;
END LOOP;
END;
FOR LOOP
BEGIN
FOR I in 1..5
LOOP
Dbms_output.put_line('The value of i : '||i);
END LOOP;
END;
BEGIN
LOOP
END LOOP;
END;
WHILE LOOP
DECLARE
i_val NUMBER:=0;
BEGIN
LOOP
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
0 Add a comment
OCT
21
Bulk Collect
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.
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
FETCH proddt_cur BULK COLLECT
INTO dta;
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta alldata_typ;
BEGIN
END LOOP;
END;
-->-- LIMIT in Bulk collect --<--
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END;
dta1 alldata_typ1;
dta2 alldata_typ2;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END LOOP;
END;
/
DROP TABLE dep_details;
0 Add a comment
OCT
21
Ref Cursor
This is unconstrained cursor which will return different types depends upon the user input.
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.
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
END LOOP;
CLOSE dep_det_c;
END;
/*sample output*/
Department Name : HR
0 Add a comment
OCT
21
Cursor
SQL Private work Area where the query get passed and executed.
Types
******
Implicit(SQL)
Explicit
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
Cursor Stages
**************
OPEN cursor_name
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
Cursor Declaration
DECLARE
CURSOR <cursor_name>
IS
<SELECT statement>
BEGIN
END;
Cursor Loop
Loop
While Loop
For Loop
Cursor Clauses
Return
For update
Where current of
Bulk collect
p_id NUMBER,
p_name VARCHAR2(30),
p_order_dt DATE
);
BEGIN
FOR i IN 1 .. 75 LOOP
END LOOP;
commit;
END;
-->-- selecting data
---------------------------------------------
---------------------------------------------
---------------------------------------------
----------------------------------------------
Implicit Cursor
----------------------------------------------
----------------------------------------------
Explicit Cursor
----------------------------------------------
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
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
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
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*/
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
FETCH prod_detail_cur
INTO all_data;
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
************************************************************
************************************************************
DECLARE
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
FOR i IN prod_detail_cur
LOOP
dbms_output.put_line('Product id : ' || i.p_id ||
END LOOP;
END;
/*sample output*/
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.
BEGIN
commit;
END;
----------------------------
----------------------------
1 Admin 1010
2 HR 1010
3 Sales 1020
4 Marketing 1020
----------------------------
DECLARE
-->--Declaring parameterized cursor
all_data dep_details%ROWTYPE;
BEGIN
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1010);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1020);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
END;
/*sample output*/
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
0 Add a comment
OCT
21
Handling Exception
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
Predefined Exception
*********************
Oracle has predefined several exceptions that correspond to the most common oracle errors.
------------------------------------------------------------------------
------------------------------------------------------------------------
DUP_VAL_ON_INDEX ORA-00001 -1
OTHERS
------------------------------------------------------------------------
DECLARE
v_result NUMBER;
BEGIN
END;
Single row SELECT returned no rows or your program referenced a deleted element in a nested
table
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
commit;
BEGIN
EXCEPTION
END;
DECLARE
v_id NUMBER;
BEGIN
END;
DECLARE
num1 NUMBER(2);
BEGIN
num1 := 345;
EXCEPTION
END;
BEGIN
COMMIT;
END;
DECLARE
cursor emp_c IS
all_data emp%ROWTYPE;
BEGIN
OPEN emp_c;
OPEN emp_c;
NULL;
CLOSE emp_c;
EXCEPTION
WHEN CURSOR_ALREADY_OPEN THEN
END;
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
**********************
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,
DECLARE
gender_ex EXCEPTION;
BEGIN
RAISE gender_ex;
END IF;
dbms_output.put_line('Gender : '||v_gender);
EXCEPTION
END;
DECLARE
abort_ex EXCEPTION;
BEGIN
FOR i IN 1..100
LOOP
BEGIN
IF mod(i,10)=0 THEN
RAISE abort_ex;
END IF;
EXCEPTION
NULL;
END;
END LOOP;
COMMIT;
END;
********************
SQLCODE returns the current error code, and SQLERRM returns the current error message
text;
DECLARE
v_id NUMBER;
BEGIN
dbms_output.put_line(v_id);
EXCEPTION
END;
/*sample output*/
SQLCODE : 100
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:
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
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 :
DECLARE
BEGIN
END IF;
END;
1 View comments
Loading
search
JUL
20
--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
, AVG(b.salary) avg_sal
FROM employees b
GROUP BY b.department_id
)b
Display all the customer who have placed more number of orders by using INLINE view
( custm_id NUMBER ,
custm_nm VARCHAR2(30) ,
ttl_amt NUMBER(7,2)
);
BEGIN
COMMIT;
END;
SELECT c.*
FROM customer_order_det_tb c;
--------------------------------------------
--------------------------------------------
--------------------------------------------
--Writing a Quer to display all the customer who have placed maximum number of order
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
--------------------------------
--------------------------------
100 Murugappan 2
102 Ramesh 2
101 Raja 1
--------------------------------
----------
total_odr
----------
----------
Inline view to find all the customers who have placed maximum number of orders
/****************************************
Syntax
WHERE contition;
****************************************/
SELECT query1.* FROM
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
) query1,
) query2
-------------------------------
-------------------------------
100 Murugappan 2
102 Ramesh 2
-------------------------------
--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 employees e
Example :
--in 11g
SELECT *
FROM departments d
SELECT *
FROM departments d
);
--in 11g
WITH t
AS
( SELECT LEVEL a
FROM dual
SELECT *
FROM t, (SELECT *
FROM employees
);
--in 12c
WITH t
AS
SELECT * FROM t,
LATERAL(SELECT *
FROM employees
0 Add a comment
JAN
23
--creating table
(
eid NUMBER(4),
ename VARCHAR2(30),
depno NUMBER(3),
salary NUMBER(8)
);
BEGIN
--Inserting records
COMMIT;
END;
/
SELECT * FROM employee_data
SELECT MAX(salary)
FROM employee_data
FROM employee_data);
SELECT MIN(salary)
FROM employee_data
SELECT MIN(salary)
FROM employee_data
--query to select all the details of the employee whose getting nth maximum salary
SELECT *
rownum rn
FROM (SELECT *
FROM employee_data
WHERE rn = 9;
WHERE rank = 9;
SELECT *
WHERE rank = 4;
SELECT *
WHERE rank = 4;
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
--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
--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,
first_name,
salary
FROM employees
7 View comments
JAN
22
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.
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.
14 rows selected.
Elapsed: 00:00:14.01
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.
0 Add a comment
DEC
21
Constraints
Format : [part_of_project_name-table_name-column_name-constraint_type]
Format : sys_cn
Example : SYS_C405323
Types
Primary Key
Ex : Employee_id, Student_id
Unique Key
allowed Null value
Ex : Contact_no, email
Foreign Key
c1(pk) : 1 2 3
Not Null
Check
Duplicate NULL
------------------------------------
Primary Key X X
------------------------------------
S_id Number(2),
s_mail Varchar2(30),
s_gender char(1),
s_did Number(3),
);
DESC my_stu_details;
------------------------------------
------------------------------------
S_ID NUMBER(2)
S_NAME VARCHAR2(30)
S_MAIL VARCHAR2(30) Y
S_GENDER CHAR(1) Y
S_DID NUMBER(3) Y
------------------------------------
--Duplicate Check
--Null Check
--------------------------------------------------------
--------------------------------------------------------
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
--------------------------------------------------------
------------------------------------------------------------
-------------------------------------------------
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
-------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
ON DELETE CASCADE
Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)
SELECT c.owner,
c.constraint_name,
c.constraint_type,
c.table_name,
c.r_constraint_name,
c.status
FROM user_constraints c
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.
Interview Questions
Which Data Dictionary table contains information about constraint with corresponding column
name?
1 View comments
good
Reply
DEC
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 :
--Example 1:
BEGIN
commit;
END;
listagg(product,
',') within
FROM test_ins
GROUP BY empid;
-->-- Example 2
FROM employees
GROUP BY department_id;
0 Add a comment
NOV
IF ELSE
Multiple IF ELSE
LOOP
FOR LOOP
WHILE LOOP
BEGIN
Commit;
END;
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 1;
UPDATE test_udt t
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;
UPDATE test_udt t
ELSE
UPDATE test_udt t
END IF;
commit;
END;
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 2;
v_salary := v_salary+10005;
ELSE
v_salary := v_salary+20007;
END IF;
UPDATE test_udt t
commit;
END;
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');
v_salary := 2000;
dbms_output.put_line('2 inside');
v_salary := 3000;
dbms_output.put_line('3 inside');
v_salary := 4000;
dbms_output.put_line('4 inside');
END IF;
UPDATE test_udt t
commit;
END;
LOOP
--syntax
LOOP
--statements
--increment
--exit statement
END LOOP;
DECLARE
i NUMBER := 1;
x VARCHAR2(3);
BEGIN
LOOP
x := lpad(i,3,'0');
i := i+1;
IF MOD(i,100) = 0 THEN
commit;
dbms_output.put_line('commit executed');
END IF;
END LOOP;
END;
FOR LOOP
BEGIN
FOR I in 1..5
LOOP
END LOOP;
END;
BEGIN
LOOP
END LOOP;
END;
WHILE LOOP
DECLARE
i_val NUMBER:=0;
BEGIN
LOOP
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
0 Add a comment
OCT
21
Bulk Collect
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.
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
INTO dta;
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta alldata_typ;
BEGIN
END LOOP;
END;
-->-- LIMIT in Bulk collect --<--
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END;
dta1 alldata_typ1;
dta2 alldata_typ2;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END LOOP;
END;
/
DROP TABLE dep_details;
0 Add a comment
OCT
21
Ref Cursor
This is unconstrained cursor which will return different types depends upon the user input.
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.
AS
BEGIN
OPEN dep_det_c
FOR
END;
DECLARE
dep_det_c SYS_REFCURSOR;
tab_data dep_details%ROWTYPE;
BEGIN
ref_c_sp(dep_det_c);
LOOP
END LOOP;
CLOSE dep_det_c;
END;
/*sample output*/
Department Name : HR
Department Name : Sales
0 Add a comment
OCT
21
Cursor
SQL Private work Area where the query get passed and executed.
Types
******
Implicit(SQL)
Explicit
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
Cursor Stages
**************
OPEN cursor_name
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
Cursor Declaration
DECLARE
CURSOR <cursor_name>
IS
<SELECT statement>
BEGIN
END;
Cursor Loop
Loop
While Loop
For Loop
Cursor Clauses
Return
For update
Where current of
Bulk collect
p_id NUMBER,
p_name VARCHAR2(30),
p_order_dt DATE
);
BEGIN
FOR i IN 1 .. 75 LOOP
END LOOP;
commit;
END;
-->-- selecting data
---------------------------------------------
---------------------------------------------
---------------------------------------------
----------------------------------------------
Implicit Cursor
----------------------------------------------
----------------------------------------------
Explicit Cursor
----------------------------------------------
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
SELECT * FROM product_details
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
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
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*/
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
FETCH prod_detail_cur
INTO all_data;
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
************************************************************
************************************************************
DECLARE
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
FOR i IN prod_detail_cur
LOOP
END LOOP;
END;
/*sample output*/
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.
BEGIN
commit;
END;
----------------------------
----------------------------
1 Admin 1010
2 HR 1010
3 Sales 1020
4 Marketing 1020
----------------------------
DECLARE
all_data dep_details%ROWTYPE;
BEGIN
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1010);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1020);
LOOP
FETCH dep_det_c
INTO all_data;
EXIT WHEN dep_det_c%NOTFOUND;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
END;
/*sample output*/
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
0 Add a comment
OCT
21
Handling Exception
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
*********************
Oracle has predefined several exceptions that correspond to the most common oracle errors.
------------------------------------------------------------------------
------------------------------------------------------------------------
DUP_VAL_ON_INDEX ORA-00001 -1
OTHERS
------------------------------------------------------------------------
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
Single row SELECT returned no rows or your program referenced a deleted element in a nested
table
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
-->-- DUP_VAL_ON_INDEX --<--
commit;
BEGIN
EXCEPTION
END;
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
DECLARE
num1 NUMBER(2);
BEGIN
num1 := 345;
EXCEPTION
END;
BEGIN
COMMIT;
END;
DECLARE
cursor emp_c IS
all_data emp%ROWTYPE;
BEGIN
OPEN emp_c;
OPEN emp_c;
NULL;
CLOSE emp_c;
EXCEPTION
END;
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
**********************
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,
DECLARE
gender_ex EXCEPTION;
BEGIN
RAISE gender_ex;
END IF;
dbms_output.put_line('Gender : '||v_gender);
EXCEPTION
END;
DECLARE
abort_ex EXCEPTION;
BEGIN
FOR i IN 1..100
LOOP
BEGIN
IF mod(i,10)=0 THEN
RAISE abort_ex;
END IF;
EXCEPTION
NULL;
END;
END LOOP;
COMMIT;
END;
********************
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.
DECLARE
v_id NUMBER;
BEGIN
dbms_output.put_line(v_id);
EXCEPTION
END;
/*sample output*/
SQLCODE : 100
*********************
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:
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
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 :
DECLARE
BEGIN
END IF;
END;
1 View comments
Loading
search
JUL
20
--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 b
GROUP BY b.department_id
)b
Display all the customer who have placed more number of orders by using INLINE view
( custm_id NUMBER ,
custm_nm VARCHAR2(30) ,
ttl_amt NUMBER(7,2)
);
BEGIN
COMMIT;
END;
SELECT c.*
FROM customer_order_det_tb c;
--------------------------------------------
--------------------------------------------
--------------------------------------------
--Writing a Quer to display all the customer who have placed maximum number of order
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
--------------------------------
custm_id custm_nm total_odr
--------------------------------
100 Murugappan 2
102 Ramesh 2
101 Raja 1
--------------------------------
----------
total_odr
----------
----------
Inline view to find all the customers who have placed maximum number of orders
/****************************************
Syntax
****************************************/
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
) query1,
) query2
-------------------------------
-------------------------------
100 Murugappan 2
102 Ramesh 2
-------------------------------
--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 employees e
Example :
--in 11g
SELECT *
FROM departments d
--in 12c
SELECT *
FROM departments d
);
--in 11g
WITH t
AS
( SELECT LEVEL a
FROM dual
SELECT *
FROM t, (SELECT *
FROM employees
);
WITH t
AS
SELECT * FROM t,
LATERAL(SELECT *
FROM employees
0 Add a comment
JAN
23
--creating table
CREATE TABLE employee_data
eid NUMBER(4),
ename VARCHAR2(30),
depno NUMBER(3),
salary NUMBER(8)
);
BEGIN
--Inserting records
COMMIT;
END;
/
SELECT * FROM employee_data
SELECT MAX(salary)
FROM employee_data
FROM employee_data);
SELECT MIN(salary)
SELECT MIN(salary)
FROM employee_data
--query to select all the details of the employee whose getting nth maximum salary
SELECT *
rownum rn
FROM (SELECT *
FROM employee_data
WHERE rn = 9;
--same query using row_numbr( ) function
SELECT *
WHERE rank = 9;
SELECT *
WHERE rank = 4;
SELECT *
WHERE rank = 4;
--query to display display maximum salary in all the department
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
--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
--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,
first_name,
salary
FROM employees
7 View comments
JAN
22
Why prefer COALESCE over NVL
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.
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.
Elapsed: 00:00:14.01
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.
0 Add a comment
DEC
21
Constraints
Format : [part_of_project_name-table_name-column_name-constraint_type]
Format : sys_cn
Example : SYS_C405323
Types
Primary Key
Ex : Employee_id, Student_id
Unique Key
Ex : Contact_no, email
Foreign Key
c1(pk) : 1 2 3
Not Null
Check
Duplicate NULL
------------------------------------
Primary Key X X
------------------------------------
S_id Number(2),
s_mail Varchar2(30),
s_gender char(1),
s_did Number(3),
DESC my_stu_details;
------------------------------------
------------------------------------
S_ID NUMBER(2)
S_NAME VARCHAR2(30)
S_MAIL VARCHAR2(30) Y
S_GENDER CHAR(1) Y
S_DID NUMBER(3) Y
------------------------------------
--Duplicate Check
--Null Check
--------------------------------------------------------
--------------------------------------------------------
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
--------------------------------------------------------
------------------------------------------------------------
-------------------------------------------------
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
-------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
SELECT c.owner,
c.constraint_name,
c.constraint_type,
c.table_name,
c.r_constraint_name,
c.status
FROM user_constraints c
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.
Interview Questions
Which Data Dictionary table contains information about constraint with corresponding column
name?
1 View comments
good
Reply
DEC
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 :
--Example 1:
BEGIN
commit;
END;
listagg(product,
',') within
FROM test_ins
GROUP BY empid;
-->-- Example 2
FROM employees
GROUP BY department_id;
0 Add a comment
NOV
IF ELSE
Multiple IF ELSE
LOOP
FOR LOOP
WHILE LOOP
BEGIN
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;
UPDATE test_udt t
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;
UPDATE test_udt t
ELSE
UPDATE test_udt t
END IF;
commit;
END;
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 2;
v_salary := v_salary+10005;
ELSE
v_salary := v_salary+20007;
END IF;
UPDATE test_udt t
commit;
END;
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');
v_salary := 2000;
dbms_output.put_line('2 inside');
v_salary := 3000;
dbms_output.put_line('3 inside');
v_salary := 4000;
dbms_output.put_line('4 inside');
END IF;
UPDATE test_udt t
commit;
END;
LOOP
--syntax
LOOP
--statements
--increment
--exit statement
END LOOP;
DECLARE
i NUMBER := 1;
x VARCHAR2(3);
BEGIN
LOOP
x := lpad(i,3,'0');
i := i+1;
IF MOD(i,100) = 0 THEN
commit;
dbms_output.put_line('commit executed');
END IF;
END LOOP;
END;
FOR LOOP
BEGIN
FOR I in 1..5
LOOP
END LOOP;
END;
BEGIN
LOOP
END LOOP;
END;
WHILE LOOP
DECLARE
i_val NUMBER:=0;
BEGIN
LOOP
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
0 Add a comment
OCT
21
Bulk Collect
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.
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
OPEN proddt_cur;
INTO dta;
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta alldata_typ;
BEGIN
END LOOP;
END;
-->-- LIMIT in Bulk collect --<--
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta1 alldata_typ1;
dta2 alldata_typ2;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END LOOP;
END;
/
DROP TABLE dep_details;
0 Add a comment
OCT
21
Ref Cursor
This is unconstrained cursor which will return different types depends upon the user input.
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.
AS
BEGIN
OPEN dep_det_c
FOR
END;
DECLARE
dep_det_c SYS_REFCURSOR;
tab_data dep_details%ROWTYPE;
BEGIN
ref_c_sp(dep_det_c);
LOOP
END LOOP;
CLOSE dep_det_c;
END;
/*sample output*/
0 Add a comment
OCT
21
Cursor
SQL Private work Area where the query get passed and executed.
Types
******
Implicit(SQL)
Explicit
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
Cursor Stages
**************
OPEN cursor_name
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
Cursor Declaration
DECLARE
CURSOR <cursor_name>
IS
<SELECT statement>
BEGIN
END;
Cursor Loop
Loop
While Loop
For Loop
Cursor Clauses
Return
For update
Where current of
Bulk collect
p_id NUMBER,
p_name VARCHAR2(30),
p_order_dt DATE
);
BEGIN
FOR i IN 1 .. 75 LOOP
END LOOP;
commit;
END;
---------------------------------------------
---------------------------------------------
---------------------------------------------
----------------------------------------------
Implicit Cursor
----------------------------------------------
----------------------------------------------
Explicit Cursor
----------------------------------------------
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
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
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
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*/
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
FETCH prod_detail_cur
INTO all_data;
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
************************************************************
************************************************************
DECLARE
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
FOR i IN prod_detail_cur
LOOP
END LOOP;
END;
/*sample output*/
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.
BEGIN
commit;
END;
----------------------------
----------------------------
1 Admin 1010
2 HR 1010
3 Sales 1020
4 Marketing 1020
----------------------------
DECLARE
all_data dep_details%ROWTYPE;
BEGIN
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1010);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1020);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
END;
/*sample output*/
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
0 Add a comment
OCT
21
Handling Exception
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
*********************
Oracle has predefined several exceptions that correspond to the most common oracle errors.
------------------------------------------------------------------------
------------------------------------------------------------------------
DUP_VAL_ON_INDEX ORA-00001 -1
OTHERS
------------------------------------------------------------------------
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
Single row SELECT returned no rows or your program referenced a deleted element in a nested
table
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
-->-- DUP_VAL_ON_INDEX --<--
commit;
BEGIN
EXCEPTION
END;
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
DECLARE
num1 NUMBER(2);
BEGIN
num1 := 345;
EXCEPTION
END;
-->-- CURSOR_ALREADY_OPEN --<--
BEGIN
COMMIT;
END;
DECLARE
cursor emp_c IS
all_data emp%ROWTYPE;
BEGIN
OPEN emp_c;
OPEN emp_c;
NULL;
CLOSE emp_c;
EXCEPTION
END;
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,
DECLARE
gender_ex EXCEPTION;
BEGIN
RAISE gender_ex;
END IF;
dbms_output.put_line('Gender : '||v_gender);
EXCEPTION
END;
DECLARE
abort_ex EXCEPTION;
BEGIN
FOR i IN 1..100
LOOP
BEGIN
IF mod(i,10)=0 THEN
RAISE abort_ex;
END IF;
EXCEPTION
NULL;
END;
END LOOP;
COMMIT;
END;
********************
SQLCODE returns the current error code, and SQLERRM returns the current error message
text;
SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.
DECLARE
v_id NUMBER;
BEGIN
dbms_output.put_line(v_id);
EXCEPTION
END;
/*sample output*/
SQLCODE : 100
*********************
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:
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
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 :
DECLARE
BEGIN
END IF;
END;
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
I) specification
II) Body
5. Overloading
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_sal_sp;
BEGIN
END;
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
EXCEPTION
WHEN OTHERS THEN
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_hdt_sp;
BEGIN
END;
RETURN NUMBER
IS
v_c NUMBER;
BEGIN
END;
--Specification Part
IS
RETURN NUMBER;
END emp_pkg ;
--Body Part
IS
v_first_name employees.first_name%TYPE;
v_error VARCHAR2(1000);
BEGIN
SELECT salary,
first_name
INTO v_salary,
v_first_name
FROM employees
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_sal_sp;
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_hdt_sp;
RETURN NUMBER
IS
v_c NUMBER;
BEGIN
RETURN v_c;
END;
END emp_pkg;
BEGIN
emp_pkg.emp_sal_sp(120);
END;
as
RETURN NUMBER;
IS
FROM employees;
End all_detail;
as
PROCEDURE emp2sal (a IN NUMBER)
AS
BEGIN
SELECT salary
INTO c
FROM Employees
WHERE Employee_id = a;
EXCEPTION
END emp2sal;
AS
BEGIN
SELECT Round(Months_between(sysdate,hire_date)/12)
INTO c
FROM Employees
WHERE Employee_id = a;
END emp2exep;
RETURN NUMBER
AS
BEGIN
c := a+b;
RETURN C;
END;
End all_detail;
IS
END global_constant;
BEGIN
END;
DECLARE
PROCEDURE P3;
PROCEDURE P1 IS
BEGIN
p2;
END P1;
PROCEDURE P2 IS
BEGIN
END P2;
PROCEDURE P3 IS
BEGIN
END P3;
BEGIN
p1;
END;
sample output:
From procedure p1
From procedure p2
From procedure p3
What is package?
Advantage of package
0 Add a comment
OCT
p_id NUMBER(3),
p_nm VARCHAR2(30),
p_qty NUMBER(8),
order_dt DATE
);
BEGIN
commit;
END;
------------------------------------
P_ID P_NM P_QTY ORDER_DT
------------------------------------
------------------------------------
DECLARE
v_name VARCHAR2(4);
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
DECLARE
v_name VARCHAR2(5);
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
VALUES
(106,
'name6',
700,
'26-Dec-12');
commit;
106 name6 700 12/26/2012
DECLARE
v_name VARCHAR2(5);
BEGIN
FROM product_details
--error
END;
DECLARE
v_name product_details.p_nm%TYPE;
BEGIN
SELECT p_nm
INTO v_name
FROM 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;
END;
--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
END;
dept_id number(3) ,
dept_name varchar2(30),
dept_manager_name varchar2(30)
);
-------------------------------------------------------
| 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
END;
/
1 Row(s) get updated
---------------------------------------------------
---------------------------------------------------
| 20 | dept2 | manager_name2 |
---------------------------------------------------
Interview Question :
0 Add a comment
SEP
29
BULK Exceptions
/************************************************************************
* Reference : http://www.dba-oracle.com/plsql/t_plsql_exceptions.htm *
************************************************************************/
DECLARE
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
commit;
END;
COUNT(*)
-------
200
DECLARE
BEGIN
FOR i in 1..200
LOOP
v_dat.EXTEND;
v_dat(v_dat.LAST) := i;
END LOOP;
v_dat(100) := NULL;
FORALL i IN v_dat.FIRST..v_dat.LAST
commit;
END;
/*
Error Message :
ORA-06512: at line 15
*/
sample2.sql --with exception part
DECLARE
BEGIN
FOR i in 1..200
LOOP
v_dat.EXTEND;
v_dat(v_dat.LAST) := i;
END LOOP;
v_dat(100) := NULL;
BEGIN
FORALL i IN v_dat.FIRST..v_dat.LAST
COMMIT;
EXCEPTION
END;
END;
COUNT(*)
-------
99
SQL%BULK_EXCEPTIONS(i).ERROR_INDEX
Holds the iteration (not the subscript) of the original FORALL statement that raised the
exception.
the exception row must be found by looping through the original collection the correct
number of times.
SQL%BULK_EXCEPTIONS(i).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,
DECLARE
v_ex_count NUMBER(4);
abort_ex EXCEPTION;
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;
COMMIT;
EXCEPTION
v_ex_count := SQL%BULK_EXCEPTIONS.COUNT;
END LOOP;
END;
END;
/*
Sample output:
*/
SELECT COUNT(*) FROM bulk_tb;
COUNT(*)
-------
198
SAVE EXCEPTIONS clause being removed, in the above script now traps a different error number.
/*
Sample output:
*/
COUNT(*)
-------
99
SELECT COUNT(*) FROM bulk_tb;
0 Add a comment
SEP
29
/************************************************************************
************************************************************************/
END LOOP;
commit;
END;
DECLARE
CURSOR PROD_DTLS_C IS
V_PID PROD_DETAILS.P_ID%TYPE;
V_PRDNAME PROD_DETAILS.P_NAME%TYPE;
BEGIN
OPEN PROD_DTLS_C;
LOOP
EXIT;
ELSE
UPDATE PROD_DETAILS P
END IF;
END LOOP;
CLOSE PROD_DTLS_C;
COMMIT;
END;
BEGIN
commit;
END;
DECLARE
CURSOR PROD_DTLS_C IS
V_PID PROD_DETAILS.P_ID%TYPE;
V_PRDNAME PROD_DETAILS.P_NAME%TYPE;
BEGIN
OPEN PROD_DTLS_C;
LOOP
IF PROD_DTLS_C%NOTFOUND THEN
EXIT;
ELSE
UPDATE PROD_DETAILS P
SET P.P_ID = LPAD(P_ID, 10, 0)
END IF;
COMMIT;
END LOOP;
CLOSE PROD_DTLS_C;
--COMMIT;
END;
0 Add a comment
MAY
28
FROM Dual;
FROM Dual;
SAL_DETAILS
---------------------------------------
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
------------------------------------
The '_' wild card character is used to match exactly one character
WITH mail_ids AS
UNION
UNION
SELECT 'an%murugappan@gmail.com' mail FROM Dual
----------------------------------
an_murugappan@gmail.com
WITH mail_ids AS
UNION
UNION
----------------------------------
an%murugappan@gmail.com
Escape ampersand (&) characters in SQL*Plus
'23'
----
23
'&A'
----
&a
'&A'
----
&a
SQL> SET SCAN ON;
'45'
----
45
0 Add a comment
MAY
28
Data Manipulation Language (DML) statements are used for managing data within schema
objects. Some examples:
DELETE - deletes all records from a table, the space for the records remain
prod_id NUMBER(4) ,
prod_name VARCHAR2(30) ,
comments VARCHAR2(300)
);
no_data_found
INSERT
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
VALUES(103,'Moto X','11-May-14','13-May-14');
VALUES(103,'Moto X','11-May-14','13-May-14');
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--If you want to insert NULL value you can ignore that column at the time of inserting
VALUES(104,'Moto G','19-May-14','22-May-14',NULL);
---------------------------------------------------------------------------
PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS
---------------------------------------------------------------------------
---------------------------------------------------------------------------
--if you are not providing values for order_dt and deliver_dt column default value can be taken.
---------------------------------------------------------------------------
----------------------------------------------------------------------------
---------------------------------------------------------------------------
--Inserting data by using sub query
COUNT(*)
-------
WHERE id = 900;
SELECT COUNT(*) FROM ins_chk;
COUNT(*)
-------
COUNT(*)
-------
Syntax :
UPDATE table_name
column2_name = column2_value,
column2_name = column3_value,
columnn_name = columnn_value
WHERE condition(s);
---------------------------------------------------------------------------
----------------------------------------------------------------------
---------------------------------------------------------------------------
UPDATE prod_details ps
SELECT *
FROM prod_details ps
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--If you try to execute update statement without condition it'll update all the records inside the
table.
UPDATE prod_details ps
---------------------------------------------------------------------------
---------------------------------------------------------------------------
----------------------------------------------------------------------
--if your update text contain ' means you can use following metnod (use '')
UPDATE prod_details ps
SELECT *
FROM prod_details ps
WHERE ps.prod_id = 100;
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
DELETE
Syntax:
WHERE condition(s);
SELECT *
---------------------------------------------------------------------------------------
100 Apple iphone 5s 5/21/2014 5/24/2014 Some product's are not available
---------------------------------------------------------------------------------------
no rows selected.
MAY
28
Data Definition Language (DDL) statements are used to define the database structure or schema.
Some examples:
ADD
RENAME
MODIFY
DROP
--------------------------------------------------------------------------
--------------------------------------------------------------------------
S: -84 to 127
VARCHAR2 4000 Bytes we can store 0-9, a-z, A-Z and special characters
--------------------------------------------------------------------------
CREATE
RENAME
DROP
TRUNCATE
--creating table
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
ADD : Used to add a column after the table hase been created
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)
-----------------------------
SYNTAX
ADD (
column_1 Data_type(size),
column_2 Data_type(size),
column_3 Data_type(size),
column_4 Data_type(size)
);
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.
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)
-----------------------------
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.
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)
-----------------------------
SYNTAX
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
DROP : Used to drop the tabel (Data + stucture of the table get removed from the database )
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
Posted 28th May 2014 by Unknown
0 Add a comment
MAY
28
Statements in Oracle
DDL statements are used to define the database structure or schema. Some examples:
ADD
RENAME
MODIFY
DROP
DELETE - deletes all records from a table, the space for the records remain
TCL statements are used to manage the changes made by DML statements. It allows
statements to be grouped together into logical transactions.
SAVEPOINT - identify a point in a transaction to which you can later roll back
0 Add a comment
MAY
19
roll_no NUMBER(4) ,
Name VARCHAR2(30) ,
dept_cd VARCHAR2(20) ,
total_marks NUMBER(3)
);
BEGIN
END;
/
DECODE
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',
'IT',
'Information Technology',
FROM students;
Sample Output
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
CASE
Example
SELECT roll_no,
NAME,
dept_cd,
total_marks,
CASE
'A Grade'
'B Grade'
WHEN total_marks > 300 THEN
'C Grade'
ELSE
'U Grade'
END AS "GRADE"
FROM students;
-----------------------------------------------
-----------------------------------------------
-----------------------------------------------
Interview Questions:
What is DECODE?
What is CASE?
MAY
19
Sub Query
Want to fetch the person Who are all getting salary more than Neena's salary ?
From Employees
Sub Query :
From Employees
);
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
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)
From Employees
);
From Employees
);
From Employees
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
FROM
Dual;
(
Select * from Employees
Where Department_id = 60
);
SELECT AVG(salary)
FROM employees
);
0 Add a comment
Loading
search
JUL
20
--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
Display all the customer who have placed more number of orders by using INLINE view
( custm_id NUMBER ,
custm_nm VARCHAR2(30) ,
ttl_amt NUMBER(7,2)
);
BEGIN
COMMIT;
END;
SELECT c.*
FROM customer_order_det_tb c;
--------------------------------------------
--------------------------------------------
--------------------------------------------
--Writing a Quer to display all the customer who have placed maximum number of order
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
--------------------------------
100 Murugappan 2
102 Ramesh 2
101 Raja 1
--------------------------------
----------
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;
****************************************/
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
) query1,
) query2
-------------------------------
-------------------------------
100 Murugappan 2
102 Ramesh 2
-------------------------------
FROM employees e
Example :
--in 11g
SELECT *
FROM departments d
--in 12c
SELECT *
FROM departments d
);
--in 11g
WITH t
AS
( SELECT LEVEL a
FROM dual
SELECT *
FROM t, (SELECT *
FROM employees
);
WITH t
AS
SELECT * FROM t,
LATERAL(SELECT *
FROM employees
0 Add a comment
JAN
23
--creating table
CREATE TABLE employee_data
eid NUMBER(4),
ename VARCHAR2(30),
depno NUMBER(3),
salary NUMBER(8)
);
BEGIN
--Inserting records
COMMIT;
END;
/
SELECT MAX(salary)
FROM employee_data
FROM employee_data);
SELECT MIN(salary)
FROM employee_data
SELECT MIN(salary)
FROM employee_data
--query to select all the details of the employee whose getting nth maximum salary
SELECT *
rownum rn
FROM (SELECT *
FROM employee_data
WHERE rn = 9;
--same query using row_numbr( ) function
SELECT *
WHERE rank = 9;
SELECT *
WHERE rank = 4;
SELECT *
WHERE rank = 4;
--query to display display maximum salary in all the department
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
--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
SELECT employee_id,
first_name,
salary
FROM employees
7 View comments
JAN
22
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.
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.
Elapsed: 00:00:14.01
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.
0 Add a comment
DEC
21
Constraints
Format : [part_of_project_name-table_name-column_name-constraint_type]
Format : sys_cn
Example : SYS_C405323
Types
Primary Key
Ex : Employee_id, Student_id
Unique Key
Ex : Contact_no, email
Foreign Key
c1(pk) : 1 2 3
Not Null
Check
------------------------------------
Duplicate NULL
------------------------------------
Primary Key X X
------------------------------------
S_id Number(2),
s_mail Varchar2(30),
s_gender char(1),
s_did Number(3),
);
DESC my_stu_details;
------------------------------------
------------------------------------
S_ID NUMBER(2)
S_NAME VARCHAR2(30)
S_MAIL VARCHAR2(30) Y
S_GENDER CHAR(1) Y
S_DID NUMBER(3) Y
------------------------------------
--Duplicate Check
--Null Check
Insert into 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
--------------------------------------------------------
------------------------------------------------------------
-------------------------------------------------
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
-------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
SELECT c.owner,
c.constraint_name,
c.constraint_type,
c.table_name,
c.r_constraint_name,
c.status
FROM user_constraints c
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
HR SYS_C004023 C MY_STU_DETAILS ENABLED
------------------------------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
Creating Composite Primary Key
In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.
Interview Questions
Which Data Dictionary table contains information about constraint with corresponding column
name?
1 View comments
good
Reply
DEC
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 :
--Example 1:
BEGIN
commit;
END;
listagg(product,
',') within
FROM test_ins
GROUP BY empid;
-->-- Example 2
FROM employees
GROUP BY department_id;
0 Add a comment
NOV
8
Condition and Looping Statement
IF
IF ELSE
Multiple IF ELSE
LOOP
FOR LOOP
WHILE LOOP
BEGIN
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;
UPDATE test_udt t
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;
UPDATE test_udt t
ELSE
UPDATE test_udt t
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;
v_salary := v_salary+10005;
ELSE
v_salary := v_salary+20007;
END IF;
UPDATE test_udt t
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');
v_salary := 2000;
dbms_output.put_line('2 inside');
v_salary := 3000;
dbms_output.put_line('3 inside');
v_salary := 4000;
dbms_output.put_line('4 inside');
END IF;
UPDATE test_udt t
commit;
END;
LOOP
--syntax
LOOP
--statements
--increment
--exit statement
END LOOP;
i NUMBER := 1;
x VARCHAR2(3);
BEGIN
LOOP
x := lpad(i,3,'0');
i := i+1;
IF MOD(i,100) = 0 THEN
commit;
dbms_output.put_line('commit executed');
END IF;
END LOOP;
END;
FOR LOOP
BEGIN
FOR I in 1..5
LOOP
END LOOP;
END;
BEGIN
LOOP
END LOOP;
END;
WHILE LOOP
DECLARE
i_val NUMBER:=0;
BEGIN
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
0 Add a comment
OCT
21
Bulk Collect
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.
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
SELECT * FROM product_details;
BEGIN
OPEN proddt_cur;
INTO dta;
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta alldata_typ;
BEGIN
END LOOP;
END;
-->-- LIMIT in Bulk collect --<--
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta1 alldata_typ1;
dta2 alldata_typ2;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END LOOP;
END;
/
0 Add a comment
OCT
21
Ref Cursor
This is unconstrained cursor which will return different types depends upon the user input.
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.
AS
BEGIN
OPEN dep_det_c
FOR
END;
DECLARE
dep_det_c SYS_REFCURSOR;
tab_data dep_details%ROWTYPE;
BEGIN
ref_c_sp(dep_det_c);
LOOP
END LOOP;
CLOSE dep_det_c;
END;
/*sample output*/
Department Name : Admin
Department Name : HR
0 Add a comment
OCT
21
Cursor
SQL Private work Area where the query get passed and executed.
Types
******
Implicit(SQL)
Explicit
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
Cursor Stages
**************
OPEN cursor_name
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
Cursor Declaration
DECLARE
CURSOR <cursor_name>
IS
<SELECT statement>
BEGIN
END;
Cursor Loop
Loop
While Loop
For Loop
Cursor Clauses
Return
For update
Where current of
Bulk collect
p_id NUMBER,
p_name VARCHAR2(30),
p_order_dt DATE
);
BEGIN
FOR i IN 1 .. 75 LOOP
END LOOP;
commit;
END;
---------------------------------------------
---------------------------------------------
---------------------------------------------
----------------------------------------------
Implicit Cursor
----------------------------------------------
----------------------------------------------
Explicit Cursor
----------------------------------------------
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
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
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
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*/
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
dbms_output.put_line('prod_detail_cur cursor Already closed');
END IF;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
FETCH prod_detail_cur
INTO all_data;
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
************************************************************
************************************************************
DECLARE
--cursor declaration
CURSOR prod_detail_cur IS
FOR i IN prod_detail_cur
LOOP
END LOOP;
END;
/*sample output*/
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.
BEGIN
commit;
END;
----------------------------
----------------------------
1 Admin 1010
2 HR 1010
3 Sales 1020
4 Marketing 1020
----------------------------
DECLARE
all_data dep_details%ROWTYPE;
BEGIN
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1010);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1020);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
END;
/*sample output*/
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
0 Add a comment
OCT
21
Handling Exception
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
Predefined Exception
*********************
Oracle has predefined several exceptions that correspond to the most common oracle errors.
------------------------------------------------------------------------
------------------------------------------------------------------------
DUP_VAL_ON_INDEX ORA-00001 -1
OTHERS
------------------------------------------------------------------------
v_result NUMBER;
BEGIN
EXCEPTION
END;
Single row SELECT returned no rows or your program referenced a deleted element in a nested
table
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
commit;
BEGIN
EXCEPTION
END;
v_id NUMBER;
BEGIN
EXCEPTION
END;
DECLARE
num1 NUMBER(2);
BEGIN
num1 := 345;
EXCEPTION
END;
-->-- CURSOR_ALREADY_OPEN --<--
BEGIN
COMMIT;
END;
DECLARE
cursor emp_c IS
all_data emp%ROWTYPE;
BEGIN
OPEN emp_c;
OPEN emp_c;
NULL;
CLOSE emp_c;
EXCEPTION
END;
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
User Defined Exception
**********************
User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,
DECLARE
gender_ex EXCEPTION;
BEGIN
RAISE gender_ex;
END IF;
dbms_output.put_line('Gender : '||v_gender);
EXCEPTION
END;
abort_ex EXCEPTION;
BEGIN
FOR i IN 1..100
LOOP
BEGIN
IF mod(i,10)=0 THEN
RAISE abort_ex;
END IF;
EXCEPTION
NULL;
END;
END LOOP;
COMMIT;
END;
********************
SQLCODE returns the current error code, and SQLERRM returns the current error message
text;
SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.
DECLARE
v_id NUMBER;
BEGIN
dbms_output.put_line(v_id);
EXCEPTION
END;
/*sample output*/
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:
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
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 :
DECLARE
BEGIN
END IF;
END;
How to get the two table data without using Joins and sub query,union?
Reply
OCT
Package
I) specification
II) Body
5. Overloading
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_sal_sp;
BEGIN
END;
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
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_hdt_sp;
BEGIN
END;
RETURN NUMBER
IS
v_c NUMBER;
BEGIN
v_c := p_a + p_b;
RETURN v_c;
END;
--Specification Part
IS
RETURN NUMBER;
END emp_pkg ;
--Body Part
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
EXCEPTION
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_hdt_sp;
IS
v_c NUMBER;
BEGIN
RETURN v_c;
END;
END emp_pkg;
BEGIN
emp_pkg.emp_sal_sp(120);
END;
as
RETURN NUMBER;
IS
FROM employees;
End all_detail;
as
PROCEDURE emp2sal (a IN NUMBER)
AS
BEGIN
SELECT salary
INTO c
FROM Employees
WHERE Employee_id = a;
EXCEPTION
END emp2sal;
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
END emp2exep;
RETURN NUMBER
AS
BEGIN
c := a+b;
RETURN C;
END;
End all_detail;
IS
END global_constant;
BEGIN
END;
DECLARE
PROCEDURE P3;
PROCEDURE P1 IS
BEGIN
p2;
END P1;
PROCEDURE P2 IS
BEGIN
dbms_output.put_line('From procedure p2');
p3;
END P2;
PROCEDURE P3 IS
BEGIN
END P3;
BEGIN
p1;
END;
sample output:
From procedure p1
From procedure p2
From procedure p3
Interview Questions:
What is package?
Advantage of package
0 Add a comment
OCT
p_id NUMBER(3),
p_nm VARCHAR2(30),
p_qty NUMBER(8),
order_dt DATE
);
BEGIN
commit;
END;
------------------------------------
------------------------------------
DECLARE
v_name VARCHAR2(4);
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
DECLARE
v_name VARCHAR2(5);
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
VALUES
(106,
'name6',
700,
'26-Dec-12');
commit;
106 name6 700 12/26/2012
DECLARE
v_name VARCHAR2(5);
BEGIN
FROM product_details
--error
END;
DECLARE
v_name product_details.p_nm%TYPE;
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
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
END;
--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
END;
dept_id number(3) ,
dept_name varchar2(30),
dept_manager_name varchar2(30)
);
+------------+-----------------------+-----------------
| 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
END;
/
1 Row(s) get updated
---------------------------------------------------
---------------------------------------------------
| 20 | dept2 | manager_name2 |
---------------------------------------------------
Interview Question :
0 Add a comment
SEP
29
BULK Exceptions
/************************************************************************
* Reference : http://www.dba-oracle.com/plsql/t_plsql_exceptions.htm *
************************************************************************/
DECLARE
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
commit;
END;
COUNT(*)
-------
200
BEGIN
FOR i in 1..200
LOOP
v_dat.EXTEND;
v_dat(v_dat.LAST) := i;
END LOOP;
v_dat(100) := NULL;
FORALL i IN v_dat.FIRST..v_dat.LAST
commit;
END;
/*
Error Message :
ORA-06512: at line 15
*/
sample2.sql --with exception part
DECLARE
BEGIN
FOR i in 1..200
LOOP
v_dat.EXTEND;
v_dat(v_dat.LAST) := i;
END LOOP;
v_dat(100) := NULL;
BEGIN
FORALL i IN v_dat.FIRST..v_dat.LAST
COMMIT;
EXCEPTION
END;
END;
COUNT(*)
-------
99
SQL%BULK_EXCEPTIONS(i).ERROR_INDEX
Holds the iteration (not the subscript) of the original FORALL statement that raised the
exception.
the exception row must be found by looping through the original collection the correct
number of times.
SQL%BULK_EXCEPTIONS(i).ERROR_CODE
DECLARE
v_ex_count NUMBER(4);
abort_ex EXCEPTION;
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;
BEGIN
COMMIT;
EXCEPTION
v_ex_count := SQL%BULK_EXCEPTIONS.COUNT;
END LOOP;
END;
END;
/*
Sample output:
*/
SELECT COUNT(*) FROM bulk_tb;
COUNT(*)
-------
198
SAVE EXCEPTIONS clause being removed, in the above script now traps a different error number.
/*
Sample output:
*/
COUNT(*)
-------
99
0 Add a comment
SEP
29
/************************************************************************
************************************************************************/
END LOOP;
commit;
END;
DECLARE
CURSOR PROD_DTLS_C IS
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
END IF;
END LOOP;
CLOSE PROD_DTLS_C;
COMMIT;
END;
BEGIN
END LOOP;
commit;
END;
DECLARE
CURSOR PROD_DTLS_C IS
V_PID PROD_DETAILS.P_ID%TYPE;
V_PRDNAME PROD_DETAILS.P_NAME%TYPE;
BEGIN
OPEN PROD_DTLS_C;
LOOP
IF PROD_DTLS_C%NOTFOUND THEN
EXIT;
ELSE
UPDATE PROD_DETAILS P
END IF;
COMMIT;
END LOOP;
CLOSE PROD_DTLS_C;
--COMMIT;
END;
0 Add a comment
MAY
28
FROM Dual;
FROM Dual;
SAL_DETAILS
---------------------------------------
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
------------------------------------
The '_' wild card character is used to match exactly one character
WITH mail_ids AS
UNION
UNION
SELECT 'an%murugappan@gmail.com' mail FROM Dual
----------------------------------
an_murugappan@gmail.com
WITH mail_ids AS
UNION
UNION
----------------------------------
an%murugappan@gmail.com
Escape ampersand (&) characters in SQL*Plus
'23'
----
23
'&A'
----
&a
'&A'
----
&a
SQL> SET SCAN ON;
'45'
----
45
0 Add a comment
MAY
28
Data Manipulation Language (DML) statements are used for managing data within schema
objects. Some examples:
DELETE - deletes all records from a table, the space for the records remain
prod_id NUMBER(4) ,
prod_name VARCHAR2(30) ,
comments VARCHAR2(300)
);
no_data_found
INSERT
---------------------------------------------------------------------------
---------------------------------------------------------------------------
100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
VALUES(103,'Moto X','11-May-14','13-May-14');
VALUES(103,'Moto X','11-May-14','13-May-14');
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--If you want to insert NULL value you can ignore that column at the time of inserting
VALUES(104,'Moto G','19-May-14','22-May-14',NULL);
---------------------------------------------------------------------------
---------------------------------------------------------------------------
--if you are not providing values for order_dt and deliver_dt column default value can be taken.
---------------------------------------------------------------------------
----------------------------------------------------------------------------
COUNT(*)
-------
WHERE id = 900;
SELECT COUNT(*) FROM ins_chk;
COUNT(*)
-------
COUNT(*)
-------
UPDATE
Syntax :
UPDATE table_name
column2_name = column2_value,
column2_name = column3_value,
columnn_name = columnn_value
WHERE condition(s);
---------------------------------------------------------------------------
----------------------------------------------------------------------
UPDATE prod_details ps
SELECT *
FROM prod_details ps
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--If you try to execute update statement without condition it'll update all the records inside the
table.
UPDATE prod_details ps
---------------------------------------------------------------------------
---------------------------------------------------------------------------
----------------------------------------------------------------------
--if your update text contain ' means you can use following metnod (use '')
UPDATE prod_details ps
SELECT *
FROM prod_details ps
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
DELETE
Syntax:
WHERE condition(s);
SELECT *
---------------------------------------------------------------------------------------
100 Apple iphone 5s 5/21/2014 5/24/2014 Some product's are not available
---------------------------------------------------------------------------------------
no rows selected.
0 Add a comment
MAY
28
Data Definition Language (DDL) statements are used to define the database structure or schema.
Some examples:
ADD
RENAME
MODIFY
DROP
--------------------------------------------------------------------------
--------------------------------------------------------------------------
S: -84 to 127
VARCHAR2 4000 Bytes we can store 0-9, a-z, A-Z and special characters
--------------------------------------------------------------------------
CREATE
RENAME
DROP
TRUNCATE
--creating table
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
ADD : Used to add a column after the table hase been created
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)
-----------------------------
SYNTAX
ADD (
column_1 Data_type(size),
column_2 Data_type(size),
column_3 Data_type(size),
column_4 Data_type(size)
);
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.
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)
-----------------------------
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.
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)
-----------------------------
SYNTAX
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
DROP : Used to drop the tabel (Data + stucture of the table get removed from the database )
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
Posted 28th May 2014 by Unknown
0 Add a comment
MAY
28
Statements in Oracle
DDL statements are used to define the database structure or schema. Some examples:
ADD
RENAME
MODIFY
DROP
DELETE - deletes all records from a table, the space for the records remain
TCL statements are used to manage the changes made by DML statements. It allows
statements to be grouped together into logical transactions.
SAVEPOINT - identify a point in a transaction to which you can later roll back
0 Add a comment
MAY
19
roll_no NUMBER(4) ,
Name VARCHAR2(30) ,
dept_cd VARCHAR2(20) ,
total_marks NUMBER(3)
);
BEGIN
END;
/
DECODE
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',
'IT',
'Information Technology',
FROM students;
Sample Output
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
CASE
Example
SELECT roll_no,
NAME,
dept_cd,
total_marks,
CASE
'A Grade'
'B Grade'
WHEN total_marks > 300 THEN
'C Grade'
ELSE
'U Grade'
END AS "GRADE"
FROM students;
-----------------------------------------------
-----------------------------------------------
-----------------------------------------------
Interview Questions:
What is DECODE?
What is CASE?
MAY
19
Sub Query
Want to fetch the person Who are all getting salary more than Neena's salary ?
From Employees
Sub Query :
From Employees
);
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 :
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
);
From Employees
);
From Employees
);
From Employees
);
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
FROM
Dual;
);
SELECT AVG(salary)
FROM employees
);
0 Add a comment
Loading
search
JUL
20
--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
, AVG(b.salary) avg_sal
FROM employees b
GROUP BY b.department_id
)b
Display all the customer who have placed more number of orders by using INLINE view
( custm_id NUMBER ,
custm_nm VARCHAR2(30) ,
ttl_amt NUMBER(7,2)
);
BEGIN
COMMIT;
END;
SELECT c.*
FROM customer_order_det_tb c;
--------------------------------------------
--------------------------------------------
--------------------------------------------
--Writing a Quer to display all the customer who have placed maximum number of order
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
--------------------------------
100 Murugappan 2
102 Ramesh 2
101 Raja 1
--------------------------------
----------
total_odr
----------
----------
Inline view to find all the customers who have placed maximum number of orders
/****************************************
Syntax
WHERE contition;
****************************************/
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
) query1,
) query2
-------------------------------
-------------------------------
100 Murugappan 2
102 Ramesh 2
-------------------------------
--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 employees e
Example :
--in 11g
SELECT *
FROM departments d
SELECT *
FROM departments d
);
--in 11g
WITH t
AS
( SELECT LEVEL a
FROM dual
SELECT *
FROM t, (SELECT *
FROM employees
);
--in 12c
WITH t
AS
SELECT * FROM t,
LATERAL(SELECT *
FROM employees
0 Add a comment
JAN
23
--creating table
eid NUMBER(4),
ename VARCHAR2(30),
depno NUMBER(3),
salary NUMBER(8)
);
BEGIN
--Inserting records
COMMIT;
END;
/
SELECT * FROM employee_data
SELECT MAX(salary)
FROM employee_data
FROM employee_data);
SELECT MIN(salary)
FROM employee_data
ORDER BY salary DESC)
SELECT MIN(salary)
FROM employee_data
--query to select all the details of the employee whose getting nth maximum salary
SELECT *
rownum rn
FROM (SELECT *
FROM employee_data
WHERE rn = 9;
WHERE rank = 9;
SELECT *
WHERE rank = 4;
SELECT *
WHERE rank = 4;
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
--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
--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,
first_name,
salary
FROM employees
7 View comments
JAN
22
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.
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.
14 rows selected.
Elapsed: 00:00:14.01
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.
0 Add a comment
DEC
21
Constraints
Format : [part_of_project_name-table_name-column_name-constraint_type]
Format : sys_cn
Example : SYS_C405323
Types
Primary Key
Ex : Employee_id, Student_id
Unique Key
allowed Null value
Ex : Contact_no, email
Foreign Key
c1(pk) : 1 2 3
Not Null
Check
Duplicate NULL
------------------------------------
Primary Key X X
------------------------------------
S_id Number(2),
s_mail Varchar2(30),
s_gender char(1),
s_did Number(3),
);
DESC my_stu_details;
------------------------------------
------------------------------------
S_ID NUMBER(2)
S_NAME VARCHAR2(30)
S_MAIL VARCHAR2(30) Y
S_GENDER CHAR(1) Y
S_DID NUMBER(3) Y
------------------------------------
--Duplicate Check
--Null Check
--------------------------------------------------------
--------------------------------------------------------
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
--------------------------------------------------------
------------------------------------------------------------
-------------------------------------------------
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
-------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
ON DELETE CASCADE
Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)
SELECT c.owner,
c.constraint_name,
c.constraint_type,
c.table_name,
c.r_constraint_name,
c.status
FROM user_constraints c
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.
Interview Questions
Which Data Dictionary table contains information about constraint with corresponding column
name?
1 View comments
good
Reply
DEC
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 :
--Example 1:
BEGIN
commit;
END;
listagg(product,
',') within
FROM test_ins
GROUP BY empid;
-->-- Example 2
FROM employees
GROUP BY department_id;
0 Add a comment
NOV
IF ELSE
Multiple IF ELSE
LOOP
FOR LOOP
WHILE LOOP
BEGIN
Commit;
END;
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 1;
UPDATE test_udt t
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;
UPDATE test_udt t
ELSE
UPDATE test_udt t
END IF;
commit;
END;
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 2;
v_salary := v_salary+10005;
ELSE
v_salary := v_salary+20007;
END IF;
UPDATE test_udt t
commit;
END;
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');
v_salary := 2000;
dbms_output.put_line('2 inside');
v_salary := 3000;
dbms_output.put_line('3 inside');
v_salary := 4000;
dbms_output.put_line('4 inside');
END IF;
UPDATE test_udt t
commit;
END;
LOOP
--syntax
LOOP
--statements
--increment
--exit statement
END LOOP;
DECLARE
i NUMBER := 1;
x VARCHAR2(3);
BEGIN
LOOP
x := lpad(i,3,'0');
i := i+1;
IF MOD(i,100) = 0 THEN
commit;
dbms_output.put_line('commit executed');
END IF;
END LOOP;
END;
FOR LOOP
BEGIN
FOR I in 1..5
LOOP
END LOOP;
END;
BEGIN
LOOP
END LOOP;
END;
WHILE LOOP
DECLARE
i_val NUMBER:=0;
BEGIN
LOOP
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
0 Add a comment
OCT
21
Bulk Collect
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.
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
INTO dta;
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta alldata_typ;
BEGIN
END LOOP;
END;
-->-- LIMIT in Bulk collect --<--
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END;
dta1 alldata_typ1;
dta2 alldata_typ2;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END LOOP;
END;
/
DROP TABLE dep_details;
0 Add a comment
OCT
21
Ref Cursor
This is unconstrained cursor which will return different types depends upon the user input.
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.
AS
BEGIN
OPEN dep_det_c
FOR
END;
DECLARE
dep_det_c SYS_REFCURSOR;
tab_data dep_details%ROWTYPE;
BEGIN
ref_c_sp(dep_det_c);
LOOP
END LOOP;
CLOSE dep_det_c;
END;
/*sample output*/
Department Name : HR
Department Name : Sales
0 Add a comment
OCT
21
Cursor
SQL Private work Area where the query get passed and executed.
Types
******
Implicit(SQL)
Explicit
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
Cursor Stages
**************
OPEN cursor_name
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
Cursor Declaration
DECLARE
CURSOR <cursor_name>
IS
<SELECT statement>
BEGIN
END;
Cursor Loop
Loop
While Loop
For Loop
Cursor Clauses
Return
For update
Where current of
Bulk collect
p_id NUMBER,
p_name VARCHAR2(30),
p_order_dt DATE
);
BEGIN
FOR i IN 1 .. 75 LOOP
END LOOP;
commit;
END;
-->-- selecting data
---------------------------------------------
---------------------------------------------
---------------------------------------------
----------------------------------------------
Implicit Cursor
----------------------------------------------
----------------------------------------------
Explicit Cursor
----------------------------------------------
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
SELECT * FROM product_details
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
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
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*/
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
FETCH prod_detail_cur
INTO all_data;
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
************************************************************
************************************************************
DECLARE
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
FOR i IN prod_detail_cur
LOOP
END LOOP;
END;
/*sample output*/
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.
BEGIN
commit;
END;
----------------------------
----------------------------
1 Admin 1010
2 HR 1010
3 Sales 1020
4 Marketing 1020
----------------------------
DECLARE
all_data dep_details%ROWTYPE;
BEGIN
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1010);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1020);
LOOP
FETCH dep_det_c
INTO all_data;
EXIT WHEN dep_det_c%NOTFOUND;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
END;
/*sample output*/
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
0 Add a comment
OCT
21
Handling Exception
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
*********************
Oracle has predefined several exceptions that correspond to the most common oracle errors.
------------------------------------------------------------------------
------------------------------------------------------------------------
DUP_VAL_ON_INDEX ORA-00001 -1
OTHERS
------------------------------------------------------------------------
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
Single row SELECT returned no rows or your program referenced a deleted element in a nested
table
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
-->-- DUP_VAL_ON_INDEX --<--
commit;
BEGIN
EXCEPTION
END;
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
DECLARE
num1 NUMBER(2);
BEGIN
num1 := 345;
EXCEPTION
END;
BEGIN
COMMIT;
END;
DECLARE
cursor emp_c IS
all_data emp%ROWTYPE;
BEGIN
OPEN emp_c;
OPEN emp_c;
NULL;
CLOSE emp_c;
EXCEPTION
END;
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
**********************
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,
DECLARE
gender_ex EXCEPTION;
BEGIN
RAISE gender_ex;
END IF;
dbms_output.put_line('Gender : '||v_gender);
EXCEPTION
END;
DECLARE
abort_ex EXCEPTION;
BEGIN
FOR i IN 1..100
LOOP
BEGIN
IF mod(i,10)=0 THEN
RAISE abort_ex;
END IF;
EXCEPTION
NULL;
END;
END LOOP;
COMMIT;
END;
********************
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.
DECLARE
v_id NUMBER;
BEGIN
dbms_output.put_line(v_id);
EXCEPTION
END;
/*sample output*/
SQLCODE : 100
*********************
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:
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
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 :
DECLARE
BEGIN
END IF;
END;
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
I) specification
II) Body
5. Overloading
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_sal_sp;
BEGIN
END;
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_hdt_sp;
BEGIN
END;
RETURN NUMBER
IS
v_c NUMBER;
BEGIN
RETURN v_c;
END;
--Specification Part
IS
RETURN NUMBER;
END emp_pkg ;
--Body Part
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_sal_sp;
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_hdt_sp;
RETURN NUMBER
IS
v_c NUMBER;
BEGIN
RETURN v_c;
END;
END emp_pkg;
BEGIN
emp_pkg.emp_sal_sp(120);
END;
as
RETURN NUMBER;
IS
FROM employees;
End all_detail;
as
BEGIN
SELECT salary
INTO c
FROM Employees
WHERE Employee_id = a;
EXCEPTION
END emp2sal;
AS
BEGIN
SELECT Round(Months_between(sysdate,hire_date)/12)
INTO c
FROM Employees
WHERE Employee_id = a;
EXCEPTION
WHEN no_data_found THEN
END emp2exep;
RETURN NUMBER
AS
BEGIN
c := a+b;
RETURN C;
END;
End all_detail;
IS
END global_constant;
BEGIN
END;
DECLARE
PROCEDURE P3;
PROCEDURE P1 IS
BEGIN
p2;
END P1;
PROCEDURE P2 IS
BEGIN
p3;
END P2;
PROCEDURE P3 IS
BEGIN
END P3;
BEGIN
p1;
END;
sample output:
From procedure p1
From procedure p2
From procedure p3
What is package?
Advantage of package
0 Add a comment
OCT
p_id NUMBER(3),
p_nm VARCHAR2(30),
p_qty NUMBER(8),
order_dt DATE
);
BEGIN
commit;
END;
------------------------------------
------------------------------------
DECLARE
v_name VARCHAR2(4);
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
DECLARE
v_name VARCHAR2(5);
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
VALUES
(106,
'name6',
700,
'26-Dec-12');
commit;
v_name VARCHAR2(5);
BEGIN
FROM product_details
--error
END;
DECLARE
v_name product_details.p_nm%TYPE;
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
/
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
END;
--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
END;
dept_id number(3) ,
dept_name varchar2(30),
dept_manager_name varchar2(30)
);
-------------------------------------------------------
| 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
END;
---------------------------------------------------
---------------------------------------------------
| 20 | dept2 | manager_name2 |
---------------------------------------------------
Interview Question :
0 Add a comment
SEP
29
BULK Exceptions
/************************************************************************
* Reference : http://www.dba-oracle.com/plsql/t_plsql_exceptions.htm *
************************************************************************/
DECLARE
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
commit;
END;
COUNT(*)
-------
200
DECLARE
TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;
BEGIN
FOR i in 1..200
LOOP
v_dat.EXTEND;
v_dat(v_dat.LAST) := i;
END LOOP;
v_dat(100) := NULL;
FORALL i IN v_dat.FIRST..v_dat.LAST
commit;
END;
/*
Error Message :
ORA-06512: at line 15
*/
sample2.sql --with exception part
DECLARE
BEGIN
FOR i in 1..200
LOOP
v_dat.EXTEND;
v_dat(v_dat.LAST) := i;
END LOOP;
v_dat(100) := NULL;
BEGIN
FORALL i IN v_dat.FIRST..v_dat.LAST
COMMIT;
EXCEPTION
END;
COUNT(*)
-------
99
SQL%BULK_EXCEPTIONS(i).ERROR_INDEX
Holds the iteration (not the subscript) of the original FORALL statement that raised the
exception.
the exception row must be found by looping through the original collection the correct
number of times.
SQL%BULK_EXCEPTIONS(i).ERROR_CODE
DECLARE
v_ex_count NUMBER(4);
abort_ex EXCEPTION;
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;
COMMIT;
EXCEPTION
v_ex_count := SQL%BULK_EXCEPTIONS.COUNT;
END LOOP;
END;
END;
/*
Sample output:
*/
SELECT COUNT(*) FROM bulk_tb;
COUNT(*)
-------
198
SAVE EXCEPTIONS clause being removed, in the above script now traps a different error number.
/*
Sample output:
*/
COUNT(*)
-------
99
SELECT COUNT(*) FROM bulk_tb;
0 Add a comment
SEP
29
/************************************************************************
************************************************************************/
END LOOP;
commit;
END;
DECLARE
CURSOR PROD_DTLS_C IS
V_PID PROD_DETAILS.P_ID%TYPE;
V_PRDNAME PROD_DETAILS.P_NAME%TYPE;
BEGIN
OPEN PROD_DTLS_C;
LOOP
EXIT;
ELSE
UPDATE PROD_DETAILS P
END IF;
END LOOP;
CLOSE PROD_DTLS_C;
COMMIT;
END;
BEGIN
commit;
END;
DECLARE
CURSOR PROD_DTLS_C IS
V_PID PROD_DETAILS.P_ID%TYPE;
V_PRDNAME PROD_DETAILS.P_NAME%TYPE;
BEGIN
OPEN PROD_DTLS_C;
LOOP
IF PROD_DTLS_C%NOTFOUND THEN
EXIT;
ELSE
UPDATE PROD_DETAILS P
SET P.P_ID = LPAD(P_ID, 10, 0)
END IF;
COMMIT;
END LOOP;
CLOSE PROD_DTLS_C;
--COMMIT;
END;
0 Add a comment
MAY
28
FROM Dual;
FROM Dual;
SAL_DETAILS
---------------------------------------
FROM Dual;
Info
---------------------------------------
FROM dual;
In 10g
------------------------------------
The '_' wild card character is used to match exactly one character
WITH mail_ids AS
UNION
UNION
----------------------------------
an_murugappan@gmail.com
WITH mail_ids AS
UNION
UNION
----------------------------------
an%murugappan@gmail.com
Escape ampersand (&) characters in SQL*Plus
'23'
----
23
'&A'
----
&a
'&A'
----
&a
'45'
----
45
0 Add a comment
MAY
28
Data Manipulation Language (DML) statements are used for managing data within schema
objects. Some examples:
DELETE - deletes all records from a table, the space for the records remain
prod_id NUMBER(4) ,
prod_name VARCHAR2(30) ,
comments VARCHAR2(300)
);
no_data_found
INSERT
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
VALUES(103,'Moto X','11-May-14','13-May-14');
VALUES(103,'Moto X','11-May-14','13-May-14');
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--If you want to insert NULL value you can ignore that column at the time of inserting
VALUES(104,'Moto G','19-May-14','22-May-14',NULL);
---------------------------------------------------------------------------
PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS
---------------------------------------------------------------------------
---------------------------------------------------------------------------
--if you are not providing values for order_dt and deliver_dt column default value can be taken.
---------------------------------------------------------------------------
----------------------------------------------------------------------------
---------------------------------------------------------------------------
--Inserting data by using sub query
COUNT(*)
-------
WHERE id = 900;
SELECT COUNT(*) FROM ins_chk;
COUNT(*)
-------
COUNT(*)
-------
Syntax :
UPDATE table_name
column2_name = column2_value,
column2_name = column3_value,
columnn_name = columnn_value
WHERE condition(s);
---------------------------------------------------------------------------
----------------------------------------------------------------------
---------------------------------------------------------------------------
UPDATE prod_details ps
SELECT *
FROM prod_details ps
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--If you try to execute update statement without condition it'll update all the records inside the
table.
UPDATE prod_details ps
---------------------------------------------------------------------------
---------------------------------------------------------------------------
----------------------------------------------------------------------
--if your update text contain ' means you can use following metnod (use '')
UPDATE prod_details ps
SELECT *
FROM prod_details ps
WHERE ps.prod_id = 100;
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
DELETE
Syntax:
WHERE condition(s);
SELECT *
---------------------------------------------------------------------------------------
100 Apple iphone 5s 5/21/2014 5/24/2014 Some product's are not available
---------------------------------------------------------------------------------------
no rows selected.
MAY
28
Data Definition Language (DDL) statements are used to define the database structure or schema.
Some examples:
ADD
RENAME
MODIFY
DROP
--------------------------------------------------------------------------
--------------------------------------------------------------------------
S: -84 to 127
VARCHAR2 4000 Bytes we can store 0-9, a-z, A-Z and special characters
--------------------------------------------------------------------------
CREATE
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)
-----------------------------
ADD : Used to add a column after the table hase been created
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
ADD (
column_1 Data_type(size),
column_2 Data_type(size),
column_3 Data_type(size),
column_4 Data_type(size)
);
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.
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)
-----------------------------
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.
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)
-----------------------------
SYNTAX
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
DROP : Used to drop the tabel (Data + stucture of the table get removed from the database )
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
MAY
28
Statements in Oracle
DDL statements are used to define the database structure or schema. Some examples:
ADD
RENAME
MODIFY
DROP
DML statements are used for managing data within schema objects. Some examples:
INSERT - insert data into a table
DELETE - deletes all records from a table, the space for the records remain
TCL statements are used to manage the changes made by DML statements. It allows
statements to be grouped together into logical transactions.
SAVEPOINT - identify a point in a transaction to which you can later roll back
0 Add a comment
MAY
19
roll_no NUMBER(4) ,
Name VARCHAR2(30) ,
dept_cd VARCHAR2(20) ,
total_marks NUMBER(3)
);
BEGIN
END;
/
SELECT * FROM students;
DECODE
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',
'IT',
'Information Technology',
FROM students;
Sample Output
------------------------------------------------------------
ROLL_NO NAME DEPT_CD DEPARTMENT NAME
------------------------------------------------------------
------------------------------------------------------------
CASE
Example
SELECT roll_no,
NAME,
dept_cd,
total_marks,
CASE
'A Grade'
'B Grade'
ELSE
'U Grade'
END AS "GRADE"
FROM students;
-----------------------------------------------
-----------------------------------------------
-----------------------------------------------
Interview Questions:
What is DECODE?
What is CASE?
MAY
19
Sub Query
Want to fetch the person Who are all getting salary more than Neena's salary ?
From Employees
Sub Query :
From Employees
);
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 :
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
);
From Employees
);
From Employees
);
From Employees
);
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
FROM
Dual;
Where Department_id = 60
);
SELECT AVG(salary)
FROM employees
);
0 Add a comment
Loading
search
JUL
20
--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
, AVG(b.salary) avg_sal
FROM employees b
GROUP BY b.department_id
)b
Display all the customer who have placed more number of orders by using INLINE view
( custm_id NUMBER ,
custm_nm VARCHAR2(30) ,
ttl_amt NUMBER(7,2)
);
BEGIN
COMMIT;
END;
SELECT c.*
FROM customer_order_det_tb c;
--------------------------------------------
--------------------------------------------
--------------------------------------------
--Writing a Quer to display all the customer who have placed maximum number of order
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
--------------------------------
--------------------------------
100 Murugappan 2
102 Ramesh 2
101 Raja 1
--------------------------------
----------
total_odr
----------
----------
Inline view to find all the customers who have placed maximum number of orders
/****************************************
Syntax
WHERE contition;
****************************************/
SELECT query1.* FROM
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
) query1,
) query2
-------------------------------
-------------------------------
100 Murugappan 2
102 Ramesh 2
-------------------------------
--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 employees e
Example :
--in 11g
SELECT *
FROM departments d
SELECT *
FROM departments d
);
--in 11g
WITH t
AS
( SELECT LEVEL a
FROM dual
SELECT *
FROM t, (SELECT *
FROM employees
);
--in 12c
WITH t
AS
SELECT * FROM t,
LATERAL(SELECT *
FROM employees
0 Add a comment
JAN
23
--creating table
(
eid NUMBER(4),
ename VARCHAR2(30),
depno NUMBER(3),
salary NUMBER(8)
);
BEGIN
--Inserting records
COMMIT;
END;
/
SELECT * FROM employee_data
SELECT MAX(salary)
FROM employee_data
FROM employee_data);
SELECT MIN(salary)
FROM employee_data
SELECT MIN(salary)
FROM employee_data
--query to select all the details of the employee whose getting nth maximum salary
SELECT *
rownum rn
FROM (SELECT *
FROM employee_data
WHERE rn = 9;
WHERE rank = 9;
SELECT *
WHERE rank = 4;
SELECT *
WHERE rank = 4;
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
--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
--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,
first_name,
salary
FROM employees
7 View comments
JAN
22
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.
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.
14 rows selected.
Elapsed: 00:00:14.01
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.
0 Add a comment
DEC
21
Constraints
Format : [part_of_project_name-table_name-column_name-constraint_type]
Format : sys_cn
Example : SYS_C405323
Types
Primary Key
Ex : Employee_id, Student_id
Unique Key
allowed Null value
Ex : Contact_no, email
Foreign Key
c1(pk) : 1 2 3
Not Null
Check
Duplicate NULL
------------------------------------
Primary Key X X
------------------------------------
S_id Number(2),
s_mail Varchar2(30),
s_gender char(1),
s_did Number(3),
);
DESC my_stu_details;
------------------------------------
------------------------------------
S_ID NUMBER(2)
S_NAME VARCHAR2(30)
S_MAIL VARCHAR2(30) Y
S_GENDER CHAR(1) Y
S_DID NUMBER(3) Y
------------------------------------
--Duplicate Check
--Null Check
--------------------------------------------------------
--------------------------------------------------------
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
--------------------------------------------------------
------------------------------------------------------------
-------------------------------------------------
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
-------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
ON DELETE CASCADE
Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)
SELECT c.owner,
c.constraint_name,
c.constraint_type,
c.table_name,
c.r_constraint_name,
c.status
FROM user_constraints c
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.
Interview Questions
Which Data Dictionary table contains information about constraint with corresponding column
name?
1 View comments
good
Reply
DEC
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 :
--Example 1:
BEGIN
commit;
END;
listagg(product,
',') within
FROM test_ins
GROUP BY empid;
-->-- Example 2
FROM employees
GROUP BY department_id;
0 Add a comment
NOV
IF ELSE
Multiple IF ELSE
LOOP
FOR LOOP
WHILE LOOP
BEGIN
Commit;
END;
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 1;
UPDATE test_udt t
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;
UPDATE test_udt t
ELSE
UPDATE test_udt t
END IF;
commit;
END;
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 2;
v_salary := v_salary+10005;
ELSE
v_salary := v_salary+20007;
END IF;
UPDATE test_udt t
commit;
END;
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');
v_salary := 2000;
dbms_output.put_line('2 inside');
v_salary := 3000;
dbms_output.put_line('3 inside');
v_salary := 4000;
dbms_output.put_line('4 inside');
END IF;
UPDATE test_udt t
commit;
END;
LOOP
--syntax
LOOP
--statements
--increment
--exit statement
END LOOP;
DECLARE
i NUMBER := 1;
x VARCHAR2(3);
BEGIN
LOOP
x := lpad(i,3,'0');
i := i+1;
IF MOD(i,100) = 0 THEN
commit;
dbms_output.put_line('commit executed');
END IF;
END LOOP;
END;
FOR LOOP
BEGIN
FOR I in 1..5
LOOP
END LOOP;
END;
BEGIN
LOOP
END LOOP;
END;
WHILE LOOP
DECLARE
i_val NUMBER:=0;
BEGIN
LOOP
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
0 Add a comment
OCT
21
Bulk Collect
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.
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
INTO dta;
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta alldata_typ;
BEGIN
END LOOP;
END;
-->-- LIMIT in Bulk collect --<--
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END;
dta1 alldata_typ1;
dta2 alldata_typ2;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END LOOP;
END;
/
DROP TABLE dep_details;
0 Add a comment
OCT
21
Ref Cursor
This is unconstrained cursor which will return different types depends upon the user input.
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.
AS
BEGIN
OPEN dep_det_c
FOR
END;
DECLARE
dep_det_c SYS_REFCURSOR;
tab_data dep_details%ROWTYPE;
BEGIN
ref_c_sp(dep_det_c);
LOOP
END LOOP;
CLOSE dep_det_c;
END;
/*sample output*/
Department Name : HR
Department Name : Sales
0 Add a comment
OCT
21
Cursor
SQL Private work Area where the query get passed and executed.
Types
******
Implicit(SQL)
Explicit
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
Cursor Stages
**************
OPEN cursor_name
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
Cursor Declaration
DECLARE
CURSOR <cursor_name>
IS
<SELECT statement>
BEGIN
END;
Cursor Loop
Loop
While Loop
For Loop
Cursor Clauses
Return
For update
Where current of
Bulk collect
p_id NUMBER,
p_name VARCHAR2(30),
p_order_dt DATE
);
BEGIN
FOR i IN 1 .. 75 LOOP
END LOOP;
commit;
END;
-->-- selecting data
---------------------------------------------
---------------------------------------------
---------------------------------------------
----------------------------------------------
Implicit Cursor
----------------------------------------------
----------------------------------------------
Explicit Cursor
----------------------------------------------
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
SELECT * FROM product_details
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
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
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*/
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
FETCH prod_detail_cur
INTO all_data;
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
************************************************************
************************************************************
DECLARE
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
FOR i IN prod_detail_cur
LOOP
END LOOP;
END;
/*sample output*/
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.
BEGIN
commit;
END;
----------------------------
----------------------------
1 Admin 1010
2 HR 1010
3 Sales 1020
4 Marketing 1020
----------------------------
DECLARE
all_data dep_details%ROWTYPE;
BEGIN
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1010);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1020);
LOOP
FETCH dep_det_c
INTO all_data;
EXIT WHEN dep_det_c%NOTFOUND;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
END;
/*sample output*/
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
0 Add a comment
OCT
21
Handling Exception
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
*********************
Oracle has predefined several exceptions that correspond to the most common oracle errors.
------------------------------------------------------------------------
------------------------------------------------------------------------
DUP_VAL_ON_INDEX ORA-00001 -1
OTHERS
------------------------------------------------------------------------
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
Single row SELECT returned no rows or your program referenced a deleted element in a nested
table
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
-->-- DUP_VAL_ON_INDEX --<--
commit;
BEGIN
EXCEPTION
END;
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
DECLARE
num1 NUMBER(2);
BEGIN
num1 := 345;
EXCEPTION
END;
BEGIN
COMMIT;
END;
DECLARE
cursor emp_c IS
all_data emp%ROWTYPE;
BEGIN
OPEN emp_c;
OPEN emp_c;
NULL;
CLOSE emp_c;
EXCEPTION
END;
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
**********************
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,
DECLARE
gender_ex EXCEPTION;
BEGIN
RAISE gender_ex;
END IF;
dbms_output.put_line('Gender : '||v_gender);
EXCEPTION
END;
DECLARE
abort_ex EXCEPTION;
BEGIN
FOR i IN 1..100
LOOP
BEGIN
IF mod(i,10)=0 THEN
RAISE abort_ex;
END IF;
EXCEPTION
NULL;
END;
END LOOP;
COMMIT;
END;
********************
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.
DECLARE
v_id NUMBER;
BEGIN
dbms_output.put_line(v_id);
EXCEPTION
END;
/*sample output*/
SQLCODE : 100
*********************
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:
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
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 :
DECLARE
BEGIN
END IF;
END;
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
I) specification
II) Body
5. Overloading
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_sal_sp;
BEGIN
END;
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_hdt_sp;
BEGIN
END;
RETURN NUMBER
IS
v_c NUMBER;
BEGIN
RETURN v_c;
END;
--Specification Part
IS
RETURN NUMBER;
END emp_pkg ;
--Body Part
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_sal_sp;
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_hdt_sp;
RETURN NUMBER
IS
v_c NUMBER;
BEGIN
RETURN v_c;
END;
END emp_pkg;
BEGIN
emp_pkg.emp_sal_sp(120);
END;
as
RETURN NUMBER;
IS
FROM employees;
End all_detail;
as
BEGIN
SELECT salary
INTO c
FROM Employees
WHERE Employee_id = a;
EXCEPTION
END emp2sal;
AS
BEGIN
SELECT Round(Months_between(sysdate,hire_date)/12)
INTO c
FROM Employees
WHERE Employee_id = a;
EXCEPTION
WHEN no_data_found THEN
END emp2exep;
RETURN NUMBER
AS
BEGIN
c := a+b;
RETURN C;
END;
End all_detail;
IS
END global_constant;
BEGIN
END;
DECLARE
PROCEDURE P3;
PROCEDURE P1 IS
BEGIN
p2;
END P1;
PROCEDURE P2 IS
BEGIN
p3;
END P2;
PROCEDURE P3 IS
BEGIN
END P3;
BEGIN
p1;
END;
sample output:
From procedure p1
From procedure p2
From procedure p3
What is package?
Advantage of package
0 Add a comment
OCT
p_id NUMBER(3),
p_nm VARCHAR2(30),
p_qty NUMBER(8),
order_dt DATE
);
BEGIN
commit;
END;
------------------------------------
------------------------------------
DECLARE
v_name VARCHAR2(4);
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
DECLARE
v_name VARCHAR2(5);
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
VALUES
(106,
'name6',
700,
'26-Dec-12');
commit;
v_name VARCHAR2(5);
BEGIN
FROM product_details
--error
END;
DECLARE
v_name product_details.p_nm%TYPE;
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
/
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
END;
--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
END;
dept_id number(3) ,
dept_name varchar2(30),
dept_manager_name varchar2(30)
);
-------------------------------------------------------
| 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
END;
---------------------------------------------------
---------------------------------------------------
| 20 | dept2 | manager_name2 |
---------------------------------------------------
Interview Question :
0 Add a comment
SEP
29
BULK Exceptions
/************************************************************************
* Reference : http://www.dba-oracle.com/plsql/t_plsql_exceptions.htm *
************************************************************************/
DECLARE
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
commit;
END;
COUNT(*)
-------
200
DECLARE
TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;
BEGIN
FOR i in 1..200
LOOP
v_dat.EXTEND;
v_dat(v_dat.LAST) := i;
END LOOP;
v_dat(100) := NULL;
FORALL i IN v_dat.FIRST..v_dat.LAST
commit;
END;
/*
Error Message :
ORA-06512: at line 15
*/
sample2.sql --with exception part
DECLARE
BEGIN
FOR i in 1..200
LOOP
v_dat.EXTEND;
v_dat(v_dat.LAST) := i;
END LOOP;
v_dat(100) := NULL;
BEGIN
FORALL i IN v_dat.FIRST..v_dat.LAST
COMMIT;
EXCEPTION
END;
COUNT(*)
-------
99
SQL%BULK_EXCEPTIONS(i).ERROR_INDEX
Holds the iteration (not the subscript) of the original FORALL statement that raised the
exception.
the exception row must be found by looping through the original collection the correct
number of times.
SQL%BULK_EXCEPTIONS(i).ERROR_CODE
DECLARE
v_ex_count NUMBER(4);
abort_ex EXCEPTION;
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;
COMMIT;
EXCEPTION
v_ex_count := SQL%BULK_EXCEPTIONS.COUNT;
END LOOP;
END;
END;
/*
Sample output:
*/
SELECT COUNT(*) FROM bulk_tb;
COUNT(*)
-------
198
SAVE EXCEPTIONS clause being removed, in the above script now traps a different error number.
/*
Sample output:
*/
COUNT(*)
-------
99
SELECT COUNT(*) FROM bulk_tb;
0 Add a comment
SEP
29
/************************************************************************
************************************************************************/
END LOOP;
commit;
END;
DECLARE
CURSOR PROD_DTLS_C IS
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
END IF;
END LOOP;
CLOSE PROD_DTLS_C;
COMMIT;
END;
BEGIN
END LOOP;
commit;
END;
DECLARE
CURSOR PROD_DTLS_C IS
V_PID PROD_DETAILS.P_ID%TYPE;
V_PRDNAME PROD_DETAILS.P_NAME%TYPE;
BEGIN
OPEN PROD_DTLS_C;
LOOP
IF PROD_DTLS_C%NOTFOUND THEN
EXIT;
ELSE
UPDATE PROD_DETAILS P
END IF;
COMMIT;
END LOOP;
CLOSE PROD_DTLS_C;
--COMMIT;
END;
0 Add a comment
MAY
28
FROM Dual;
FROM Dual;
SAL_DETAILS
---------------------------------------
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
------------------------------------
The '_' wild card character is used to match exactly one character
WITH mail_ids AS
UNION
UNION
SELECT 'an%murugappan@gmail.com' mail FROM Dual
----------------------------------
an_murugappan@gmail.com
WITH mail_ids AS
UNION
UNION
----------------------------------
an%murugappan@gmail.com
Escape ampersand (&) characters in SQL*Plus
'23'
----
23
'&A'
----
&a
'&A'
----
&a
SQL> SET SCAN ON;
'45'
----
45
0 Add a comment
MAY
28
Data Manipulation Language (DML) statements are used for managing data within schema
objects. Some examples:
DELETE - deletes all records from a table, the space for the records remain
prod_id NUMBER(4) ,
prod_name VARCHAR2(30) ,
comments VARCHAR2(300)
);
no_data_found
INSERT
---------------------------------------------------------------------------
---------------------------------------------------------------------------
100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
VALUES(103,'Moto X','11-May-14','13-May-14');
VALUES(103,'Moto X','11-May-14','13-May-14');
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--If you want to insert NULL value you can ignore that column at the time of inserting
VALUES(104,'Moto G','19-May-14','22-May-14',NULL);
---------------------------------------------------------------------------
---------------------------------------------------------------------------
--if you are not providing values for order_dt and deliver_dt column default value can be taken.
---------------------------------------------------------------------------
----------------------------------------------------------------------------
COUNT(*)
-------
WHERE id = 900;
SELECT COUNT(*) FROM ins_chk;
COUNT(*)
-------
COUNT(*)
-------
UPDATE
Syntax :
UPDATE table_name
column2_name = column2_value,
column2_name = column3_value,
columnn_name = columnn_value
WHERE condition(s);
---------------------------------------------------------------------------
----------------------------------------------------------------------
UPDATE prod_details ps
SELECT *
FROM prod_details ps
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--If you try to execute update statement without condition it'll update all the records inside the
table.
UPDATE prod_details ps
---------------------------------------------------------------------------
---------------------------------------------------------------------------
----------------------------------------------------------------------
--if your update text contain ' means you can use following metnod (use '')
UPDATE prod_details ps
SELECT *
FROM prod_details ps
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
DELETE
Syntax:
WHERE condition(s);
SELECT *
---------------------------------------------------------------------------------------
100 Apple iphone 5s 5/21/2014 5/24/2014 Some product's are not available
---------------------------------------------------------------------------------------
no rows selected.
0 Add a comment
MAY
28
Data Definition Language (DDL) statements are used to define the database structure or schema.
Some examples:
ADD
RENAME
MODIFY
DROP
--------------------------------------------------------------------------
--------------------------------------------------------------------------
S: -84 to 127
VARCHAR2 4000 Bytes we can store 0-9, a-z, A-Z and special characters
--------------------------------------------------------------------------
CREATE
RENAME
DROP
TRUNCATE
--creating table
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
ADD : Used to add a column after the table hase been created
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)
-----------------------------
SYNTAX
ADD (
column_1 Data_type(size),
column_2 Data_type(size),
column_3 Data_type(size),
column_4 Data_type(size)
);
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.
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)
-----------------------------
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.
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)
-----------------------------
SYNTAX
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
DROP : Used to drop the tabel (Data + stucture of the table get removed from the database )
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
Posted 28th May 2014 by Unknown
0 Add a comment
MAY
28
Statements in Oracle
DDL statements are used to define the database structure or schema. Some examples:
ADD
RENAME
MODIFY
DROP
DELETE - deletes all records from a table, the space for the records remain
TCL statements are used to manage the changes made by DML statements. It allows
statements to be grouped together into logical transactions.
SAVEPOINT - identify a point in a transaction to which you can later roll back
0 Add a comment
MAY
19
roll_no NUMBER(4) ,
Name VARCHAR2(30) ,
dept_cd VARCHAR2(20) ,
total_marks NUMBER(3)
);
BEGIN
END;
/
DECODE
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',
'IT',
'Information Technology',
FROM students;
Sample Output
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
CASE
Example
SELECT roll_no,
NAME,
dept_cd,
total_marks,
CASE
'A Grade'
'B Grade'
WHEN total_marks > 300 THEN
'C Grade'
ELSE
'U Grade'
END AS "GRADE"
FROM students;
-----------------------------------------------
-----------------------------------------------
-----------------------------------------------
Interview Questions:
What is DECODE?
What is CASE?
MAY
19
Sub Query
Want to fetch the person Who are all getting salary more than Neena's salary ?
From Employees
Sub Query :
From Employees
);
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 :
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
);
From Employees
);
From Employees
);
From Employees
);
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
FROM
Dual;
);
SELECT AVG(salary)
FROM employees
);
0 Add a comment
Loading
search
JUL
20
--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
, AVG(b.salary) avg_sal
FROM employees b
GROUP BY b.department_id
)b
Display all the customer who have placed more number of orders by using INLINE view
( custm_id NUMBER ,
custm_nm VARCHAR2(30) ,
ttl_amt NUMBER(7,2)
);
BEGIN
COMMIT;
END;
SELECT c.*
FROM customer_order_det_tb c;
--------------------------------------------
--------------------------------------------
--------------------------------------------
--Writing a Quer to display all the customer who have placed maximum number of order
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
--------------------------------
100 Murugappan 2
102 Ramesh 2
101 Raja 1
--------------------------------
----------
total_odr
----------
----------
Inline view to find all the customers who have placed maximum number of orders
/****************************************
Syntax
WHERE contition;
****************************************/
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
) query1,
) query2
-------------------------------
-------------------------------
100 Murugappan 2
102 Ramesh 2
-------------------------------
--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 employees e
Example :
--in 11g
SELECT *
FROM departments d
SELECT *
FROM departments d
);
--in 11g
WITH t
AS
( SELECT LEVEL a
FROM dual
SELECT *
FROM t, (SELECT *
FROM employees
);
--in 12c
WITH t
AS
SELECT * FROM t,
LATERAL(SELECT *
FROM employees
0 Add a comment
JAN
23
--creating table
eid NUMBER(4),
ename VARCHAR2(30),
depno NUMBER(3),
salary NUMBER(8)
);
BEGIN
--Inserting records
COMMIT;
END;
/
SELECT * FROM employee_data
SELECT MAX(salary)
FROM employee_data
FROM employee_data);
SELECT MIN(salary)
FROM employee_data
ORDER BY salary DESC)
SELECT MIN(salary)
FROM employee_data
--query to select all the details of the employee whose getting nth maximum salary
SELECT *
rownum rn
FROM (SELECT *
FROM employee_data
WHERE rn = 9;
WHERE rank = 9;
SELECT *
WHERE rank = 4;
SELECT *
WHERE rank = 4;
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
--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
--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,
first_name,
salary
FROM employees
7 View comments
JAN
22
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.
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.
14 rows selected.
Elapsed: 00:00:14.01
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.
0 Add a comment
DEC
21
Constraints
Format : [part_of_project_name-table_name-column_name-constraint_type]
Format : sys_cn
Example : SYS_C405323
Types
Primary Key
Ex : Employee_id, Student_id
Unique Key
allowed Null value
Ex : Contact_no, email
Foreign Key
c1(pk) : 1 2 3
Not Null
Check
Duplicate NULL
------------------------------------
Primary Key X X
------------------------------------
S_id Number(2),
s_mail Varchar2(30),
s_gender char(1),
s_did Number(3),
);
DESC my_stu_details;
------------------------------------
------------------------------------
S_ID NUMBER(2)
S_NAME VARCHAR2(30)
S_MAIL VARCHAR2(30) Y
S_GENDER CHAR(1) Y
S_DID NUMBER(3) Y
------------------------------------
--Duplicate Check
--Null Check
--------------------------------------------------------
--------------------------------------------------------
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
--------------------------------------------------------
------------------------------------------------------------
-------------------------------------------------
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
-------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
ON DELETE CASCADE
Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)
SELECT c.owner,
c.constraint_name,
c.constraint_type,
c.table_name,
c.r_constraint_name,
c.status
FROM user_constraints c
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.
Interview Questions
Which Data Dictionary table contains information about constraint with corresponding column
name?
1 View comments
good
Reply
DEC
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 :
--Example 1:
BEGIN
commit;
END;
listagg(product,
',') within
FROM test_ins
GROUP BY empid;
-->-- Example 2
FROM employees
GROUP BY department_id;
0 Add a comment
NOV
IF ELSE
Multiple IF ELSE
LOOP
FOR LOOP
WHILE LOOP
BEGIN
Commit;
END;
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 1;
UPDATE test_udt t
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;
UPDATE test_udt t
ELSE
UPDATE test_udt t
END IF;
commit;
END;
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 2;
v_salary := v_salary+10005;
ELSE
v_salary := v_salary+20007;
END IF;
UPDATE test_udt t
commit;
END;
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');
v_salary := 2000;
dbms_output.put_line('2 inside');
v_salary := 3000;
dbms_output.put_line('3 inside');
v_salary := 4000;
dbms_output.put_line('4 inside');
END IF;
UPDATE test_udt t
commit;
END;
LOOP
--syntax
LOOP
--statements
--increment
--exit statement
END LOOP;
DECLARE
i NUMBER := 1;
x VARCHAR2(3);
BEGIN
LOOP
x := lpad(i,3,'0');
i := i+1;
IF MOD(i,100) = 0 THEN
commit;
dbms_output.put_line('commit executed');
END IF;
END LOOP;
END;
FOR LOOP
BEGIN
FOR I in 1..5
LOOP
END LOOP;
END;
BEGIN
LOOP
END LOOP;
END;
WHILE LOOP
DECLARE
i_val NUMBER:=0;
BEGIN
LOOP
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
0 Add a comment
OCT
21
Bulk Collect
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.
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
INTO dta;
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta alldata_typ;
BEGIN
END LOOP;
END;
-->-- LIMIT in Bulk collect --<--
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END;
dta1 alldata_typ1;
dta2 alldata_typ2;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END LOOP;
END;
/
DROP TABLE dep_details;
0 Add a comment
OCT
21
Ref Cursor
This is unconstrained cursor which will return different types depends upon the user input.
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.
AS
BEGIN
OPEN dep_det_c
FOR
END;
DECLARE
dep_det_c SYS_REFCURSOR;
tab_data dep_details%ROWTYPE;
BEGIN
ref_c_sp(dep_det_c);
LOOP
END LOOP;
CLOSE dep_det_c;
END;
/*sample output*/
Department Name : HR
Department Name : Sales
0 Add a comment
OCT
21
Cursor
SQL Private work Area where the query get passed and executed.
Types
******
Implicit(SQL)
Explicit
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
Cursor Stages
**************
OPEN cursor_name
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
Cursor Declaration
DECLARE
CURSOR <cursor_name>
IS
<SELECT statement>
BEGIN
END;
Cursor Loop
Loop
While Loop
For Loop
Cursor Clauses
Return
For update
Where current of
Bulk collect
p_id NUMBER,
p_name VARCHAR2(30),
p_order_dt DATE
);
BEGIN
FOR i IN 1 .. 75 LOOP
END LOOP;
commit;
END;
-->-- selecting data
---------------------------------------------
---------------------------------------------
---------------------------------------------
----------------------------------------------
Implicit Cursor
----------------------------------------------
----------------------------------------------
Explicit Cursor
----------------------------------------------
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
SELECT * FROM product_details
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
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
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*/
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
FETCH prod_detail_cur
INTO all_data;
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
************************************************************
************************************************************
DECLARE
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
FOR i IN prod_detail_cur
LOOP
END LOOP;
END;
/*sample output*/
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.
BEGIN
commit;
END;
----------------------------
----------------------------
1 Admin 1010
2 HR 1010
3 Sales 1020
4 Marketing 1020
----------------------------
DECLARE
all_data dep_details%ROWTYPE;
BEGIN
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1010);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1020);
LOOP
FETCH dep_det_c
INTO all_data;
EXIT WHEN dep_det_c%NOTFOUND;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
END;
/*sample output*/
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
0 Add a comment
OCT
21
Handling Exception
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
*********************
Oracle has predefined several exceptions that correspond to the most common oracle errors.
------------------------------------------------------------------------
------------------------------------------------------------------------
DUP_VAL_ON_INDEX ORA-00001 -1
OTHERS
------------------------------------------------------------------------
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
Single row SELECT returned no rows or your program referenced a deleted element in a nested
table
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
-->-- DUP_VAL_ON_INDEX --<--
commit;
BEGIN
EXCEPTION
END;
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
DECLARE
num1 NUMBER(2);
BEGIN
num1 := 345;
EXCEPTION
END;
BEGIN
COMMIT;
END;
DECLARE
cursor emp_c IS
all_data emp%ROWTYPE;
BEGIN
OPEN emp_c;
OPEN emp_c;
NULL;
CLOSE emp_c;
EXCEPTION
END;
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
**********************
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,
DECLARE
gender_ex EXCEPTION;
BEGIN
RAISE gender_ex;
END IF;
dbms_output.put_line('Gender : '||v_gender);
EXCEPTION
END;
DECLARE
abort_ex EXCEPTION;
BEGIN
FOR i IN 1..100
LOOP
BEGIN
IF mod(i,10)=0 THEN
RAISE abort_ex;
END IF;
EXCEPTION
NULL;
END;
END LOOP;
COMMIT;
END;
********************
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.
DECLARE
v_id NUMBER;
BEGIN
dbms_output.put_line(v_id);
EXCEPTION
END;
/*sample output*/
SQLCODE : 100
*********************
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:
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
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 :
DECLARE
BEGIN
END IF;
END;
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
I) specification
II) Body
5. Overloading
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_sal_sp;
BEGIN
END;
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_hdt_sp;
BEGIN
END;
RETURN NUMBER
IS
v_c NUMBER;
BEGIN
RETURN v_c;
END;
--Specification Part
IS
RETURN NUMBER;
END emp_pkg ;
--Body Part
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_sal_sp;
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_hdt_sp;
RETURN NUMBER
IS
v_c NUMBER;
BEGIN
RETURN v_c;
END;
END emp_pkg;
BEGIN
emp_pkg.emp_sal_sp(120);
END;
as
RETURN NUMBER;
IS
FROM employees;
End all_detail;
as
BEGIN
SELECT salary
INTO c
FROM Employees
WHERE Employee_id = a;
EXCEPTION
END emp2sal;
AS
BEGIN
SELECT Round(Months_between(sysdate,hire_date)/12)
INTO c
FROM Employees
WHERE Employee_id = a;
EXCEPTION
WHEN no_data_found THEN
END emp2exep;
RETURN NUMBER
AS
BEGIN
c := a+b;
RETURN C;
END;
End all_detail;
IS
END global_constant;
BEGIN
END;
DECLARE
PROCEDURE P3;
PROCEDURE P1 IS
BEGIN
p2;
END P1;
PROCEDURE P2 IS
BEGIN
p3;
END P2;
PROCEDURE P3 IS
BEGIN
END P3;
BEGIN
p1;
END;
sample output:
From procedure p1
From procedure p2
From procedure p3
What is package?
Advantage of package
0 Add a comment
OCT
p_id NUMBER(3),
p_nm VARCHAR2(30),
p_qty NUMBER(8),
order_dt DATE
);
BEGIN
commit;
END;
------------------------------------
------------------------------------
DECLARE
v_name VARCHAR2(4);
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
DECLARE
v_name VARCHAR2(5);
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
VALUES
(106,
'name6',
700,
'26-Dec-12');
commit;
v_name VARCHAR2(5);
BEGIN
FROM product_details
--error
END;
DECLARE
v_name product_details.p_nm%TYPE;
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
/
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
END;
--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
END;
dept_id number(3) ,
dept_name varchar2(30),
dept_manager_name varchar2(30)
);
-------------------------------------------------------
| 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
END;
---------------------------------------------------
---------------------------------------------------
| 20 | dept2 | manager_name2 |
---------------------------------------------------
Interview Question :
0 Add a comment
SEP
29
BULK Exceptions
/************************************************************************
* Reference : http://www.dba-oracle.com/plsql/t_plsql_exceptions.htm *
************************************************************************/
DECLARE
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
commit;
END;
COUNT(*)
-------
200
DECLARE
TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;
BEGIN
FOR i in 1..200
LOOP
v_dat.EXTEND;
v_dat(v_dat.LAST) := i;
END LOOP;
v_dat(100) := NULL;
FORALL i IN v_dat.FIRST..v_dat.LAST
commit;
END;
/*
Error Message :
ORA-06512: at line 15
*/
sample2.sql --with exception part
DECLARE
BEGIN
FOR i in 1..200
LOOP
v_dat.EXTEND;
v_dat(v_dat.LAST) := i;
END LOOP;
v_dat(100) := NULL;
BEGIN
FORALL i IN v_dat.FIRST..v_dat.LAST
COMMIT;
EXCEPTION
END;
COUNT(*)
-------
99
SQL%BULK_EXCEPTIONS(i).ERROR_INDEX
Holds the iteration (not the subscript) of the original FORALL statement that raised the
exception.
the exception row must be found by looping through the original collection the correct
number of times.
SQL%BULK_EXCEPTIONS(i).ERROR_CODE
DECLARE
v_ex_count NUMBER(4);
abort_ex EXCEPTION;
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;
COMMIT;
EXCEPTION
v_ex_count := SQL%BULK_EXCEPTIONS.COUNT;
END LOOP;
END;
END;
/*
Sample output:
*/
SELECT COUNT(*) FROM bulk_tb;
COUNT(*)
-------
198
SAVE EXCEPTIONS clause being removed, in the above script now traps a different error number.
/*
Sample output:
*/
COUNT(*)
-------
99
SELECT COUNT(*) FROM bulk_tb;
0 Add a comment
SEP
29
/************************************************************************
************************************************************************/
END LOOP;
commit;
END;
DECLARE
CURSOR PROD_DTLS_C IS
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
END IF;
END LOOP;
CLOSE PROD_DTLS_C;
COMMIT;
END;
BEGIN
END LOOP;
commit;
END;
DECLARE
CURSOR PROD_DTLS_C IS
V_PID PROD_DETAILS.P_ID%TYPE;
V_PRDNAME PROD_DETAILS.P_NAME%TYPE;
BEGIN
OPEN PROD_DTLS_C;
LOOP
IF PROD_DTLS_C%NOTFOUND THEN
EXIT;
ELSE
UPDATE PROD_DETAILS P
END IF;
COMMIT;
END LOOP;
CLOSE PROD_DTLS_C;
--COMMIT;
END;
0 Add a comment
MAY
28
FROM Dual;
FROM Dual;
SAL_DETAILS
---------------------------------------
FROM Dual;
Info
---------------------------------------
SELECT q'[some test ' some test ' some text ']' AS "In 10g"
FROM dual;
In 10g
------------------------------------
The '_' wild card character is used to match exactly one character
WITH mail_ids AS
UNION
----------------------------------
an_murugappan@gmail.com
WITH mail_ids AS
UNION
UNION
----------------------------------
an%murugappan@gmail.com
'23'
----
23
'&A'
----
&a
'&A'
----
&a
SQL> SET SCAN ON;
'45'
----
45
0 Add a comment
MAY
28
Data Manipulation Language (DML) statements are used for managing data within schema
objects. Some examples:
DELETE - deletes all records from a table, the space for the records remain
prod_id NUMBER(4) ,
prod_name VARCHAR2(30) ,
comments VARCHAR2(300)
);
no_data_found
INSERT
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
VALUES(103,'Moto X','11-May-14','13-May-14');
VALUES(103,'Moto X','11-May-14','13-May-14');
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--If you want to insert NULL value you can ignore that column at the time of inserting
VALUES(104,'Moto G','19-May-14','22-May-14',NULL);
---------------------------------------------------------------------------
---------------------------------------------------------------------------
--if you are not providing values for order_dt and deliver_dt column default value can be taken.
---------------------------------------------------------------------------
----------------------------------------------------------------------------
---------------------------------------------------------------------------
COUNT(*)
-------
COUNT(*)
-------
COUNT(*)
-------
UPDATE
Syntax :
UPDATE table_name
column2_name = column2_value,
column2_name = column3_value,
columnn_name = columnn_value
WHERE condition(s);
---------------------------------------------------------------------------
----------------------------------------------------------------------
---------------------------------------------------------------------------
UPDATE prod_details ps
SELECT *
FROM prod_details ps
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--If you try to execute update statement without condition it'll update all the records inside the
table.
UPDATE prod_details ps
SELECT *
---------------------------------------------------------------------------
---------------------------------------------------------------------------
----------------------------------------------------------------------
--if your update text contain ' means you can use following metnod (use '')
UPDATE prod_details ps
FROM prod_details ps
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
DELETE
Syntax:
WHERE condition(s);
SELECT *
FROM prod_details ps;
---------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------
100 Apple iphone 5s 5/21/2014 5/24/2014 Some product's are not available
---------------------------------------------------------------------------------------
no rows selected.
0 Add a comment
MAY
28
Data Definition Language (DDL) statements are used to define the database structure or schema.
Some examples:
ADD
RENAME
MODIFY
DROP
--------------------------------------------------------------------------
--------------------------------------------------------------------------
S: -84 to 127
VARCHAR2 4000 Bytes we can store 0-9, a-z, A-Z and special characters
--------------------------------------------------------------------------
CREATE
RENAME
DROP
TRUNCATE
--creating table
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
ADD : Used to add a column after the table hase been created
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)
-----------------------------
SYNTAX
ADD (
column_1 Data_type(size),
column_2 Data_type(size),
column_3 Data_type(size),
column_4 Data_type(size)
);
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.
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)
-----------------------------
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.
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)
-----------------------------
SYNTAX
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
DROP : Used to drop the tabel (Data + stucture of the table get removed from the database )
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
Posted 28th May 2014 by Unknown
0 Add a comment
MAY
28
Statements in Oracle
DDL statements are used to define the database structure or schema. Some examples:
ADD
RENAME
MODIFY
DROP
DELETE - deletes all records from a table, the space for the records remain
TCL statements are used to manage the changes made by DML statements. It allows
statements to be grouped together into logical transactions.
SAVEPOINT - identify a point in a transaction to which you can later roll back
0 Add a comment
MAY
19
roll_no NUMBER(4) ,
Name VARCHAR2(30) ,
dept_cd VARCHAR2(20) ,
total_marks NUMBER(3)
);
BEGIN
DECODE
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',
'IT',
'Information Technology',
FROM students;
Sample Output
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
CASE
Example
SELECT roll_no,
NAME,
dept_cd,
total_marks,
CASE
'A Grade'
'C Grade'
ELSE
'U Grade'
END AS "GRADE"
FROM students;
-----------------------------------------------
-----------------------------------------------
-----------------------------------------------
Interview Questions:
What is DECODE?
What is CASE?
0 Add a comment
MAY
19
Sub Query
Want to fetch the person Who are all getting salary more than Neena's salary ?
From Employees
Sub Query :
From Employees
);
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
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)
From Employees
);
From Employees
);
From Employees
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
FROM
Dual;
(
Select * from Employees
Where Department_id = 60
);
SELECT AVG(salary)
FROM employees
);
0 Add a comment
Loading
search
JUL
20
--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
, AVG(b.salary) avg_sal
FROM employees b
GROUP BY b.department_id
)b
Display all the customer who have placed more number of orders by using INLINE view
( custm_id NUMBER ,
custm_nm VARCHAR2(30) ,
ttl_amt NUMBER(7,2)
);
BEGIN
COMMIT;
END;
SELECT c.*
FROM customer_order_det_tb c;
--------------------------------------------
--------------------------------------------
--------------------------------------------
--Writing a Quer to display all the customer who have placed maximum number of order
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
--------------------------------
100 Murugappan 2
102 Ramesh 2
101 Raja 1
--------------------------------
----------
total_odr
----------
----------
Inline view to find all the customers who have placed maximum number of orders
/****************************************
Syntax
WHERE contition;
****************************************/
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
) query1,
) query2
-------------------------------
-------------------------------
100 Murugappan 2
102 Ramesh 2
-------------------------------
--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 employees e
Example :
--in 11g
SELECT *
FROM departments d
SELECT *
FROM departments d
);
--in 11g
WITH t
AS
( SELECT LEVEL a
FROM dual
SELECT *
FROM t, (SELECT *
FROM employees
);
--in 12c
WITH t
AS
SELECT * FROM t,
LATERAL(SELECT *
FROM employees
0 Add a comment
JAN
23
--creating table
eid NUMBER(4),
ename VARCHAR2(30),
depno NUMBER(3),
salary NUMBER(8)
);
BEGIN
--Inserting records
COMMIT;
END;
/
SELECT * FROM employee_data
SELECT MAX(salary)
FROM employee_data
FROM employee_data);
SELECT MIN(salary)
FROM employee_data
ORDER BY salary DESC)
SELECT MIN(salary)
FROM employee_data
--query to select all the details of the employee whose getting nth maximum salary
SELECT *
rownum rn
FROM (SELECT *
FROM employee_data
WHERE rn = 9;
WHERE rank = 9;
SELECT *
WHERE rank = 4;
SELECT *
WHERE rank = 4;
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
--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
--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,
first_name,
salary
FROM employees
7 View comments
JAN
22
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.
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.
14 rows selected.
Elapsed: 00:00:14.01
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.
0 Add a comment
DEC
21
Constraints
Format : [part_of_project_name-table_name-column_name-constraint_type]
Format : sys_cn
Example : SYS_C405323
Types
Primary Key
Ex : Employee_id, Student_id
Unique Key
allowed Null value
Ex : Contact_no, email
Foreign Key
c1(pk) : 1 2 3
Not Null
Check
Duplicate NULL
------------------------------------
Primary Key X X
------------------------------------
S_id Number(2),
s_mail Varchar2(30),
s_gender char(1),
s_did Number(3),
);
DESC my_stu_details;
------------------------------------
------------------------------------
S_ID NUMBER(2)
S_NAME VARCHAR2(30)
S_MAIL VARCHAR2(30) Y
S_GENDER CHAR(1) Y
S_DID NUMBER(3) Y
------------------------------------
--Duplicate Check
--Null Check
--------------------------------------------------------
--------------------------------------------------------
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
--------------------------------------------------------
------------------------------------------------------------
-------------------------------------------------
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
-------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
ON DELETE CASCADE
Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)
SELECT c.owner,
c.constraint_name,
c.constraint_type,
c.table_name,
c.r_constraint_name,
c.status
FROM user_constraints c
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.
Interview Questions
Which Data Dictionary table contains information about constraint with corresponding column
name?
1 View comments
good
Reply
DEC
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 :
--Example 1:
BEGIN
commit;
END;
listagg(product,
',') within
FROM test_ins
GROUP BY empid;
-->-- Example 2
FROM employees
GROUP BY department_id;
0 Add a comment
NOV
IF ELSE
Multiple IF ELSE
LOOP
FOR LOOP
WHILE LOOP
BEGIN
Commit;
END;
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 1;
UPDATE test_udt t
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;
UPDATE test_udt t
ELSE
UPDATE test_udt t
END IF;
commit;
END;
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 2;
v_salary := v_salary+10005;
ELSE
v_salary := v_salary+20007;
END IF;
UPDATE test_udt t
commit;
END;
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');
v_salary := 2000;
dbms_output.put_line('2 inside');
v_salary := 3000;
dbms_output.put_line('3 inside');
v_salary := 4000;
dbms_output.put_line('4 inside');
END IF;
UPDATE test_udt t
commit;
END;
LOOP
--syntax
LOOP
--statements
--increment
--exit statement
END LOOP;
DECLARE
i NUMBER := 1;
x VARCHAR2(3);
BEGIN
LOOP
x := lpad(i,3,'0');
i := i+1;
IF MOD(i,100) = 0 THEN
commit;
dbms_output.put_line('commit executed');
END IF;
END LOOP;
END;
FOR LOOP
BEGIN
FOR I in 1..5
LOOP
END LOOP;
END;
BEGIN
LOOP
END LOOP;
END;
WHILE LOOP
DECLARE
i_val NUMBER:=0;
BEGIN
LOOP
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
0 Add a comment
OCT
21
Bulk Collect
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.
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
INTO dta;
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta alldata_typ;
BEGIN
END LOOP;
END;
-->-- LIMIT in Bulk collect --<--
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END;
dta1 alldata_typ1;
dta2 alldata_typ2;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END LOOP;
END;
/
DROP TABLE dep_details;
0 Add a comment
OCT
21
Ref Cursor
This is unconstrained cursor which will return different types depends upon the user input.
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.
AS
BEGIN
OPEN dep_det_c
FOR
END;
DECLARE
dep_det_c SYS_REFCURSOR;
tab_data dep_details%ROWTYPE;
BEGIN
ref_c_sp(dep_det_c);
LOOP
END LOOP;
CLOSE dep_det_c;
END;
/*sample output*/
Department Name : HR
Department Name : Sales
0 Add a comment
OCT
21
Cursor
SQL Private work Area where the query get passed and executed.
Types
******
Implicit(SQL)
Explicit
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
Cursor Stages
**************
OPEN cursor_name
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
Cursor Declaration
DECLARE
CURSOR <cursor_name>
IS
<SELECT statement>
BEGIN
END;
Cursor Loop
Loop
While Loop
For Loop
Cursor Clauses
Return
For update
Where current of
Bulk collect
p_id NUMBER,
p_name VARCHAR2(30),
p_order_dt DATE
);
BEGIN
FOR i IN 1 .. 75 LOOP
END LOOP;
commit;
END;
-->-- selecting data
---------------------------------------------
---------------------------------------------
---------------------------------------------
----------------------------------------------
Implicit Cursor
----------------------------------------------
----------------------------------------------
Explicit Cursor
----------------------------------------------
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
SELECT * FROM product_details
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
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
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*/
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
FETCH prod_detail_cur
INTO all_data;
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
************************************************************
************************************************************
DECLARE
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
FOR i IN prod_detail_cur
LOOP
END LOOP;
END;
/*sample output*/
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.
BEGIN
commit;
END;
----------------------------
----------------------------
1 Admin 1010
2 HR 1010
3 Sales 1020
4 Marketing 1020
----------------------------
DECLARE
all_data dep_details%ROWTYPE;
BEGIN
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1010);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1020);
LOOP
FETCH dep_det_c
INTO all_data;
EXIT WHEN dep_det_c%NOTFOUND;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
END;
/*sample output*/
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
0 Add a comment
OCT
21
Handling Exception
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
*********************
Oracle has predefined several exceptions that correspond to the most common oracle errors.
------------------------------------------------------------------------
------------------------------------------------------------------------
DUP_VAL_ON_INDEX ORA-00001 -1
OTHERS
------------------------------------------------------------------------
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
Single row SELECT returned no rows or your program referenced a deleted element in a nested
table
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
-->-- DUP_VAL_ON_INDEX --<--
commit;
BEGIN
EXCEPTION
END;
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
DECLARE
num1 NUMBER(2);
BEGIN
num1 := 345;
EXCEPTION
END;
BEGIN
COMMIT;
END;
DECLARE
cursor emp_c IS
all_data emp%ROWTYPE;
BEGIN
OPEN emp_c;
OPEN emp_c;
NULL;
CLOSE emp_c;
EXCEPTION
END;
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
**********************
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,
DECLARE
gender_ex EXCEPTION;
BEGIN
RAISE gender_ex;
END IF;
dbms_output.put_line('Gender : '||v_gender);
EXCEPTION
END;
DECLARE
abort_ex EXCEPTION;
BEGIN
FOR i IN 1..100
LOOP
BEGIN
IF mod(i,10)=0 THEN
RAISE abort_ex;
END IF;
EXCEPTION
NULL;
END;
END LOOP;
COMMIT;
END;
********************
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.
DECLARE
v_id NUMBER;
BEGIN
dbms_output.put_line(v_id);
EXCEPTION
END;
/*sample output*/
SQLCODE : 100
*********************
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:
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
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 :
DECLARE
BEGIN
END IF;
END;
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
I) specification
II) Body
5. Overloading
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_sal_sp;
BEGIN
END;
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_hdt_sp;
BEGIN
END;
RETURN NUMBER
IS
v_c NUMBER;
BEGIN
RETURN v_c;
END;
--Specification Part
IS
RETURN NUMBER;
END emp_pkg ;
--Body Part
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_sal_sp;
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_hdt_sp;
RETURN NUMBER
IS
v_c NUMBER;
BEGIN
RETURN v_c;
END;
END emp_pkg;
BEGIN
emp_pkg.emp_sal_sp(120);
END;
as
RETURN NUMBER;
IS
FROM employees;
End all_detail;
as
BEGIN
SELECT salary
INTO c
FROM Employees
WHERE Employee_id = a;
EXCEPTION
END emp2sal;
AS
BEGIN
SELECT Round(Months_between(sysdate,hire_date)/12)
INTO c
FROM Employees
WHERE Employee_id = a;
EXCEPTION
WHEN no_data_found THEN
END emp2exep;
RETURN NUMBER
AS
BEGIN
c := a+b;
RETURN C;
END;
End all_detail;
IS
END global_constant;
BEGIN
END;
DECLARE
PROCEDURE P3;
PROCEDURE P1 IS
BEGIN
p2;
END P1;
PROCEDURE P2 IS
BEGIN
p3;
END P2;
PROCEDURE P3 IS
BEGIN
END P3;
BEGIN
p1;
END;
sample output:
From procedure p1
From procedure p2
From procedure p3
What is package?
Advantage of package
0 Add a comment
OCT
p_id NUMBER(3),
p_nm VARCHAR2(30),
p_qty NUMBER(8),
order_dt DATE
);
BEGIN
commit;
END;
------------------------------------
------------------------------------
DECLARE
v_name VARCHAR2(4);
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
DECLARE
v_name VARCHAR2(5);
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
VALUES
(106,
'name6',
700,
'26-Dec-12');
commit;
v_name VARCHAR2(5);
BEGIN
FROM product_details
--error
END;
DECLARE
v_name product_details.p_nm%TYPE;
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
/
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
END;
--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
END;
dept_id number(3) ,
dept_name varchar2(30),
dept_manager_name varchar2(30)
);
-------------------------------------------------------
| 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
END;
---------------------------------------------------
---------------------------------------------------
| 20 | dept2 | manager_name2 |
---------------------------------------------------
Interview Question :
0 Add a comment
SEP
29
BULK Exceptions
/************************************************************************
* Reference : http://www.dba-oracle.com/plsql/t_plsql_exceptions.htm *
************************************************************************/
DECLARE
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
commit;
END;
COUNT(*)
-------
200
DECLARE
TYPE num_data_typ IS TABLE OF bulk_tb.ran_num%TYPE;
BEGIN
FOR i in 1..200
LOOP
v_dat.EXTEND;
v_dat(v_dat.LAST) := i;
END LOOP;
v_dat(100) := NULL;
FORALL i IN v_dat.FIRST..v_dat.LAST
commit;
END;
/*
Error Message :
ORA-06512: at line 15
*/
sample2.sql --with exception part
DECLARE
BEGIN
FOR i in 1..200
LOOP
v_dat.EXTEND;
v_dat(v_dat.LAST) := i;
END LOOP;
v_dat(100) := NULL;
BEGIN
FORALL i IN v_dat.FIRST..v_dat.LAST
COMMIT;
EXCEPTION
END;
COUNT(*)
-------
99
SQL%BULK_EXCEPTIONS(i).ERROR_INDEX
Holds the iteration (not the subscript) of the original FORALL statement that raised the
exception.
the exception row must be found by looping through the original collection the correct
number of times.
SQL%BULK_EXCEPTIONS(i).ERROR_CODE
DECLARE
v_ex_count NUMBER(4);
abort_ex EXCEPTION;
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;
COMMIT;
EXCEPTION
v_ex_count := SQL%BULK_EXCEPTIONS.COUNT;
END LOOP;
END;
END;
/*
Sample output:
*/
SELECT COUNT(*) FROM bulk_tb;
COUNT(*)
-------
198
SAVE EXCEPTIONS clause being removed, in the above script now traps a different error number.
/*
Sample output:
*/
COUNT(*)
-------
99
SELECT COUNT(*) FROM bulk_tb;
0 Add a comment
SEP
29
/************************************************************************
************************************************************************/
END LOOP;
commit;
END;
DECLARE
CURSOR PROD_DTLS_C IS
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
END IF;
END LOOP;
CLOSE PROD_DTLS_C;
COMMIT;
END;
BEGIN
END LOOP;
commit;
END;
DECLARE
CURSOR PROD_DTLS_C IS
V_PID PROD_DETAILS.P_ID%TYPE;
V_PRDNAME PROD_DETAILS.P_NAME%TYPE;
BEGIN
OPEN PROD_DTLS_C;
LOOP
IF PROD_DTLS_C%NOTFOUND THEN
EXIT;
ELSE
UPDATE PROD_DETAILS P
END IF;
COMMIT;
END LOOP;
CLOSE PROD_DTLS_C;
--COMMIT;
END;
0 Add a comment
MAY
28
FROM Dual;
FROM Dual;
SAL_DETAILS
---------------------------------------
FROM Dual;
Info
---------------------------------------
SELECT q'[some test ' some test ' some text ']' AS "In 10g"
FROM dual;
In 10g
------------------------------------
The '_' wild card character is used to match exactly one character
WITH mail_ids AS
UNION
----------------------------------
an_murugappan@gmail.com
WITH mail_ids AS
UNION
UNION
----------------------------------
an%murugappan@gmail.com
'23'
----
23
'&A'
----
&a
'&A'
----
&a
SQL> SET SCAN ON;
'45'
----
45
0 Add a comment
MAY
28
Data Manipulation Language (DML) statements are used for managing data within schema
objects. Some examples:
DELETE - deletes all records from a table, the space for the records remain
MERGE - UPSERT operation (insert or update)
prod_id NUMBER(4) ,
prod_name VARCHAR2(30) ,
comments VARCHAR2(300)
);
no_data_found
INSERT
---------------------------------------------------------------------------
PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
VALUES(103,'Moto X','11-May-14','13-May-14');
VALUES(103,'Moto X','11-May-14','13-May-14');
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--If you want to insert NULL value you can ignore that column at the time of inserting
VALUES(104,'Moto G','19-May-14','22-May-14',NULL);
SELECT * FROM prod_details;
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
--if you are not providing values for order_dt and deliver_dt column default value can be taken.
---------------------------------------------------------------------------
----------------------------------------------------------------------------
---------------------------------------------------------------------------
COUNT(*)
-------
WHERE id = 900;
COUNT(*)
-------
COUNT(*)
-------
3
DROP TABLE test_tab;
UPDATE
Syntax :
UPDATE table_name
column2_name = column2_value,
column2_name = column3_value,
columnn_name = columnn_value
WHERE condition(s);
---------------------------------------------------------------------------
----------------------------------------------------------------------
---------------------------------------------------------------------------
UPDATE prod_details ps
SELECT *
FROM prod_details ps
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--If you try to execute update statement without condition it'll update all the records inside the
table.
UPDATE prod_details ps
SELECT *
---------------------------------------------------------------------------
---------------------------------------------------------------------------
----------------------------------------------------------------------
--if your update text contain ' means you can use following metnod (use '')
UPDATE prod_details ps
FROM prod_details ps
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
DELETE
Syntax:
WHERE condition(s);
---------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------
100 Apple iphone 5s 5/21/2014 5/24/2014 Some product's are not available
---------------------------------------------------------------------------------------
no rows selected.
0 Add a comment
MAY
28
Data Definition Language (DDL) statements are used to define the database structure or schema.
Some examples:
ADD
RENAME
MODIFY
DROP
Creating Table
--------------------------------------------------------------------------
--------------------------------------------------------------------------
S: -84 to 127
VARCHAR2 4000 Bytes we can store 0-9, a-z, A-Z and special characters
--------------------------------------------------------------------------
CREATE
RENAME
DROP
TRUNCATE
--creating table
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)
-----------------------------
ADD : Used to add a column after the table hase been created
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)
-----------------------------
SYNTAX
ADD (
column_1 Data_type(size),
column_2 Data_type(size),
column_3 Data_type(size),
column_4 Data_type(size)
);
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.
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)
-----------------------------
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.
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)
-----------------------------
SYNTAX
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
DROP : Used to drop the tabel (Data + stucture of the table get removed from the database )
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
Posted 28th May 2014 by Unknown
0 Add a comment
MAY
28
Statements in Oracle
DDL statements are used to define the database structure or schema. Some examples:
ADD
RENAME
MODIFY
DROP
DML statements are used for managing data within schema objects. Some examples:
DELETE - deletes all records from a table, the space for the records remain
TCL statements are used to manage the changes made by DML statements. It allows
statements to be grouped together into logical transactions.
SAVEPOINT - identify a point in a transaction to which you can later roll back
0 Add a comment
MAY
19
roll_no NUMBER(4) ,
Name VARCHAR2(30) ,
dept_cd VARCHAR2(20) ,
total_marks NUMBER(3)
);
BEGIN
END;
DECODE
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',
'IT',
'Information Technology',
FROM students;
Sample Output
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
CASE
Example
SELECT roll_no,
NAME,
dept_cd,
total_marks,
CASE
'A Grade'
WHEN total_marks > 400 THEN
'B Grade'
'C Grade'
ELSE
'U Grade'
END AS "GRADE"
FROM students;
-----------------------------------------------
-----------------------------------------------
-----------------------------------------------
Interview Questions:
What is DECODE?
What is CASE?
0 Add a comment
MAY
19
Sub Query
Want to fetch the person Who are all getting salary more than Neena's salary ?
From Employees
Sub Query :
From Employees
);
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
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)
From Employees
);
From Employees
);
From Employees
);
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
FROM
Dual;
Where Department_id = 60
);
SELECT AVG(salary)
FROM employees
);
0 Add a comment
Loading
search
JUL
20
--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
Display all the customer who have placed more number of orders by using INLINE view
( custm_id NUMBER ,
custm_nm VARCHAR2(30) ,
ttl_amt NUMBER(7,2)
);
BEGIN
COMMIT;
END;
SELECT c.*
FROM customer_order_det_tb c;
--------------------------------------------
--------------------------------------------
--------------------------------------------
--Writing a Quer to display all the customer who have placed maximum number of order
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
--------------------------------
100 Murugappan 2
102 Ramesh 2
101 Raja 1
--------------------------------
----------
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;
****************************************/
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
) query1,
) query2
-------------------------------
-------------------------------
100 Murugappan 2
102 Ramesh 2
-------------------------------
FROM employees e
Example :
--in 11g
SELECT *
FROM departments d
--in 12c
SELECT *
FROM departments d
);
--in 11g
WITH t
AS
( SELECT LEVEL a
FROM dual
SELECT *
FROM t, (SELECT *
FROM employees
);
WITH t
AS
SELECT * FROM t,
LATERAL(SELECT *
FROM employees
0 Add a comment
JAN
23
--creating table
CREATE TABLE employee_data
eid NUMBER(4),
ename VARCHAR2(30),
depno NUMBER(3),
salary NUMBER(8)
);
BEGIN
--Inserting records
COMMIT;
END;
/
SELECT MAX(salary)
FROM employee_data
FROM employee_data);
SELECT MIN(salary)
FROM employee_data
SELECT MIN(salary)
FROM employee_data
--query to select all the details of the employee whose getting nth maximum salary
SELECT *
rownum rn
FROM (SELECT *
FROM employee_data
WHERE rn = 9;
--same query using row_numbr( ) function
SELECT *
WHERE rank = 9;
SELECT *
WHERE rank = 4;
SELECT *
WHERE rank = 4;
--query to display display maximum salary in all the department
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
--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
SELECT employee_id,
first_name,
salary
FROM employees
7 View comments
JAN
22
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.
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.
Elapsed: 00:00:14.01
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.
0 Add a comment
DEC
21
Constraints
Format : [part_of_project_name-table_name-column_name-constraint_type]
Format : sys_cn
Example : SYS_C405323
Types
Primary Key
Ex : Employee_id, Student_id
Unique Key
Ex : Contact_no, email
Foreign Key
c1(pk) : 1 2 3
Not Null
Check
------------------------------------
Duplicate NULL
------------------------------------
Primary Key X X
------------------------------------
S_id Number(2),
s_mail Varchar2(30),
s_gender char(1),
s_did Number(3),
);
DESC my_stu_details;
------------------------------------
------------------------------------
S_ID NUMBER(2)
S_NAME VARCHAR2(30)
S_MAIL VARCHAR2(30) Y
S_GENDER CHAR(1) Y
S_DID NUMBER(3) Y
------------------------------------
--Duplicate Check
--Null Check
Insert into 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
--------------------------------------------------------
------------------------------------------------------------
-------------------------------------------------
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
-------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
SELECT c.owner,
c.constraint_name,
c.constraint_type,
c.table_name,
c.r_constraint_name,
c.status
FROM user_constraints c
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
HR SYS_C004023 C MY_STU_DETAILS ENABLED
------------------------------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
Creating Composite Primary Key
In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.
Interview Questions
Which Data Dictionary table contains information about constraint with corresponding column
name?
1 View comments
good
Reply
DEC
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 :
--Example 1:
BEGIN
commit;
END;
listagg(product,
',') within
FROM test_ins
GROUP BY empid;
-->-- Example 2
FROM employees
GROUP BY department_id;
0 Add a comment
NOV
8
Condition and Looping Statement
IF
IF ELSE
Multiple IF ELSE
LOOP
FOR LOOP
WHILE LOOP
BEGIN
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;
UPDATE test_udt t
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;
UPDATE test_udt t
ELSE
UPDATE test_udt t
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;
v_salary := v_salary+10005;
ELSE
v_salary := v_salary+20007;
END IF;
UPDATE test_udt t
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');
v_salary := 2000;
dbms_output.put_line('2 inside');
v_salary := 3000;
dbms_output.put_line('3 inside');
v_salary := 4000;
dbms_output.put_line('4 inside');
END IF;
UPDATE test_udt t
commit;
END;
LOOP
--syntax
LOOP
--statements
--increment
--exit statement
END LOOP;
i NUMBER := 1;
x VARCHAR2(3);
BEGIN
LOOP
x := lpad(i,3,'0');
i := i+1;
IF MOD(i,100) = 0 THEN
commit;
dbms_output.put_line('commit executed');
END IF;
END LOOP;
END;
FOR LOOP
BEGIN
FOR I in 1..5
LOOP
END LOOP;
END;
BEGIN
LOOP
END LOOP;
END;
WHILE LOOP
DECLARE
i_val NUMBER:=0;
BEGIN
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
0 Add a comment
OCT
21
Bulk Collect
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.
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
SELECT * FROM product_details;
BEGIN
OPEN proddt_cur;
INTO dta;
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta alldata_typ;
BEGIN
END LOOP;
END;
-->-- LIMIT in Bulk collect --<--
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta1 alldata_typ1;
dta2 alldata_typ2;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END LOOP;
END;
/
0 Add a comment
OCT
21
Ref Cursor
This is unconstrained cursor which will return different types depends upon the user input.
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.
AS
BEGIN
OPEN dep_det_c
FOR
END;
DECLARE
dep_det_c SYS_REFCURSOR;
tab_data dep_details%ROWTYPE;
BEGIN
ref_c_sp(dep_det_c);
LOOP
END LOOP;
CLOSE dep_det_c;
END;
/*sample output*/
Department Name : Admin
Department Name : HR
0 Add a comment
OCT
21
Cursor
SQL Private work Area where the query get passed and executed.
Types
******
Implicit(SQL)
Explicit
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
Cursor Stages
**************
OPEN cursor_name
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
Cursor Declaration
DECLARE
CURSOR <cursor_name>
IS
<SELECT statement>
BEGIN
END;
Cursor Loop
Loop
While Loop
For Loop
Cursor Clauses
Return
For update
Where current of
Bulk collect
p_id NUMBER,
p_name VARCHAR2(30),
p_order_dt DATE
);
BEGIN
FOR i IN 1 .. 75 LOOP
END LOOP;
commit;
END;
---------------------------------------------
---------------------------------------------
---------------------------------------------
----------------------------------------------
Implicit Cursor
----------------------------------------------
----------------------------------------------
Explicit Cursor
----------------------------------------------
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
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
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
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*/
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
dbms_output.put_line('prod_detail_cur cursor Already closed');
END IF;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
FETCH prod_detail_cur
INTO all_data;
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
************************************************************
************************************************************
DECLARE
--cursor declaration
CURSOR prod_detail_cur IS
FOR i IN prod_detail_cur
LOOP
END LOOP;
END;
/*sample output*/
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.
BEGIN
commit;
END;
----------------------------
----------------------------
1 Admin 1010
2 HR 1010
3 Sales 1020
4 Marketing 1020
----------------------------
DECLARE
all_data dep_details%ROWTYPE;
BEGIN
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1010);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1020);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
END;
/*sample output*/
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
0 Add a comment
OCT
21
Handling Exception
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
Predefined Exception
*********************
Oracle has predefined several exceptions that correspond to the most common oracle errors.
------------------------------------------------------------------------
------------------------------------------------------------------------
DUP_VAL_ON_INDEX ORA-00001 -1
OTHERS
------------------------------------------------------------------------
v_result NUMBER;
BEGIN
EXCEPTION
END;
Single row SELECT returned no rows or your program referenced a deleted element in a nested
table
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
commit;
BEGIN
EXCEPTION
END;
v_id NUMBER;
BEGIN
EXCEPTION
END;
DECLARE
num1 NUMBER(2);
BEGIN
num1 := 345;
EXCEPTION
END;
-->-- CURSOR_ALREADY_OPEN --<--
BEGIN
COMMIT;
END;
DECLARE
cursor emp_c IS
all_data emp%ROWTYPE;
BEGIN
OPEN emp_c;
OPEN emp_c;
NULL;
CLOSE emp_c;
EXCEPTION
END;
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
User Defined Exception
**********************
User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,
DECLARE
gender_ex EXCEPTION;
BEGIN
RAISE gender_ex;
END IF;
dbms_output.put_line('Gender : '||v_gender);
EXCEPTION
END;
abort_ex EXCEPTION;
BEGIN
FOR i IN 1..100
LOOP
BEGIN
IF mod(i,10)=0 THEN
RAISE abort_ex;
END IF;
EXCEPTION
NULL;
END;
END LOOP;
COMMIT;
END;
********************
SQLCODE returns the current error code, and SQLERRM returns the current error message
text;
SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.
DECLARE
v_id NUMBER;
BEGIN
dbms_output.put_line(v_id);
EXCEPTION
END;
/*sample output*/
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:
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
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 :
DECLARE
BEGIN
END IF;
END;
How to get the two table data without using Joins and sub query,union?
Reply
OCT
Package
I) specification
II) Body
5. Overloading
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_sal_sp;
BEGIN
END;
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
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_hdt_sp;
BEGIN
END;
RETURN NUMBER
IS
v_c NUMBER;
BEGIN
v_c := p_a + p_b;
RETURN v_c;
END;
--Specification Part
IS
RETURN NUMBER;
END emp_pkg ;
--Body Part
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
EXCEPTION
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_hdt_sp;
IS
v_c NUMBER;
BEGIN
RETURN v_c;
END;
END emp_pkg;
BEGIN
emp_pkg.emp_sal_sp(120);
END;
as
RETURN NUMBER;
IS
FROM employees;
End all_detail;
as
PROCEDURE emp2sal (a IN NUMBER)
AS
BEGIN
SELECT salary
INTO c
FROM Employees
WHERE Employee_id = a;
EXCEPTION
END emp2sal;
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
END emp2exep;
RETURN NUMBER
AS
BEGIN
c := a+b;
RETURN C;
END;
End all_detail;
IS
END global_constant;
BEGIN
END;
DECLARE
PROCEDURE P3;
PROCEDURE P1 IS
BEGIN
p2;
END P1;
PROCEDURE P2 IS
BEGIN
dbms_output.put_line('From procedure p2');
p3;
END P2;
PROCEDURE P3 IS
BEGIN
END P3;
BEGIN
p1;
END;
sample output:
From procedure p1
From procedure p2
From procedure p3
Interview Questions:
What is package?
Advantage of package
0 Add a comment
OCT
p_id NUMBER(3),
p_nm VARCHAR2(30),
p_qty NUMBER(8),
order_dt DATE
);
BEGIN
commit;
END;
------------------------------------
------------------------------------
DECLARE
v_name VARCHAR2(4);
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
DECLARE
v_name VARCHAR2(5);
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
VALUES
(106,
'name6',
700,
'26-Dec-12');
commit;
106 name6 700 12/26/2012
DECLARE
v_name VARCHAR2(5);
BEGIN
FROM product_details
--error
END;
DECLARE
v_name product_details.p_nm%TYPE;
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
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
END;
--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
END;
dept_id number(3) ,
dept_name varchar2(30),
dept_manager_name varchar2(30)
);
+------------+-----------------------+-----------------
| 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
END;
/
1 Row(s) get updated
---------------------------------------------------
---------------------------------------------------
| 20 | dept2 | manager_name2 |
---------------------------------------------------
Interview Question :
0 Add a comment
SEP
29
BULK Exceptions
/************************************************************************
* Reference : http://www.dba-oracle.com/plsql/t_plsql_exceptions.htm *
************************************************************************/
DECLARE
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
commit;
END;
COUNT(*)
-------
200
BEGIN
FOR i in 1..200
LOOP
v_dat.EXTEND;
v_dat(v_dat.LAST) := i;
END LOOP;
v_dat(100) := NULL;
FORALL i IN v_dat.FIRST..v_dat.LAST
commit;
END;
/*
Error Message :
ORA-06512: at line 15
*/
DECLARE
BEGIN
FOR i in 1..200
LOOP
v_dat.EXTEND;
v_dat(v_dat.LAST) := i;
END LOOP;
v_dat(100) := NULL;
BEGIN
FORALL i IN v_dat.FIRST..v_dat.LAST
COMMIT;
EXCEPTION
WHEN OTHERS THEN
END;
END;
COUNT(*)
-------
99
SQL%BULK_EXCEPTIONS(i).ERROR_INDEX
Holds the iteration (not the subscript) of the original FORALL statement that raised the
exception.
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,
DECLARE
v_ex_count NUMBER(4);
abort_ex EXCEPTION;
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;
BEGIN
COMMIT;
EXCEPTION
v_ex_count := SQL%BULK_EXCEPTIONS.COUNT;
END LOOP;
END;
END;
/*
Sample output:
*/
SELECT COUNT(*) FROM bulk_tb;
COUNT(*)
-------
198
SAVE EXCEPTIONS clause being removed, in the above script now traps a different error number.
/*
Sample output:
*/
COUNT(*)
-------
99
0 Add a comment
SEP
29
/************************************************************************
************************************************************************/
create table prod_details(p_id VARCHAR2(30), P_name VARCHAR2(30));
BEGIN
END LOOP;
commit;
END;
DECLARE
CURSOR PROD_DTLS_C IS
V_PID PROD_DETAILS.P_ID%TYPE;
V_PRDNAME PROD_DETAILS.P_NAME%TYPE;
BEGIN
OPEN PROD_DTLS_C;
LOOP
IF PROD_DTLS_C%NOTFOUND THEN
EXIT;
ELSE
UPDATE PROD_DETAILS P
END IF;
END LOOP;
CLOSE PROD_DTLS_C;
COMMIT;
END;
BEGIN
--Inserting data into prod_details table
END LOOP;
commit;
END;
DECLARE
CURSOR PROD_DTLS_C IS
V_PID PROD_DETAILS.P_ID%TYPE;
V_PRDNAME PROD_DETAILS.P_NAME%TYPE;
BEGIN
OPEN PROD_DTLS_C;
LOOP
IF PROD_DTLS_C%NOTFOUND THEN
EXIT;
ELSE
UPDATE PROD_DETAILS P
END IF;
COMMIT;
END LOOP;
CLOSE PROD_DTLS_C;
--COMMIT;
END;
0 Add a comment
MAY
28
FROM Dual;
FROM Dual;
SAL_DETAILS
---------------------------------------
FROM Dual;
Info
---------------------------------------
SELECT q'[some test ' some test ' some text ']' AS "In 10g"
FROM dual;
In 10g
------------------------------------
The '_' wild card character is used to match exactly one character
WITH mail_ids AS
UNION
----------------------------------
an_murugappan@gmail.com
WITH mail_ids AS
UNION
UNION
----------------------------------
an%murugappan@gmail.com
'23'
----
23
'&A'
----
&a
'&A'
----
&a
'45'
----
45
0 Add a comment
MAY
28
Data Manipulation Language (DML) statements are used for managing data within schema
objects. Some examples:
DELETE - deletes all records from a table, the space for the records remain
prod_id NUMBER(4) ,
prod_name VARCHAR2(30) ,
comments VARCHAR2(300)
);
no_data_found
INSERT
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
VALUES(103,'Moto X','11-May-14','13-May-14');
ORA-00947 : not enough values
VALUES(103,'Moto X','11-May-14','13-May-14');
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--If you want to insert NULL value you can ignore that column at the time of inserting
VALUES(104,'Moto G','19-May-14','22-May-14',NULL);
SELECT * FROM prod_details;
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
--if you are not providing values for order_dt and deliver_dt column default value can be taken.
---------------------------------------------------------------------------
----------------------------------------------------------------------------
---------------------------------------------------------------------------
COUNT(*)
-------
WHERE id = 900;
COUNT(*)
-------
COUNT(*)
-------
3
DROP TABLE test_tab;
UPDATE
Syntax :
UPDATE table_name
column2_name = column2_value,
column2_name = column3_value,
columnn_name = columnn_value
WHERE condition(s);
---------------------------------------------------------------------------
----------------------------------------------------------------------
---------------------------------------------------------------------------
UPDATE prod_details ps
SELECT *
FROM prod_details ps
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--If you try to execute update statement without condition it'll update all the records inside the
table.
UPDATE prod_details ps
SELECT *
---------------------------------------------------------------------------
---------------------------------------------------------------------------
----------------------------------------------------------------------
--if your update text contain ' means you can use following metnod (use '')
UPDATE prod_details ps
SELECT *
FROM prod_details ps
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
DELETE
Syntax:
WHERE condition(s);
---------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------
100 Apple iphone 5s 5/21/2014 5/24/2014 Some product's are not available
---------------------------------------------------------------------------------------
no rows selected.
0 Add a comment
MAY
28
Data Definition Language (DDL) statements are used to define the database structure or schema.
Some examples:
ADD
RENAME
MODIFY
DROP
Creating Table
--------------------------------------------------------------------------
--------------------------------------------------------------------------
S: -84 to 127
VARCHAR2 4000 Bytes we can store 0-9, a-z, A-Z and special characters
--------------------------------------------------------------------------
CREATE
RENAME
DROP
TRUNCATE
--creating table
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)
-----------------------------
ADD : Used to add a column after the table hase been created
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)
-----------------------------
SYNTAX
ADD (
column_1 Data_type(size),
column_2 Data_type(size),
column_3 Data_type(size),
column_4 Data_type(size)
);
-----------------------------
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.
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)
-----------------------------
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.
-----------------------------
NAME TYPE
-----------------------------
NAME VARCHAR2(30)
PHONE NUMBER(10)
GENDER CHAR(1)
DOB DATE
MAKE_DTM TIMESTAMP(6)
EMAIL_ID VARCHAR2(30)
-----------------------------
SYNTAX
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
DROP : Used to drop the tabel (Data + stucture of the table get removed from the database )
0 Add a comment
MAY
28
Statements in Oracle
DDL statements are used to define the database structure or schema. Some examples:
ADD
RENAME
MODIFY
DROP
DML statements are used for managing data within schema objects. Some examples:
DELETE - deletes all records from a table, the space for the records remain
TCL statements are used to manage the changes made by DML statements. It allows
statements to be grouped together into logical transactions.
0 Add a comment
MAY
19
roll_no NUMBER(4) ,
Name VARCHAR2(30) ,
dept_cd VARCHAR2(20) ,
total_marks NUMBER(3)
);
BEGIN
END;
DECODE
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',
'IT',
'Information Technology',
Sample Output
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
CASE
Example
SELECT roll_no,
NAME,
dept_cd,
total_marks,
CASE
WHEN total_marks > 500 THEN
'A Grade'
'B Grade'
'C Grade'
ELSE
'U Grade'
END AS "GRADE"
FROM students;
-----------------------------------------------
-----------------------------------------------
-----------------------------------------------
Interview Questions:
What is DECODE?
What is CASE?
Difference between CASE and DECODE? Which one is faster?
0 Add a comment
MAY
19
Sub Query
Want to fetch the person Who are all getting salary more than Neena's salary ?
Sub Query :
From Employees
);
Sub Query Returns more than one value it is called as Multi row sub query
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
);
From Employees
);
From Employees
);
From Employees
Where salary > All(
);
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
FROM
Dual;
Where Department_id = 60
);
SELECT AVG(salary)
FROM employees
);
Loading
search
JUL
20
--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
, AVG(b.salary) avg_sal
FROM employees b
GROUP BY b.department_id
)b
Display all the customer who have placed more number of orders by using INLINE view
( custm_id NUMBER ,
custm_nm VARCHAR2(30) ,
ttl_amt NUMBER(7,2)
);
BEGIN
COMMIT;
END;
SELECT c.*
FROM customer_order_det_tb c;
--------------------------------------------
--------------------------------------------
--------------------------------------------
--Writing a Quer to display all the customer who have placed maximum number of order
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
ORDER BY total_odr DESC;
--------------------------------
--------------------------------
100 Murugappan 2
102 Ramesh 2
101 Raja 1
--------------------------------
----------
total_odr
----------
----------
Inline view to find all the customers who have placed maximum number of orders
/****************************************
Syntax
WHERE contition;
****************************************/
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
) query1,
) query2
-------------------------------
-------------------------------
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
FROM employees e
Example :
--in 11g
SELECT *
FROM departments d
--in 12c
SELECT *
FROM departments d
);
--in 11g
WITH t
AS
( SELECT LEVEL a
FROM dual
SELECT *
FROM t, (SELECT *
FROM employees
);
ORA-00904: "T"."A": invalid Identifier
--in 12c
WITH t
AS
SELECT * FROM t,
LATERAL(SELECT *
FROM employees
0 Add a comment
JAN
23
eid NUMBER(4),
ename VARCHAR2(30),
depno NUMBER(3),
salary NUMBER(8)
);
BEGIN
--Inserting records
END;
SELECT MAX(salary)
FROM employee_data
FROM employee_data);
FROM employee_data
SELECT MIN(salary)
FROM employee_data
--query to select all the details of the employee whose getting nth maximum salary
SELECT *
rownum rn
FROM (SELECT *
FROM employee_data
ORDER BY salary DESC) emp)
WHERE rn = 9;
SELECT *
WHERE rank = 9;
SELECT *
WHERE rank = 4;
SELECT *
WHERE rank = 4;
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
--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
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
JAN
22
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.
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.
14 rows selected.
Elapsed: 00:00:14.01
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.
0 Add a comment
DEC
21
Constraints
Format : [part_of_project_name-table_name-column_name-constraint_type]
Format : sys_cn
Example : SYS_C405323
Types
Primary Key
Ex : Employee_id, Student_id
Unique Key
Ex : Contact_no, email
Foreign Key
c1(pk) : 1 2 3
Not Null
Check
You can check your own condition
------------------------------------
Duplicate NULL
------------------------------------
Primary Key X X
------------------------------------
S_id Number(2),
s_mail Varchar2(30),
s_gender char(1),
s_did Number(3),
);
DESC my_stu_details;
------------------------------------
------------------------------------
S_ID NUMBER(2)
S_NAME VARCHAR2(30)
S_MAIL VARCHAR2(30) Y
S_GENDER CHAR(1) Y
S_DID NUMBER(3) Y
------------------------------------
--Duplicate Check
--------------------------------------------------------
--------------------------------------------------------
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
--------------------------------------------------------
------------------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
-------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
ON DELETE CASCADE
SELECT c.owner,
c.constraint_name,
c.constraint_type,
c.table_name,
c.r_constraint_name,
c.status
FROM user_constraints c
------------------------------------------------------------------------------------
owner constraint_name constraint_type table_name r_constraint_name status
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
Creating Composite Primary Key
In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.
Interview Questions
What are all the type of constraint available in oracle?
Which Data Dictionary table contains information about constraint with corresponding column
name?
1 View comments
Reply
DEC
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 :
--Example 1:
BEGIN
commit;
END;
listagg(product,
',') within
FROM test_ins
GROUP BY empid;
-->-- Example 2
FROM employees
GROUP BY department_id;
0 Add a comment
NOV
IF
IF ELSE
Multiple IF ELSE
LOOP
FOR LOOP
WHILE LOOP
BEGIN
Commit;
END;
IF
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 1;
UPDATE test_udt t
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;
UPDATE test_udt t
ELSE
UPDATE test_udt t
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;
v_salary := v_salary+10005;
ELSE
v_salary := v_salary+20007;
END IF;
UPDATE test_udt t
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');
v_salary := 2000;
dbms_output.put_line('2 inside');
v_salary := 3000;
dbms_output.put_line('3 inside');
dbms_output.put_line('4 inside');
END IF;
UPDATE test_udt t
commit;
END;
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');
i := i+1;
IF MOD(i,100) = 0 THEN
commit;
dbms_output.put_line('commit executed');
END IF;
END LOOP;
END;
BEGIN
FOR I in 1..5
LOOP
END LOOP;
END;
BEGIN
LOOP
END LOOP;
END;
WHILE LOOP
DECLARE
i_val NUMBER:=0;
BEGIN
WHILE (i_val < 11)
LOOP
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
0 Add a comment
OCT
21
Bulk Collect
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.
DECLARE
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
INTO dta;
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta alldata_typ;
BEGIN
END;
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END;
/
-->-- Multiple fetches in INTO clause --<--
DECLARE
dta1 alldata_typ1;
dta2 alldata_typ2;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END LOOP;
END;
0 Add a comment
OCT
21
Ref Cursor
This is unconstrained cursor which will return different types depends upon the user input.
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
END;
DECLARE
dep_det_c SYS_REFCURSOR;
tab_data dep_details%ROWTYPE;
BEGIN
ref_c_sp(dep_det_c);
LOOP
END LOOP;
CLOSE dep_det_c;
END;
/*sample output*/
Department Name : HR
0 Add a comment
OCT
21
Cursor
SQL Private work Area where the query get passed and executed.
Types
******
Implicit(SQL)
Explicit
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
Cursor Stages
**************
OPEN cursor_name
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
Cursor Declaration
DECLARE
CURSOR <cursor_name>
IS
<SELECT statement>
BEGIN
END;
Cursor Loop
Loop
While Loop
For Loop
Cursor Clauses
Return
For update
Where current of
Bulk collect
p_id NUMBER,
p_name VARCHAR2(30),
p_order_dt DATE
);
BEGIN
FOR i IN 1 .. 75 LOOP
commit;
END;
---------------------------------------------
---------------------------------------------
---------------------------------------------
----------------------------------------------
Implicit Cursor
----------------------------------------------
----------------------------------------------
Explicit Cursor
----------------------------------------------
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
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
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
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
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
END IF;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
FETCH prod_detail_cur
INTO all_data;
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
************************************************************
************************************************************
DECLARE
--cursor declaration
CURSOR prod_detail_cur IS
SELECT * FROM product_details WHERE ROWNUM <= 5;
BEGIN
FOR i IN prod_detail_cur
LOOP
END LOOP;
END;
/*sample output*/
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.
BEGIN
commit;
END;
----------------------------
----------------------------
1 Admin 1010
2 HR 1010
3 Sales 1020
4 Marketing 1020
----------------------------
DECLARE
all_data dep_details%ROWTYPE;
BEGIN
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1010);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1020);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
END;
/*sample output*/
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
0 Add a comment
OCT
21
Handling Exception
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
Predefined Exception
*********************
Oracle has predefined several exceptions that correspond to the most common oracle errors.
------------------------------------------------------------------------
------------------------------------------------------------------------
DUP_VAL_ON_INDEX ORA-00001 -1
OTHERS
------------------------------------------------------------------------
v_result NUMBER;
BEGIN
EXCEPTION
END;
Single row SELECT returned no rows or your program referenced a deleted element in a nested
table
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
commit;
BEGIN
EXCEPTION
END;
v_id NUMBER;
BEGIN
EXCEPTION
END;
DECLARE
num1 NUMBER(2);
BEGIN
num1 := 345;
EXCEPTION
END;
-->-- CURSOR_ALREADY_OPEN --<--
BEGIN
COMMIT;
END;
DECLARE
cursor emp_c IS
all_data emp%ROWTYPE;
BEGIN
OPEN emp_c;
OPEN emp_c;
NULL;
CLOSE emp_c;
EXCEPTION
END;
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
User Defined Exception
**********************
User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,
DECLARE
gender_ex EXCEPTION;
BEGIN
RAISE gender_ex;
END IF;
dbms_output.put_line('Gender : '||v_gender);
EXCEPTION
END;
abort_ex EXCEPTION;
BEGIN
FOR i IN 1..100
LOOP
BEGIN
IF mod(i,10)=0 THEN
RAISE abort_ex;
END IF;
EXCEPTION
NULL;
END;
END LOOP;
COMMIT;
END;
SQLCODE returns the current error code, and SQLERRM returns the current error message
text;
SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.
DECLARE
v_id NUMBER;
BEGIN
dbms_output.put_line(v_id);
EXCEPTION
END;
/*sample output*/
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:
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
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 :
DECLARE
BEGIN
END IF;
END;
How to get the two table data without using Joins and sub query,union?
Reply
OCT
Package
I) specification
II) Body
5. Overloading
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_sal_sp;
BEGIN
END;
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_hdt_sp;
BEGIN
END;
RETURN NUMBER
IS
v_c NUMBER;
BEGIN
RETURN v_c;
END;
--Specification Part
IS
RETURN NUMBER;
END emp_pkg ;
--Body Part
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
EXCEPTION
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
EXCEPTION
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
RETURN v_c;
END;
END emp_pkg;
BEGIN
emp_pkg.emp_sal_sp(120);
END;
as
RETURN NUMBER;
IS
FROM employees;
End all_detail;
AS
BEGIN
SELECT salary
INTO c
FROM Employees
WHERE Employee_id = a;
EXCEPTION
END emp2sal;
AS
BEGIN
SELECT Round(Months_between(sysdate,hire_date)/12)
INTO c
FROM Employees
WHERE Employee_id = a;
EXCEPTION
END emp2exep;
RETURN NUMBER
AS
BEGIN
c := a+b;
RETURN C;
END;
End all_detail;
IS
mile_2_kilo CONSTANT NUMBER := 1.6093;
END global_constant;
BEGIN
END;
DECLARE
PROCEDURE P3;
PROCEDURE P1 IS
BEGIN
p2;
END P1;
PROCEDURE P2 IS
BEGIN
p3;
END P2;
PROCEDURE P3 IS
BEGIN
END P3;
BEGIN
p1;
END;
sample output:
From procedure p1
From procedure p2
From procedure p3
Interview Questions:
What is package?
Advantage of package
0 Add a comment
OCT
p_id NUMBER(3),
p_nm VARCHAR2(30),
p_qty NUMBER(8),
order_dt DATE
);
BEGIN
commit;
END;
------------------------------------
------------------------------------
DECLARE
v_name VARCHAR2(4);
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
DECLARE
v_name VARCHAR2(5);
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
VALUES
(106,
'name6',
700,
'26-Dec-12');
commit;
106 name6 700 12/26/2012
DECLARE
v_name VARCHAR2(5);
BEGIN
FROM product_details
--error
END;
DECLARE
v_name product_details.p_nm%TYPE;
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
WHERE p_id = 106;
END;
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
END;
--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;
END;
dept_id number(3) ,
dept_name varchar2(30),
dept_manager_name varchar2(30)
);
+------------+-----------------------+-----------------
| 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
END;
/
1 Row(s) get updated
---------------------------------------------------
---------------------------------------------------
| 20 | dept2 | manager_name2 |
---------------------------------------------------
Interview Question :
SEP
29
BULK Exceptions
/************************************************************************
* Reference : http://www.dba-oracle.com/plsql/t_plsql_exceptions.htm *
************************************************************************/
DECLARE
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
commit;
END;
COUNT(*)
-------
200
BEGIN
FOR i in 1..200
LOOP
v_dat.EXTEND;
v_dat(v_dat.LAST) := i;
END LOOP;
v_dat(100) := NULL;
FORALL i IN v_dat.FIRST..v_dat.LAST
commit;
END;
/*
Error Message :
*/
DECLARE
BEGIN
FOR i in 1..200
LOOP
v_dat.EXTEND;
v_dat(v_dat.LAST) := i;
END LOOP;
v_dat(100) := NULL;
BEGIN
FORALL i IN v_dat.FIRST..v_dat.LAST
COMMIT;
EXCEPTION
END;
END;
COUNT(*)
-------
99
SQL%BULK_EXCEPTIONS(i).ERROR_INDEX
Holds the iteration (not the subscript) of the original FORALL statement that raised the
exception.
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,
DECLARE
v_ex_count NUMBER(4);
abort_ex EXCEPTION;
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;
BEGIN
COMMIT;
EXCEPTION
v_ex_count := SQL%BULK_EXCEPTIONS.COUNT;
END LOOP;
END;
END;
/*
Sample output:
COUNT(*)
-------
198
SAVE EXCEPTIONS clause being removed, in the above script now traps a different error number.
/*
Sample output:
*/
-------
99
0 Add a comment
SEP
29
/************************************************************************
************************************************************************/
create table prod_details(p_id VARCHAR2(30), P_name VARCHAR2(30));
BEGIN
END LOOP;
commit;
END;
DECLARE
CURSOR PROD_DTLS_C IS
V_PID PROD_DETAILS.P_ID%TYPE;
V_PRDNAME PROD_DETAILS.P_NAME%TYPE;
BEGIN
OPEN PROD_DTLS_C;
LOOP
IF PROD_DTLS_C%NOTFOUND THEN
EXIT;
ELSE
UPDATE PROD_DETAILS P
END IF;
END LOOP;
CLOSE PROD_DTLS_C;
COMMIT;
END;
END LOOP;
commit;
END;
DECLARE
CURSOR PROD_DTLS_C IS
V_PID PROD_DETAILS.P_ID%TYPE;
V_PRDNAME PROD_DETAILS.P_NAME%TYPE;
BEGIN
OPEN PROD_DTLS_C;
LOOP
EXIT;
ELSE
UPDATE PROD_DETAILS P
END IF;
COMMIT;
END LOOP;
CLOSE PROD_DTLS_C;
--COMMIT;
END;
0 Add a comment
MAY
28
FROM Dual;
FROM Dual;
SAL_DETAILS
---------------------------------------
Info
---------------------------------------
SELECT q'[some test ' some test ' some text ']' AS "In 10g"
FROM dual;
In 10g
------------------------------------
The '_' wild card character is used to match exactly one character
WITH mail_ids AS
(
SELECT 'an.murugappan@gmail.com' mail FROM Dual
UNION
UNION
----------------------------------
an_murugappan@gmail.com
WITH mail_ids AS
UNION
UNION
----------------------------------
an%murugappan@gmail.com
'23'
----
23
'&A'
----
&a
----
&a
'45'
----
45
0 Add a comment
MAY
28
Data Manipulation Language (DML) statements are used for managing data within schema
objects. Some examples:
INSERT - insert data into a table
DELETE - deletes all records from a table, the space for the records remain
prod_id NUMBER(4) ,
prod_name VARCHAR2(30) ,
comments VARCHAR2(300)
);
no_data_found
INSERT
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
VALUES(103,'Moto X','11-May-14','13-May-14');
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--If you want to insert NULL value you can ignore that column at the time of inserting
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
--if you are not providing values for order_dt and deliver_dt column default value can be taken.
---------------------------------------------------------------------------
----------------------------------------------------------------------------
100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black
---------------------------------------------------------------------------
COUNT(*)
-------
WHERE id = 900;
COUNT(*)
-------
COUNT(*)
-------
3
UPDATE
Syntax :
UPDATE table_name
column2_name = column2_value,
column2_name = column3_value,
columnn_name = columnn_value
WHERE condition(s);
---------------------------------------------------------------------------
----------------------------------------------------------------------
100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black
---------------------------------------------------------------------------
UPDATE prod_details ps
SELECT *
FROM prod_details ps
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--If you try to execute update statement without condition it'll update all the records inside the
table.
UPDATE prod_details ps
SELECT *
---------------------------------------------------------------------------
---------------------------------------------------------------------------
----------------------------------------------------------------------
--if your update text contain ' means you can use following metnod (use '')
UPDATE prod_details ps
SELECT *
FROM prod_details ps
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
DELETE
Syntax:
WHERE condition(s);
SELECT *
---------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------
100 Apple iphone 5s 5/21/2014 5/24/2014 Some product's are not available
---------------------------------------------------------------------------------------
no rows selected.
0 Add a comment
MAY
28
Data Definition Language (DDL) statements are used to define the database structure or schema.
Some examples:
ADD
RENAME
MODIFY
DROP
Creating Table
--------------------------------------------------------------------------
--------------------------------------------------------------------------
S: -84 to 127
VARCHAR2 4000 Bytes we can store 0-9, a-z, A-Z and special characters
--------------------------------------------------------------------------
CREATE
DROP
TRUNCATE
--creating table
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)
-----------------------------
ADD : Used to add a column after the table hase been created
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)
-----------------------------
SYNTAX
ADD (
column_1 Data_type(size),
column_2 Data_type(size),
column_3 Data_type(size),
column_4 Data_type(size)
);
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.
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)
-----------------------------
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.
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)
-----------------------------
SYNTAX
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
DROP : Used to drop the tabel (Data + stucture of the table get removed from the database )
DROP TABLE fnd_det;
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
0 Add a comment
MAY
28
Statements in Oracle
DDL statements are used to define the database structure or schema. Some examples:
ADD
RENAME
MODIFY
DROP
DML statements are used for managing data within schema objects. Some examples:
DELETE - deletes all records from a table, the space for the records remain
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
0 Add a comment
MAY
19
roll_no NUMBER(4) ,
Name VARCHAR2(30) ,
dept_cd VARCHAR2(20) ,
total_marks NUMBER(3)
);
BEGIN
END;
DECODE
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',
'IT',
'Information Technology',
'Default Value') AS "DEPARTMENT NAME"
FROM students;
Sample Output
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
CASE
Example
SELECT roll_no,
NAME,
dept_cd,
total_marks,
CASE
'A Grade'
'B Grade'
'C Grade'
ELSE
'U Grade'
END AS "GRADE"
FROM students;
-----------------------------------------------
-----------------------------------------------
-----------------------------------------------
Interview Questions:
What is DECODE?
What is CASE?
0 Add a comment
MAY
19
Sub Query
Want to fetch the person Who are all getting salary more than Neena's salary ?
From Employees
Sub Query :
From Employees
);
Sub Query Returns more than one value it is called as Multi row sub query
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
);
From Employees
);
From Employees
);
);
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
FROM
Dual;
Select Min(salary) From Employees;
Where Department_id = 60
);
SELECT AVG(salary)
FROM employees
);
Posted 19th May 2014 by Unknown
0 Add a comment
Loading
search
JUL
20
--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
, AVG(b.salary) avg_sal
FROM employees b
GROUP BY b.department_id
)b
Display all the customer who have placed more number of orders by using INLINE view
( custm_id NUMBER ,
custm_nm VARCHAR2(30) ,
ttl_amt NUMBER(7,2)
);
BEGIN
COMMIT;
END;
SELECT c.*
FROM customer_order_det_tb c;
--------------------------------------------
--------------------------------------------
--------------------------------------------
--Writing a Quer to display all the customer who have placed maximum number of order
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
--------------------------------
--------------------------------
100 Murugappan 2
102 Ramesh 2
101 Raja 1
--------------------------------
----------
total_odr
----------
----------
Inline view to find all the customers who have placed maximum number of orders
/****************************************
Syntax
WHERE contition;
****************************************/
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
) query1,
) query2
-------------------------------
-------------------------------
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
FROM employees e
Example :
--in 11g
FROM departments d
--in 12c
SELECT *
FROM departments d
);
--in 11g
WITH t
AS
( SELECT LEVEL a
FROM dual
SELECT *
FROM t, (SELECT *
FROM employees
--in 12c
WITH t
AS
SELECT * FROM t,
LATERAL(SELECT *
FROM employees
0 Add a comment
JAN
23
eid NUMBER(4),
ename VARCHAR2(30),
depno NUMBER(3),
salary NUMBER(8)
);
BEGIN
--Inserting records
COMMIT;
END;
SELECT MAX(salary)
FROM employee_data
FROM employee_data);
FROM employee_data
SELECT MIN(salary)
FROM employee_data
--query to select all the details of the employee whose getting nth maximum salary
SELECT *
rownum rn
FROM (SELECT *
FROM employee_data
WHERE rn = 9;
SELECT *
WHERE rank = 9;
SELECT *
WHERE rank = 4;
SELECT *
WHERE rank = 4;
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
--query to display all the employees who are all getting salary more than their department
average salary
SELECT employee_id,
first_name,
salary
--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,
first_name,
salary
FROM employees
JAN
22
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.
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.
14 rows selected.
Elapsed: 00:00:14.01
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.
0 Add a comment
DEC
21
Constraints
Format : [part_of_project_name-table_name-column_name-constraint_type]
Format : sys_cn
Example : SYS_C405323
Types
Primary Key
Not allowed Null value
Ex : Employee_id, Student_id
Unique Key
Ex : Contact_no, email
Foreign Key
c1(pk) : 1 2 3
Not Null
Check
You can check your own condition
------------------------------------
Duplicate NULL
------------------------------------
Primary Key X X
------------------------------------
S_id Number(2),
s_mail Varchar2(30),
s_gender char(1),
s_did Number(3),
Constraint my_stu_sid_pk PRIMARY KEY (s_id),
);
DESC my_stu_details;
------------------------------------
------------------------------------
S_ID NUMBER(2)
S_NAME VARCHAR2(30)
S_MAIL VARCHAR2(30) Y
S_GENDER CHAR(1) Y
S_DID NUMBER(3) Y
------------------------------------
--Duplicate Check
--------------------------------------------------------
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
--------------------------------------------------------
------------------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
-------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
ON DELETE CASCADE
SELECT c.owner,
c.constraint_name,
c.constraint_type,
c.table_name,
c.r_constraint_name,
c.status
FROM user_constraints c
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.
Interview Questions
What are all the type of constraint available in oracle?
Which Data Dictionary table contains information about constraint with corresponding column
name?
1 View comments
UnknownMay 22, 2017 at 12:39 AM
good
Reply
DEC
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 :
--Example 1:
BEGIN
commit;
END;
listagg(product,
',') within
FROM test_ins
GROUP BY empid;
-->-- Example 2
FROM employees
GROUP BY department_id;
0 Add a comment
NOV
IF
IF ELSE
Multiple IF ELSE
LOOP
FOR LOOP
WHILE LOOP
BEGIN
END;
IF
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 1;
UPDATE test_udt t
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;
UPDATE test_udt t
ELSE
UPDATE test_udt t
END IF;
commit;
END;
/
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 2;
v_salary := v_salary+10005;
ELSE
v_salary := v_salary+20007;
END IF;
UPDATE test_udt t
commit;
END;
/
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');
v_salary := 2000;
dbms_output.put_line('2 inside');
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
commit;
END;
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');
i := i+1;
IF MOD(i,100) = 0 THEN
commit;
dbms_output.put_line('commit executed');
END IF;
END LOOP;
END;
BEGIN
FOR I in 1..5
LOOP
END LOOP;
END;
BEGIN
LOOP
END LOOP;
END;
WHILE LOOP
DECLARE
i_val NUMBER:=0;
BEGIN
LOOP
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
OCT
21
Bulk Collect
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.
DECLARE
TYPE alldata_typ IS TABLE OF product_details%ROWTYPE;
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
INTO dta;
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta alldata_typ;
BEGIN
END LOOP;
END;
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END;
/
-->-- Multiple fetches in INTO clause --<--
DECLARE
dta1 alldata_typ1;
dta2 alldata_typ2;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END;
0 Add a comment
OCT
21
Ref Cursor
This is unconstrained cursor which will return different types depends upon the user input.
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
END;
DECLARE
dep_det_c SYS_REFCURSOR;
tab_data dep_details%ROWTYPE;
BEGIN
ref_c_sp(dep_det_c);
LOOP
END LOOP;
CLOSE dep_det_c;
END;
/*sample output*/
Department Name : HR
0 Add a comment
OCT
21
Cursor
SQL Private work Area where the query get passed and executed.
Types
******
Implicit(SQL)
Explicit
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
Cursor Stages
**************
OPEN cursor_name
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
Cursor Declaration
DECLARE
CURSOR <cursor_name>
IS
<SELECT statement>
BEGIN
END;
/
Cursor Loop
Loop
While Loop
For Loop
Cursor Clauses
Return
For update
Where current of
Bulk collect
p_id NUMBER,
p_name VARCHAR2(30),
p_order_dt DATE
);
BEGIN
FOR i IN 1 .. 75 LOOP
INSERT INTO product_details VALUES (i, 'prod_name_' || i, SYSDATE + i);
END LOOP;
commit;
END;
---------------------------------------------
---------------------------------------------
---------------------------------------------
----------------------------------------------
Implicit Cursor
----------------------------------------------
----------------------------------------------
Explicit Cursor
----------------------------------------------
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
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
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
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
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
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
END IF;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
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
BEGIN
OPEN prod_detail_cur;
FETCH prod_detail_cur
INTO all_data;
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
************************************************************
************************************************************
DECLARE
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
FOR i IN prod_detail_cur
LOOP
END LOOP;
END;
/*sample output*/
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.
BEGIN
commit;
END;
----------------------------
----------------------------
1 Admin 1010
2 HR 1010
3 Sales 1020
4 Marketing 1020
----------------------------
DECLARE
all_data dep_details%ROWTYPE;
BEGIN
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1010);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
END;
/*sample output*/
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
OCT
21
Handling Exception
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
Predefined Exception
*********************
Oracle has predefined several exceptions that correspond to the most common oracle errors.
------------------------------------------------------------------------
------------------------------------------------------------------------
DUP_VAL_ON_INDEX ORA-00001 -1
OTHERS
------------------------------------------------------------------------
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
Single row SELECT returned no rows or your program referenced a deleted element in a nested
table
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
WHEN NO_DATA_FOUND THEN
END;
commit;
BEGIN
EXCEPTION
END;
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
DECLARE
num1 NUMBER(2);
BEGIN
num1 := 345;
EXCEPTION
BEGIN
COMMIT;
END;
DECLARE
cursor emp_c IS
all_data emp%ROWTYPE;
BEGIN
OPEN emp_c;
OPEN emp_c;
NULL;
CLOSE emp_c;
EXCEPTION
END;
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
User Defined Exception
**********************
User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,
DECLARE
gender_ex EXCEPTION;
BEGIN
RAISE gender_ex;
END IF;
dbms_output.put_line('Gender : '||v_gender);
EXCEPTION
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;
EXCEPTION
NULL;
END;
END LOOP;
COMMIT;
END;
********************
SQLCODE returns the current error code, and SQLERRM returns the current error message
text;
SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.
DECLARE
v_id NUMBER;
BEGIN
dbms_output.put_line(v_id);
EXCEPTION
END;
/*sample output*/
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:
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
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 :
DECLARE
BEGIN
END IF;
END;
Posted 21st October 2014 by Unknown
1 View comments
How to get the two table data without using Joins and sub query,union?
Reply
OCT
Package
I) specification
II) Body
5. Overloading
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
EXCEPTION
(1,
USER,
v_error,
systimestamp);
commit;
END emp_sal_sp;
BEGIN
END;
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;
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_hdt_sp;
BEGIN
END;
RETURN NUMBER
IS
v_c NUMBER;
BEGIN
RETURN v_c;
END;
--Specification Part
IS
RETURN NUMBER;
END emp_pkg ;
--Body Part
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
EXCEPTION
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
EXCEPTION
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
RETURN v_c;
END;
END emp_pkg;
BEGIN
emp_pkg.emp_sal_sp(120);
END;
as
RETURN NUMBER;
IS
FROM employees;
End all_detail;
create or replace package body all_detail
as
AS
BEGIN
SELECT salary
INTO c
FROM Employees
WHERE Employee_id = a;
EXCEPTION
END emp2sal;
AS
BEGIN
SELECT Round(Months_between(sysdate,hire_date)/12)
INTO c
FROM Employees
WHERE Employee_id = a;
EXCEPTION
END emp2exep;
RETURN NUMBER
AS
BEGIN
c := a+b;
RETURN C;
END;
End all_detail;
END global_constant;
BEGIN
END;
DECLARE
PROCEDURE P3;
PROCEDURE P1 IS
BEGIN
p2;
END P1;
PROCEDURE P2 IS
BEGIN
p3;
END P2;
PROCEDURE P3 IS
BEGIN
END P3;
BEGIN
p1;
END;
sample output:
From procedure p1
From procedure p2
From procedure p3
Interview Questions:
What is package?
Advantage of package
0 Add a comment
OCT
p_id NUMBER(3),
p_nm VARCHAR2(30),
p_qty NUMBER(8),
order_dt DATE
);
BEGIN
commit;
END;
/
SELECT * FROM product_details;
------------------------------------
------------------------------------
------------------------------------
DECLARE
v_name VARCHAR2(4);
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
DECLARE
v_name VARCHAR2(5);
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
VALUES
(106,
'name6',
700,
'26-Dec-12');
commit;
DECLARE
v_name VARCHAR2(5);
BEGIN
FROM product_details
--error
END;
DECLARE
v_name product_details.p_nm%TYPE;
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
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
END;
--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
END;
dept_id number(3) ,
dept_name varchar2(30),
dept_manager_name varchar2(30)
);
-------------------------------------------------------
+------------+-----------------------+-----------------
| 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
END;
/
---------------------------------------------------
---------------------------------------------------
| 20 | dept2 | manager_name2 |
---------------------------------------------------
Interview Question :
SEP
29
BULK Exceptions
/************************************************************************
* Reference : http://www.dba-oracle.com/plsql/t_plsql_exceptions.htm *
************************************************************************/
DECLARE
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
commit;
END;
COUNT(*)
-------
200
BEGIN
FOR i in 1..200
LOOP
v_dat.EXTEND;
v_dat(v_dat.LAST) := i;
END LOOP;
v_dat(100) := NULL;
FORALL i IN v_dat.FIRST..v_dat.LAST
commit;
END;
/*
Error Message :
ORA-01400: cannot insert NULL into ("HR"."bulk_tb"."ran_num")
ORA-06512: at line 15
*/
DECLARE
BEGIN
FOR i in 1..200
LOOP
v_dat.EXTEND;
v_dat(v_dat.LAST) := i;
END LOOP;
v_dat(100) := NULL;
BEGIN
FORALL i IN v_dat.FIRST..v_dat.LAST
EXCEPTION
END;
END;
COUNT(*)
-------
99
SQL%BULK_EXCEPTIONS(i).ERROR_INDEX
Holds the iteration (not the subscript) of the original FORALL statement that raised the
exception.
the exception row must be found by looping through the original collection the correct
number of times.
SQL%BULK_EXCEPTIONS(i).ERROR_CODE
The total number of exceptions can be returned using the collections COUNT method,
DECLARE
v_ex_count NUMBER(4);
abort_ex EXCEPTION;
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
BEGIN
COMMIT;
EXCEPTION
v_ex_count := SQL%BULK_EXCEPTIONS.COUNT;
END LOOP;
END;
END;
/*
Sample output:
*/
COUNT(*)
-------
198
SAVE EXCEPTIONS clause being removed, in the above script now traps a different error number.
/*
Sample output:
*/
-------
99
0 Add a comment
SEP
29
/************************************************************************
************************************************************************/
create table prod_details(p_id VARCHAR2(30), P_name VARCHAR2(30));
BEGIN
END LOOP;
commit;
END;
DECLARE
CURSOR PROD_DTLS_C IS
V_PID PROD_DETAILS.P_ID%TYPE;
V_PRDNAME PROD_DETAILS.P_NAME%TYPE;
BEGIN
OPEN PROD_DTLS_C;
LOOP
IF PROD_DTLS_C%NOTFOUND THEN
EXIT;
ELSE
UPDATE PROD_DETAILS P
END IF;
END LOOP;
CLOSE PROD_DTLS_C;
COMMIT;
END;
END LOOP;
commit;
END;
DECLARE
CURSOR PROD_DTLS_C IS
V_PID PROD_DETAILS.P_ID%TYPE;
V_PRDNAME PROD_DETAILS.P_NAME%TYPE;
BEGIN
OPEN PROD_DTLS_C;
LOOP
EXIT;
ELSE
UPDATE PROD_DETAILS P
END IF;
COMMIT;
END LOOP;
CLOSE PROD_DTLS_C;
--COMMIT;
END;
0 Add a comment
MAY
28
FROM Dual;
FROM Dual;
SAL_DETAILS
---------------------------------------
FROM Dual;
Info
---------------------------------------
SELECT q'[some test ' some test ' some text ']' AS "In 10g"
FROM dual;
In 10g
------------------------------------
The '_' wild card character is used to match exactly one character
WITH mail_ids AS
(
UNION
UNION
----------------------------------
an_murugappan@gmail.com
WITH mail_ids AS
UNION
UNION
----------------------------------
an%murugappan@gmail.com
'23'
----
23
'&A'
----
&a
----
&a
'45'
----
45
0 Add a comment
MAY
28
Data Manipulation Language (DML) statements are used for managing data within schema
objects. Some examples:
INSERT - insert data into a table
DELETE - deletes all records from a table, the space for the records remain
prod_id NUMBER(4) ,
prod_name VARCHAR2(30) ,
comments VARCHAR2(300)
);
no_data_found
INSERT
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
VALUES(103,'Moto X','11-May-14','13-May-14');
VALUES(103,'Moto X','11-May-14','13-May-14');
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--If you want to insert NULL value you can ignore that column at the time of inserting
VALUES(104,'Moto G','19-May-14','22-May-14',NULL);
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
--if you are not providing values for order_dt and deliver_dt column default value can be taken.
---------------------------------------------------------------------------
---------------------------------------------------------------------------
COUNT(*)
-------
WHERE id = 900;
COUNT(*)
-------
COUNT(*)
-------
UPDATE
Syntax :
UPDATE table_name
column2_name = column2_value,
column2_name = column3_value,
columnn_name = columnn_value
WHERE condition(s);
---------------------------------------------------------------------------
---------------------------------------------------------------------------
UPDATE prod_details ps
SELECT *
FROM prod_details ps
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
UPDATE prod_details ps
SELECT *
---------------------------------------------------------------------------
---------------------------------------------------------------------------
----------------------------------------------------------------------
--if your update text contain ' means you can use following metnod (use '')
UPDATE prod_details ps
SELECT *
FROM prod_details ps
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
DELETE
Syntax:
WHERE condition(s);
SELECT *
---------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------
100 Apple iphone 5s 5/21/2014 5/24/2014 Some product's are not available
---------------------------------------------------------------------------------------
no rows selected.
0 Add a comment
MAY
28
Data Definition Language (DDL) statements are used to define the database structure or schema.
Some examples:
ADD
RENAME
MODIFY
DROP
Creating Table
--------------------------------------------------------------------------
--------------------------------------------------------------------------
S: -84 to 127
VARCHAR2 4000 Bytes we can store 0-9, a-z, A-Z and special characters
--------------------------------------------------------------------------
CREATE
RENAME
DROP
TRUNCATE
--creating table
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)
-----------------------------
ADD : Used to add a column after the table hase been created
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)
-----------------------------
SYNTAX
ADD (
column_1 Data_type(size),
column_2 Data_type(size),
column_3 Data_type(size),
column_4 Data_type(size)
);
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.
-----------------------------
NAME TYPE
-----------------------------
NAME VARCHAR2(30)
PHONE NUMBER(10)
GENDER CHAR(1)
DOB DATE
OTHER_DETAILS CLOB
MAKE_DTM TIMESTAMP(6)
EMAIL_ID VARCHAR2(30)
-----------------------------
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
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)
-----------------------------
SYNTAX
-----------------------------
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
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
0 Add a comment
MAY
28
Statements in Oracle
DDL statements are used to define the database structure or schema. Some examples:
ADD
RENAME
MODIFY
DROP
DML statements are used for managing data within schema objects. Some examples:
DELETE - deletes all records from a table, the space for the records remain
SAVEPOINT - identify a point in a transaction to which you can later roll back
0 Add a comment
MAY
19
roll_no NUMBER(4) ,
Name VARCHAR2(30) ,
dept_cd VARCHAR2(20) ,
total_marks NUMBER(3)
);
BEGIN
END;
DECODE
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',
'Information Technology',
FROM students;
Sample Output
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
CASE
Example
SELECT roll_no,
NAME,
dept_cd,
total_marks,
CASE
'A Grade'
'B Grade'
'C Grade'
ELSE
'U Grade'
END AS "GRADE"
FROM students;
-----------------------------------------------
-----------------------------------------------
-----------------------------------------------
Interview Questions:
What is DECODE?
What is CASE?
0 Add a comment
MAY
19
Sub Query
Want to fetch the person Who are all getting salary more than Neena's salary ?
From Employees
Sub Query :
From Employees
);
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
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
);
From Employees
);
From Employees
);
All : Maximum Value will be taken (9000)
From Employees
);
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
FROM
Dual;
Where Department_id = 60
);
SELECT AVG(salary)
FROM employees
);
Posted 19th May 2014 by Unknown
0 Add a comment
Loading
search
JUL
20
--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
, AVG(b.salary) avg_sal
FROM employees b
GROUP BY b.department_id
)b
Display all the customer who have placed more number of orders by using INLINE view
( custm_id NUMBER ,
custm_nm VARCHAR2(30) ,
ttl_amt NUMBER(7,2)
);
BEGIN
COMMIT;
END;
SELECT c.*
FROM customer_order_det_tb c;
--------------------------------------------
--------------------------------------------
--------------------------------------------
--Writing a Quer to display all the customer who have placed maximum number of order
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
--------------------------------
--------------------------------
100 Murugappan 2
102 Ramesh 2
101 Raja 1
--------------------------------
----------
total_odr
----------
----------
Inline view to find all the customers who have placed maximum number of orders
/****************************************
Syntax
WHERE contition;
****************************************/
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
) query1,
) query2
-------------------------------
-------------------------------
100 Murugappan 2
102 Ramesh 2
-------------------------------
--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT
FROM employees e
Example :
--in 11g
SELECT *
FROM departments d
--in 12c
SELECT *
FROM departments d
);
--in 11g
WITH t
AS
( SELECT LEVEL a
FROM dual
SELECT *
FROM t, (SELECT *
FROM employees
);
--in 12c
WITH t
AS
SELECT * FROM t,
LATERAL(SELECT *
FROM employees
0 Add a comment
JAN
23
eid NUMBER(4),
ename VARCHAR2(30),
depno NUMBER(3),
salary NUMBER(8)
);
BEGIN
--Inserting records
COMMIT;
END;
SELECT MAX(salary)
FROM employee_data
FROM employee_data);
--query to select 5th maximum salary
SELECT MIN(salary)
FROM employee_data
SELECT MIN(salary)
FROM employee_data
--query to select all the details of the employee whose getting nth maximum salary
SELECT *
FROM (SELECT *
FROM employee_data
WHERE rn = 9;
SELECT *
WHERE rank = 9;
SELECT *
WHERE rank = 4;
WHERE rank = 4;
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
--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
FROM employees
--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,
first_name,
salary
FROM employees
7 View comments
JAN
22
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.
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.
14 rows selected.
Elapsed: 00:00:14.01
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.
0 Add a comment
DEC
21
Constraints
Format : [part_of_project_name-table_name-column_name-constraint_type]
Format : sys_cn
Example : SYS_C405323
Types
Primary Key
Ex : Employee_id, Student_id
Unique Key
Ex : Contact_no, email
Foreign Key
c1(pk) : 1 2 3
Not Null
------------------------------------
Duplicate NULL
------------------------------------
Primary Key X X
------------------------------------
S_id Number(2),
s_mail Varchar2(30),
s_gender char(1),
s_did Number(3),
);
DESC my_stu_details;
------------------------------------
------------------------------------
S_ID NUMBER(2)
S_NAME VARCHAR2(30)
S_MAIL VARCHAR2(30) Y
S_GENDER CHAR(1) Y
S_DID NUMBER(3) Y
------------------------------------
--Duplicate Check
--Null Check
--------------------------------------------------------
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
--------------------------------------------------------
------------------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
-------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
ON DELETE CASCADE
SELECT c.owner,
c.constraint_name,
c.constraint_type,
c.table_name,
c.r_constraint_name,
c.status
FROM user_constraints c
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.
Which Data Dictionary table contains information about constraint with corresponding column
name?
good
Reply
DEC
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 :
--Example 1:
BEGIN
commit;
END;
listagg(product,
',') within
FROM test_ins
GROUP BY empid;
-->-- Example 2
FROM employees
GROUP BY department_id;
NOV
IF
IF ELSE
Multiple IF ELSE
LOOP
FOR LOOP
WHILE LOOP
BEGIN
Commit;
END;
IF
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 1;
UPDATE test_udt t
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;
UPDATE test_udt t
ELSE
UPDATE test_udt t
END IF;
commit;
END;
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 2;
v_salary := v_salary+10005;
ELSE
v_salary := v_salary+20007;
END IF;
UPDATE test_udt t
END;
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');
v_salary := 2000;
dbms_output.put_line('2 inside');
dbms_output.put_line('3 inside');
v_salary := 4000;
dbms_output.put_line('4 inside');
END IF;
UPDATE test_udt t
commit;
END;
LOOP
--syntax
LOOP
--statements
--increment
--exit statement
END LOOP;
DECLARE
i NUMBER := 1;
x VARCHAR2(3);
BEGIN
LOOP
x := lpad(i,3,'0');
i := i+1;
IF MOD(i,100) = 0 THEN
commit;
dbms_output.put_line('commit executed');
END IF;
END LOOP;
END;
FOR LOOP
BEGIN
FOR I in 1..5
LOOP
END LOOP;
END;
BEGIN
LOOP
END LOOP;
END;
WHILE LOOP
DECLARE
i_val NUMBER:=0;
BEGIN
LOOP
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
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.
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
INTO dta;
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta alldata_typ;
BEGIN
SELECT * BULK COLLECT INTO dta FROM product_details;
END LOOP;
END;
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END;
/
DECLARE
dta1 alldata_typ1;
dta2 alldata_typ2;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
FOR i IN dta2.FIRST .. dta2.COUNT LOOP
END LOOP;
END;
0 Add a comment
OCT
21
Ref Cursor
This is unconstrained cursor which will return different types depends upon the user input.
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.
AS
BEGIN
OPEN dep_det_c
FOR
END;
DECLARE
dep_det_c SYS_REFCURSOR;
tab_data dep_details%ROWTYPE;
BEGIN
ref_c_sp(dep_det_c);
LOOP
END LOOP;
CLOSE dep_det_c;
END;
/*sample output*/
Department Name : HR
0 Add a comment
OCT
21
Cursor
SQL Private work Area where the query get passed and executed.
Types
******
Implicit(SQL)
Explicit
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
Cursor Stages
**************
OPEN cursor_name
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
Cursor Declaration
DECLARE
CURSOR <cursor_name>
IS
<SELECT statement>
BEGIN
END;
/
Cursor Loop
Loop
While Loop
For Loop
Cursor Clauses
Return
For update
Where current of
Bulk collect
p_id NUMBER,
p_name VARCHAR2(30),
p_order_dt DATE
);
FOR i IN 1 .. 75 LOOP
END LOOP;
commit;
END;
---------------------------------------------
---------------------------------------------
---------------------------------------------
----------------------------------------------
Implicit Cursor
----------------------------------------------
----------------------------------------------
Explicit Cursor
----------------------------------------------
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
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
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
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*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
FETCH prod_detail_cur
INTO all_data;
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
************************************************************
************************************************************
DECLARE
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
FOR i IN prod_detail_cur
LOOP
END LOOP;
END;
/*sample output*/
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.
BEGIN
commit;
END;
----------------------------
----------------------------
1 Admin 1010
2 HR 1010
3 Sales 1020
4 Marketing 1020
----------------------------
DECLARE
all_data dep_details%ROWTYPE;
BEGIN
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1010);
LOOP
FETCH dep_det_c
INTO all_data;
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;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
END;
/*sample output*/
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
Posted 21st October 2014 by Unknown
0 Add a comment
OCT
21
Handling Exception
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
Predefined Exception
*********************
Oracle has predefined several exceptions that correspond to the most common oracle errors.
------------------------------------------------------------------------
------------------------------------------------------------------------
DUP_VAL_ON_INDEX ORA-00001 -1
OTHERS
------------------------------------------------------------------------
-->-- ZERO_DIVIDE --<--
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
Single row SELECT returned no rows or your program referenced a deleted element in a nested
table
DECLARE
v_id NUMBER;
BEGIN
SELECT id INTO v_id FROM test_tb;
EXCEPTION
END;
commit;
BEGIN
EXCEPTION
END;
-->-- TOO_MANY_ROWS --<--
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
DECLARE
num1 NUMBER(2);
BEGIN
num1 := 345;
EXCEPTION
WHEN VALUE_ERROR THEN
END;
BEGIN
COMMIT;
END;
DECLARE
cursor emp_c IS
SELECT * FROM emp;
all_data emp%ROWTYPE;
BEGIN
OPEN emp_c;
OPEN emp_c;
NULL;
CLOSE emp_c;
EXCEPTION
END;
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
**********************
User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,
DECLARE
gender_ex EXCEPTION;
BEGIN
RAISE gender_ex;
END IF;
dbms_output.put_line('Gender : '||v_gender);
EXCEPTION
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;
EXCEPTION
NULL;
END;
END LOOP;
COMMIT;
END;
********************
SQLCODE returns the current error code, and SQLERRM returns the current error message
text;
SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.
DECLARE
v_id NUMBER;
BEGIN
dbms_output.put_line(v_id);
EXCEPTION
END;
/*sample output*/
SQLERRM : ORA-01403: no data found
SQLCODE : 100
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:
DECLARE
v_result NUMBER;
BEGIN
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 :
DECLARE
BEGIN
END IF;
END;
Posted 21st October 2014 by Unknown
1 View comments
How to get the two table data without using Joins and sub query,union?
Reply
OCT
Package
I) specification
II) Body
5. Overloading
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_sal_sp;
BEGIN
END;
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_hdt_sp;
BEGIN
END;
IS
v_c NUMBER;
BEGIN
RETURN v_c;
END;
--Specification Part
IS
RETURN NUMBER;
END emp_pkg ;
--Body Part
CREATE OR REPLACE PACKAGE BODY emp_pkg
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_sal_sp;
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_hdt_sp;
RETURN NUMBER
IS
v_c NUMBER;
BEGIN
RETURN v_c;
END;
END emp_pkg;
BEGIN
emp_pkg.emp_sal_sp(120);
END;
--Executing function inside the package
as
RETURN NUMBER;
IS
FROM employees;
End all_detail;
create or replace package body all_detail
as
AS
BEGIN
SELECT salary
INTO c
FROM Employees
WHERE Employee_id = a;
EXCEPTION
END emp2sal;
AS
BEGIN
SELECT Round(Months_between(sysdate,hire_date)/12)
INTO c
FROM Employees
WHERE Employee_id = a;
EXCEPTION
END emp2exep;
RETURN NUMBER
AS
BEGIN
c := a+b;
RETURN C;
END;
End all_detail;
IS
END global_constant;
BEGIN
END;
DECLARE
PROCEDURE P3;
PROCEDURE P1 IS
BEGIN
p2;
END P1;
PROCEDURE P2 IS
BEGIN
p3;
END P2;
PROCEDURE P3 IS
BEGIN
END P3;
BEGIN
p1;
END;
sample output:
From procedure p1
From procedure p2
From procedure p3
Interview Questions:
What is package?
Advantage of package
0 Add a comment
OCT
2
p_id NUMBER(3),
p_nm VARCHAR2(30),
p_qty NUMBER(8),
order_dt DATE
);
BEGIN
commit;
END;
/
------------------------------------
------------------------------------
------------------------------------
DECLARE
v_name VARCHAR2(4);
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
DECLARE
v_name VARCHAR2(5);
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
VALUES
(106,
'name6',
700,
'26-Dec-12');
commit;
DECLARE
v_name VARCHAR2(5);
BEGIN
FROM product_details
--error
END;
DECLARE
v_name product_details.p_nm%TYPE;
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
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
END;
--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
END;
dept_id number(3) ,
dept_name varchar2(30),
dept_manager_name varchar2(30)
);
-------------------------------------------------------
+------------+-----------------------+-----------------
| 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
---------------------------------------------------
---------------------------------------------------
| 20 | dept2 | manager_name2 |
---------------------------------------------------
Interview Question :
0 Add a comment
SEP
29
BULK Exceptions
/************************************************************************
* Reference : http://www.dba-oracle.com/plsql/t_plsql_exceptions.htm *
************************************************************************/
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
commit;
END;
COUNT(*)
-------
200
DECLARE
BEGIN
FOR i in 1..200
LOOP
v_dat.EXTEND;
v_dat(v_dat.LAST) := i;
END LOOP;
v_dat(100) := NULL;
FORALL i IN v_dat.FIRST..v_dat.LAST
commit;
END;
/*
Error Message :
ORA-06512: at line 15
*/
DECLARE
BEGIN
FOR i in 1..200
LOOP
v_dat.EXTEND;
v_dat(v_dat.LAST) := i;
END LOOP;
v_dat(100) := NULL;
BEGIN
FORALL i IN v_dat.FIRST..v_dat.LAST
COMMIT;
EXCEPTION
END;
END;
COUNT(*)
-------
99
SQL%BULK_EXCEPTIONS(i).ERROR_INDEX
Holds the iteration (not the subscript) of the original FORALL statement that raised the
exception.
the exception row must be found by looping through the original collection the correct
number of times.
SQL%BULK_EXCEPTIONS(i).ERROR_CODE
The total number of exceptions can be returned using the collections COUNT method,
DECLARE
v_ex_count NUMBER(4);
abort_ex EXCEPTION;
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;
BEGIN
COMMIT;
EXCEPTION
v_ex_count := SQL%BULK_EXCEPTIONS.COUNT;
END LOOP;
END;
END;
/*
Sample output:
*/
COUNT(*)
-------
198
SAVE EXCEPTIONS clause being removed, in the above script now traps a different error number.
/*
Sample output:
*/
SELECT COUNT(*) FROM bulk_tb;
COUNT(*)
-------
99
0 Add a comment
SEP
29
/************************************************************************
************************************************************************/
BEGIN
END LOOP;
commit;
END;
DECLARE
CURSOR PROD_DTLS_C IS
V_PRDNAME PROD_DETAILS.P_NAME%TYPE;
BEGIN
OPEN PROD_DTLS_C;
LOOP
IF PROD_DTLS_C%NOTFOUND THEN
EXIT;
ELSE
UPDATE PROD_DETAILS P
END IF;
END LOOP;
CLOSE PROD_DTLS_C;
COMMIT;
END;
BEGIN
END LOOP;
commit;
END;
DECLARE
CURSOR PROD_DTLS_C IS
V_PID PROD_DETAILS.P_ID%TYPE;
V_PRDNAME PROD_DETAILS.P_NAME%TYPE;
BEGIN
OPEN PROD_DTLS_C;
LOOP
IF PROD_DTLS_C%NOTFOUND THEN
EXIT;
ELSE
UPDATE PROD_DETAILS P
END IF;
COMMIT;
END LOOP;
CLOSE PROD_DTLS_C;
--COMMIT;
END;
0 Add a comment
MAY
28
FROM Dual;
FROM Dual;
SAL_DETAILS
---------------------------------------
FROM Dual;
Info
---------------------------------------
SELECT q'[some test ' some test ' some text ']' AS "In 10g"
FROM dual;
In 10g
------------------------------------
The '_' wild card character is used to match exactly one character
UNION
UNION
----------------------------------
an_murugappan@gmail.com
WITH mail_ids AS
UNION
UNION
----------------------------------
an%murugappan@gmail.com
'23'
----
23
'&A'
----
&a
SQL> SET SCAN OFF;
'&A'
----
&a
'45'
----
45
0 Add a comment
MAY
28
DELETE - deletes all records from a table, the space for the records remain
prod_id NUMBER(4) ,
prod_name VARCHAR2(30) ,
comments VARCHAR2(300)
);
no_data_found
INSERT
INSERT INTO prod_details(prod_id,prod_name,order_dt,deliver_dt,comments)
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
--Inserting selective number of values
VALUES(103,'Moto X','11-May-14','13-May-14');
VALUES(103,'Moto X','11-May-14','13-May-14');
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--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.
VALUES(104,'Moto G','19-May-14','22-May-14',NULL);
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
--if you are not providing values for order_dt and deliver_dt column default value can be taken.
----------------------------------------------------------------------------
---------------------------------------------------------------------------
COUNT(*)
-------
3
--creating table by using sub query (with out data)
WHERE id = 900;
COUNT(*)
-------
-------
UPDATE
Syntax :
UPDATE table_name
column2_name = column2_value,
column2_name = column3_value,
columnn_name = columnn_value
WHERE condition(s);
----------------------------------------------------------------------
---------------------------------------------------------------------------
UPDATE prod_details ps
SELECT *
FROM prod_details ps
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--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
SELECT *
---------------------------------------------------------------------------
---------------------------------------------------------------------------
----------------------------------------------------------------------
--if your update text contain ' means you can use following metnod (use '')
UPDATE prod_details ps
SELECT *
FROM prod_details ps
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
DELETE
Syntax:
WHERE condition(s);
DELETE FROM prod_details
SELECT *
---------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------
100 Apple iphone 5s 5/21/2014 5/24/2014 Some product's are not available
---------------------------------------------------------------------------------------
no rows selected.
DROP TABLE prod_details;
0 Add a comment
MAY
28
Data Definition Language (DDL) statements are used to define the database structure or schema.
Some examples:
ADD
RENAME
MODIFY
DROP
Creating Table
--------------------------------------------------------------------------
--------------------------------------------------------------------------
S: -84 to 127
VARCHAR2 4000 Bytes we can store 0-9, a-z, A-Z and special characters
CREATE
RENAME
DROP
TRUNCATE
--creating table
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)
-----------------------------
ADD : Used to add a column after the table hase been created
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)
-----------------------------
SYNTAX
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
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.
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)
-----------------------------
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.
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)
-----------------------------
SYNTAX
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
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
0 Add a comment
MAY
28
Statements in Oracle
DDL statements are used to define the database structure or schema. Some examples:
ADD
RENAME
MODIFY
DROP
DML statements are used for managing data within schema objects. Some examples:
DELETE - deletes all records from a table, the space for the records remain
TCL statements are used to manage the changes made by DML statements. It allows
statements to be grouped together into logical transactions.
SAVEPOINT - identify a point in a transaction to which you can later roll back
0 Add a comment
MAY
19
roll_no NUMBER(4) ,
Name VARCHAR2(30) ,
dept_cd VARCHAR2(20) ,
total_marks NUMBER(3)
);
BEGIN
END;
DECODE
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',
'IT',
'Information Technology',
FROM students;
Sample Output
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
CASE
Example
SELECT roll_no,
NAME,
dept_cd,
total_marks,
CASE
'A Grade'
'B Grade'
'C Grade'
ELSE
'U Grade'
END AS "GRADE"
FROM students;
-----------------------------------------------
-----------------------------------------------
Interview Questions:
What is DECODE?
What is CASE?
0 Add a comment
MAY
19
Sub Query
From Employees
Sub Query :
From Employees
);
Select * from employees;
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
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
);
From Employees
);
From Employees
From Employees
);
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
FROM
Dual;
Where Department_id = 60
);
SELECT AVG(salary)
FROM employees
WHERE department = Bob.department
);
0 Add a comment
Loading
search
JUL
20
--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
, AVG(b.salary) avg_sal
FROM employees b
GROUP BY b.department_id
)b
Display all the customer who have placed more number of orders by using INLINE view
( custm_id NUMBER ,
custm_nm VARCHAR2(30) ,
ttl_amt NUMBER(7,2)
);
BEGIN
COMMIT;
END;
SELECT c.*
FROM customer_order_det_tb c;
--------------------------------------------
--------------------------------------------
--------------------------------------------
--Writing a Quer to display all the customer who have placed maximum number of order
--Query #1 for inline view
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
--------------------------------
--------------------------------
100 Murugappan 2
102 Ramesh 2
101 Raja 1
--------------------------------
----------
total_odr
----------
2
----------
Inline view to find all the customers who have placed maximum number of orders
/****************************************
Syntax
WHERE contition;
****************************************/
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
) query1,
) query2
-------------------------------
100 Murugappan 2
102 Ramesh 2
-------------------------------
--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT
FROM employees e
--in 11g
SELECT *
FROM departments d
--in 12c
SELECT *
FROM departments d
);
--in 11g
WITH t
AS
( SELECT LEVEL a
FROM dual
FROM t, (SELECT *
FROM employees
);
--in 12c
WITH t
AS
SELECT * FROM t,
LATERAL(SELECT *
FROM employees
0 Add a comment
JAN
23
Salary Related Questions in Oracle
--creating table
eid NUMBER(4),
ename VARCHAR2(30),
depno NUMBER(3),
salary NUMBER(8)
);
BEGIN
--Inserting records
COMMIT;
END;
SELECT MAX(salary)
FROM employee_data
WHERE salary NOT IN (SELECT MAX(salary)
FROM employee_data);
SELECT MIN(salary)
FROM employee_data
SELECT MIN(salary)
FROM employee_data
--query to select all the details of the employee whose getting nth maximum salary
SELECT *
rownum rn
FROM (SELECT *
FROM employee_data
WHERE rn = 9;
SELECT *
WHERE rank = 9;
SELECT *
WHERE rank = 4;
WHERE rank = 4;
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
--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
--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,
first_name,
salary
FROM employees
7 View comments
JAN
22
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.
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.
14 rows selected.
Elapsed: 00:00:14.01
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.
0 Add a comment
DEC
21
Constraints
It Enforce Rule On Table
Format : [part_of_project_name-table_name-column_name-constraint_type]
Format : sys_cn
Example : SYS_C405323
Types
Primary Key
Ex : Employee_id, Student_id
Unique Key
Ex : Contact_no, email
Foreign Key
c1(pk) : 1 2 3
Not Null
It will not allowed you to enter null value
Check
------------------------------------
Duplicate NULL
------------------------------------
Primary Key X X
------------------------------------
S_id Number(2),
S_name Varchar2(30) Not Null, --SYS_Cn
s_mail Varchar2(30),
s_gender char(1),
s_did Number(3),
);
DESC my_stu_details;
------------------------------------
------------------------------------
S_ID NUMBER(2)
S_NAME VARCHAR2(30)
S_MAIL VARCHAR2(30) Y
S_GENDER CHAR(1) Y
S_DID NUMBER(3) Y
------------------------------------
--Duplicate Check
Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)
--Null Check
--------------------------------------------------------
--------------------------------------------------------
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
--------------------------------------------------------
------------------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
-------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
ON DELETE CASCADE
SELECT c.owner,
c.constraint_name,
c.constraint_type,
c.table_name,
c.r_constraint_name,
c.status
FROM user_constraints c
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.
Which Data Dictionary table contains information about constraint with corresponding column
name?
1 View comments
good
Reply
DEC
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 :
--Example 1:
BEGIN
INSERT INTO test_ins VALUES( 101,'pendrive');
commit;
END;
listagg(product,
',') within
FROM test_ins
GROUP BY empid;
-->-- Example 2
FROM employees
GROUP BY department_id;
0 Add a comment
NOV
IF
IF ELSE
Multiple IF ELSE
LOOP
FOR LOOP
WHILE LOOP
BEGIN
Commit;
END;
IF
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 1;
UPDATE test_udt t
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;
UPDATE test_udt t
ELSE
UPDATE test_udt t
END IF;
commit;
END;
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 2;
v_salary := v_salary+10005;
ELSE
v_salary := v_salary+20007;
END IF;
UPDATE test_udt t
SET t.salary = v_salary
commit;
END;
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');
v_salary := 2000;
dbms_output.put_line('2 inside');
v_salary := 3000;
dbms_output.put_line('3 inside');
v_salary := 4000;
dbms_output.put_line('4 inside');
END IF;
UPDATE test_udt t
commit;
END;
LOOP
--syntax
LOOP
--statements
--increment
--exit statement
END LOOP;
DECLARE
i NUMBER := 1;
x VARCHAR2(3);
BEGIN
LOOP
x := lpad(i,3,'0');
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;
FOR LOOP
BEGIN
FOR I in 1..5
LOOP
END LOOP;
END;
BEGIN
LOOP
END LOOP;
END;
/
WHILE LOOP
DECLARE
i_val NUMBER:=0;
BEGIN
LOOP
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
0 Add a comment
OCT
21
Bulk Collect
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.
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
INTO dta;
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
BEGIN
END LOOP;
END;
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END;
DECLARE
dta1 alldata_typ1;
dta2 alldata_typ2;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END;
0 Add a comment
OCT
21
Ref Cursor
This is unconstrained cursor which will return different types depends upon the user input.
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.
AS
BEGIN
OPEN dep_det_c
FOR
END;
DECLARE
dep_det_c SYS_REFCURSOR;
tab_data dep_details%ROWTYPE;
BEGIN
ref_c_sp(dep_det_c);
LOOP
CLOSE dep_det_c;
END;
/*sample output*/
Department Name : HR
0 Add a comment
OCT
21
Cursor
SQL Private work Area where the query get passed and executed.
Types
******
Implicit(SQL)
Explicit
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
Cursor Stages
**************
OPEN 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
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
p_id NUMBER,
p_name VARCHAR2(30),
p_order_dt DATE
);
-->-- Inserting data
BEGIN
FOR i IN 1 .. 75 LOOP
END LOOP;
commit;
END;
---------------------------------------------
---------------------------------------------
---------------------------------------------
----------------------------------------------
Implicit Cursor
----------------------------------------------
----------------------------------------------
Explicit Cursor
----------------------------------------------
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
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
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
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
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*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
FETCH prod_detail_cur
INTO all_data;
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
************************************************************
DECLARE
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
FOR i IN prod_detail_cur
LOOP
END LOOP;
END;
/*sample output*/
*********************
This was used when you are going to use the cursor in more than one place with different
values for the same where clause.
BEGIN
commit;
END;
----------------------------
1 Admin 1010
2 HR 1010
3 Sales 1020
4 Marketing 1020
----------------------------
DECLARE
all_data dep_details%ROWTYPE;
BEGIN
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1010);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1020);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
END;
/*sample output*/
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
0 Add a comment
OCT
21
Handling Exception
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
Predefined Exception
*********************
Oracle has predefined several exceptions that correspond to the most common oracle errors.
------------------------------------------------------------------------
------------------------------------------------------------------------
DUP_VAL_ON_INDEX ORA-00001 -1
OTHERS
------------------------------------------------------------------------
-->-- ZERO_DIVIDE --<--
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
Single row SELECT returned no rows or your program referenced a deleted element in a nested
table
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
commit;
BEGIN
EXCEPTION
END;
-->-- TOO_MANY_ROWS --<--
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
DECLARE
num1 NUMBER(2);
BEGIN
num1 := 345;
EXCEPTION
END;
BEGIN
COMMIT;
END;
cursor emp_c IS
all_data emp%ROWTYPE;
BEGIN
OPEN emp_c;
OPEN emp_c;
NULL;
CLOSE emp_c;
EXCEPTION
END;
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
**********************
User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,
DECLARE
gender_ex EXCEPTION;
BEGIN
RAISE gender_ex;
END IF;
dbms_output.put_line('Gender : '||v_gender);
EXCEPTION
END;
DECLARE
abort_ex EXCEPTION;
BEGIN
FOR i IN 1..100
LOOP
BEGIN
IF mod(i,10)=0 THEN
RAISE abort_ex;
END IF;
EXCEPTION
NULL;
END;
END LOOP;
COMMIT;
END;
********************
SQLCODE returns the current error code, and SQLERRM returns the current error message
text;
SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.
DECLARE
v_id NUMBER;
BEGIN
dbms_output.put_line(v_id);
EXCEPTION
END;
/*sample output*/
SQLCODE : 100
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:
DECLARE
v_result NUMBER;
BEGIN
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 :
DECLARE
BEGIN
END IF;
dbms_output.put_line('Gender : ' || v_gender);
END;
1 View comments
How to get the two table data without using Joins and sub query,union?
Reply
OCT
Package
I) specification
II) Body
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
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_sal_sp;
BEGIN
END;
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_hdt_sp;
BEGIN
END;
create or replace function sum_fn (p_a IN NUMBER, p_b IN NUMBER)
RETURN NUMBER
IS
v_c NUMBER;
BEGIN
RETURN v_c;
END;
--Specification Part
IS
RETURN NUMBER;
END emp_pkg ;
--Body Part
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_sal_sp;
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_hdt_sp;
RETURN NUMBER
IS
v_c NUMBER;
BEGIN
RETURN v_c;
END;
END emp_pkg;
BEGIN
emp_pkg.emp_sal_sp(120);
END;
as
RETURN NUMBER;
IS
FROM employees;
End all_detail;
as
AS
BEGIN
SELECT salary
INTO c
FROM Employees
WHERE Employee_id = a;
EXCEPTION
END emp2sal;
AS
BEGIN
SELECT Round(Months_between(sysdate,hire_date)/12)
INTO c
FROM Employees
WHERE Employee_id = a;
EXCEPTION
END emp2exep;
RETURN NUMBER
AS
BEGIN
c := a+b;
RETURN C;
END;
End all_detail;
/*Declaring a Bodiless Package */
IS
END global_constant;
BEGIN
END;
DECLARE
PROCEDURE P3;
PROCEDURE P1 IS
BEGIN
dbms_output.put_line('From procedure p1');
p2;
END P1;
PROCEDURE P2 IS
BEGIN
p3;
END P2;
PROCEDURE P3 IS
BEGIN
END P3;
BEGIN
p1;
END;
sample output:
From procedure p1
From procedure p2
From procedure p3
Drop package package_name;
Interview Questions:
What is package?
Advantage of package
0 Add a comment
OCT
p_id NUMBER(3),
p_nm VARCHAR2(30),
p_qty NUMBER(8),
order_dt DATE
);
BEGIN
END;
------------------------------------
------------------------------------
------------------------------------
DECLARE
v_name VARCHAR2(4);
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
WHERE p_id = 100;
END;
DECLARE
v_name VARCHAR2(5);
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
VALUES
(106,
'name6',
700,
'26-Dec-12');
commit;
DECLARE
v_name VARCHAR2(5);
BEGIN
FROM product_details
--error
END;
DECLARE
v_name product_details.p_nm%TYPE;
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
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
END;
--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
END;
dept_id number(3) ,
dept_name varchar2(30),
dept_manager_name varchar2(30)
);
insert into dept_details values(10,'dept1','manager_name1');
-------------------------------------------------------
+------------+-----------------------+-----------------
| 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
END;
---------------------------------------------------
---------------------------------------------------
| 20 | dept2 | manager_name2 |
---------------------------------------------------
Interview Question :
0 Add a comment
SEP
29
BULK Exceptions
/************************************************************************
* Reference : http://www.dba-oracle.com/plsql/t_plsql_exceptions.htm *
************************************************************************/
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
commit;
END;
COUNT(*)
-------
200
TRUNCATE TABLE bulk_tb;
DECLARE
BEGIN
FOR i in 1..200
LOOP
v_dat.EXTEND;
v_dat(v_dat.LAST) := i;
END LOOP;
v_dat(100) := NULL;
FORALL i IN v_dat.FIRST..v_dat.LAST
commit;
END;
/*
Error Message :
ORA-06512: at line 15
*/
DECLARE
BEGIN
FOR i in 1..200
LOOP
v_dat.EXTEND;
v_dat(v_dat.LAST) := i;
END LOOP;
v_dat(100) := NULL;
FORALL i IN v_dat.FIRST..v_dat.LAST
COMMIT;
EXCEPTION
END;
END;
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
The total number of exceptions can be returned using the collections COUNT method,
DECLARE
v_ex_count NUMBER(4);
abort_ex EXCEPTION;
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;
BEGIN
COMMIT;
EXCEPTION
v_ex_count := SQL%BULK_EXCEPTIONS.COUNT;
END LOOP;
END;
END;
/*
Sample output:
*/
COUNT(*)
-------
198
SAVE EXCEPTIONS clause being removed, in the above script now traps a different error number.
/*
Sample output:
*/
SELECT COUNT(*) FROM bulk_tb;
COUNT(*)
-------
99
0 Add a comment
SEP
29
/************************************************************************
* FOR UPDATE clause in oracle *
************************************************************************/
BEGIN
END LOOP;
commit;
END;
DECLARE
CURSOR PROD_DTLS_C IS
V_PRDNAME PROD_DETAILS.P_NAME%TYPE;
BEGIN
OPEN PROD_DTLS_C;
LOOP
IF PROD_DTLS_C%NOTFOUND THEN
EXIT;
ELSE
UPDATE PROD_DETAILS P
END IF;
END LOOP;
CLOSE PROD_DTLS_C;
COMMIT;
END;
BEGIN
END LOOP;
commit;
END;
DECLARE
CURSOR PROD_DTLS_C IS
V_PID PROD_DETAILS.P_ID%TYPE;
V_PRDNAME PROD_DETAILS.P_NAME%TYPE;
BEGIN
OPEN PROD_DTLS_C;
LOOP
IF PROD_DTLS_C%NOTFOUND THEN
EXIT;
ELSE
UPDATE PROD_DETAILS P
END IF;
COMMIT;
END LOOP;
CLOSE PROD_DTLS_C;
--COMMIT;
END;
0 Add a comment
MAY
28
FROM Dual;
FROM Dual;
SAL_DETAILS
---------------------------------------
FROM Dual;
Info
---------------------------------------
SELECT q'[some test ' some test ' some text ']' AS "In 10g"
FROM dual;
In 10g
------------------------------------
The '_' wild card character is used to match exactly one character
WITH mail_ids AS
UNION
UNION
----------------------------------
an_murugappan@gmail.com
WITH mail_ids AS
UNION
UNION
SELECT 'an%murugappan@gmail.com' mail FROM Dual
----------------------------------
an%murugappan@gmail.com
'23'
----
23
'&A'
----
&a
SQL> SET SCAN OFF;
'&A'
----
&a
'45'
----
45
0 Add a comment
MAY
28
DELETE - deletes all records from a table, the space for the records remain
prod_id NUMBER(4) ,
prod_name VARCHAR2(30) ,
comments VARCHAR2(300)
);
no_data_found
INSERT
INSERT INTO prod_details(prod_id,prod_name,order_dt,deliver_dt,comments)
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
--Inserting selective number of values
VALUES(103,'Moto X','11-May-14','13-May-14');
VALUES(103,'Moto X','11-May-14','13-May-14');
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
VALUES(104,'Moto G','19-May-14','22-May-14',NULL);
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
--if you are not providing values for order_dt and deliver_dt column default value can be taken.
----------------------------------------------------------------------------
---------------------------------------------------------------------------
COUNT(*)
-------
3
--creating table by using sub query (with out data)
WHERE id = 900;
COUNT(*)
-------
COUNT(*)
-------
UPDATE
Syntax :
UPDATE table_name
column2_name = column2_value,
column2_name = column3_value,
columnn_name = columnn_value
WHERE condition(s);
----------------------------------------------------------------------
---------------------------------------------------------------------------
UPDATE prod_details ps
SELECT *
FROM prod_details ps
--------------------------------------------------------------------
--------------------------------------------------------------------
--If you try to execute update statement without condition it'll update all the records inside the
table.
UPDATE prod_details ps
SELECT *
---------------------------------------------------------------------------
---------------------------------------------------------------------------
----------------------------------------------------------------------
--if your update text contain ' means you can use following metnod (use '')
UPDATE prod_details ps
SELECT *
FROM prod_details ps
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
DELETE
Syntax:
WHERE condition(s);
DELETE FROM prod_details
SELECT *
---------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------
100 Apple iphone 5s 5/21/2014 5/24/2014 Some product's are not available
---------------------------------------------------------------------------------------
0 Add a comment
MAY
28
Data Definition Language (DDL) statements are used to define the database structure or schema.
Some examples:
RENAME
MODIFY
DROP
Creating Table
--------------------------------------------------------------------------
--------------------------------------------------------------------------
S: -84 to 127
VARCHAR2 4000 Bytes we can store 0-9, a-z, A-Z and special characters
--------------------------------------------------------------------------
CREATE
RENAME
DROP
TRUNCATE
--creating table
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)
-----------------------------
ADD : Used to add a column after the table hase been created
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)
-----------------------------
SYNTAX
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
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
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)
-----------------------------
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.
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)
-----------------------------
SYNTAX
RENAME old_table_name TO new_table_name;
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
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
0 Add a comment
MAY
28
Statements in Oracle
DDL statements are used to define the database structure or schema. Some examples:
ADD
RENAME
MODIFY
DROP
DML statements are used for managing data within schema objects. Some examples:
DELETE - deletes all records from a table, the space for the records remain
TCL statements are used to manage the changes made by DML statements. It allows
statements to be grouped together into logical transactions.
SAVEPOINT - identify a point in a transaction to which you can later roll back
0 Add a comment
MAY
19
roll_no NUMBER(4) ,
Name VARCHAR2(30) ,
dept_cd VARCHAR2(20) ,
total_marks NUMBER(3)
);
BEGIN
END;
DECODE
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',
'IT',
'Information Technology',
FROM students;
Sample Output
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
CASE
SELECT roll_no,
NAME,
dept_cd,
total_marks,
CASE
'A Grade'
'B Grade'
'C Grade'
ELSE
'U Grade'
END AS "GRADE"
FROM students;
-----------------------------------------------
-----------------------------------------------
-----------------------------------------------
Interview Questions:
What is DECODE?
What is CASE?
0 Add a comment
MAY
19
Sub Query
Want to fetch the person Who are all getting salary more than Neena's salary ?
From Employees
Sub Query :
From Employees
);
Select * from employees;
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
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
);
From Employees
);
From Employees
);
From Employees
);
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,
FROM
Dual;
Where Department_id = 60
);
FROM employees
);
0 Add a comment
Loading
search
JUL
20
--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
, AVG(b.salary) avg_sal
FROM employees b
GROUP BY b.department_id
)b
Display all the customer who have placed more number of orders by using INLINE view
( custm_id NUMBER ,
custm_nm VARCHAR2(30) ,
);
BEGIN
COMMIT;
END;
SELECT c.*
FROM customer_order_det_tb c;
--------------------------------------------
--------------------------------------------
--------------------------------------------
--Writing a Quer to display all the customer who have placed maximum number of order
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
--------------------------------
--------------------------------
100 Murugappan 2
102 Ramesh 2
101 Raja 1
--------------------------------
----------
total_odr
----------
----------
Inline view to find all the customers who have placed maximum number of orders
/****************************************
Syntax
WHERE contition;
****************************************/
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
) query1,
) query2
-------------------------------
100 Murugappan 2
102 Ramesh 2
-------------------------------
--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT
FROM employees e
Example :
--in 11g
SELECT *
FROM departments d
--in 12c
SELECT *
FROM departments d
);
--in 11g
WITH t
AS
( SELECT LEVEL a
FROM dual
SELECT *
FROM t, (SELECT *
FROM employees
);
--in 12c
WITH t
AS
SELECT * FROM t,
LATERAL(SELECT *
FROM employees
0 Add a comment
JAN
23
--creating table
eid NUMBER(4),
ename VARCHAR2(30),
depno NUMBER(3),
salary NUMBER(8)
);
BEGIN
--Inserting records
COMMIT;
END;
FROM employee_data
FROM employee_data);
SELECT MIN(salary)
FROM employee_data
SELECT MIN(salary)
FROM employee_data
--query to select all the details of the employee whose getting nth maximum salary
SELECT *
rownum rn
FROM (SELECT *
FROM employee_data
WHERE rn = 9;
SELECT *
WHERE rank = 9;
SELECT *
WHERE rank = 4;
--same query using dense_rank( ) function
SELECT *
WHERE rank = 4;
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
--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
--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,
first_name,
salary
FROM employees
7 View comments
JAN
22
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.
14 rows selected.
Elapsed: 00:00:14.01
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.
0 Add a comment
DEC
21
Constraints
Format : [part_of_project_name-table_name-column_name-constraint_type]
Format : sys_cn
Example : SYS_C405323
Types
Primary Key
Ex : Employee_id, Student_id
Unique Key
Ex : Contact_no, email
Foreign Key
c1(pk) : 1 2 3
Check
------------------------------------
Duplicate NULL
------------------------------------
Primary Key X X
------------------------------------
S_id Number(2),
s_mail Varchar2(30),
s_gender char(1),
s_did Number(3),
);
DESC my_stu_details;
------------------------------------
------------------------------------
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)
--Duplicate Check
Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)
--Null Check
--------------------------------------------------------
--------------------------------------------------------
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
--------------------------------------------------------
------------------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
-------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
ON DELETE CASCADE
SELECT c.owner,
c.constraint_name,
c.constraint_type,
c.table_name,
c.r_constraint_name,
c.status
FROM user_constraints c
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.
Interview Questions
Which Data Dictionary table contains information about constraint with corresponding column
name?
1 View comments
good
Reply
DEC
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 :
--Example 1:
commit;
END;
listagg(product,
',') within
FROM test_ins
GROUP BY empid;
-->-- Example 2
FROM employees
GROUP BY department_id;
0 Add a comment
NOV
IF
IF ELSE
Multiple IF ELSE
LOOP
FOR LOOP
WHILE LOOP
BEGIN
INSERT INTO test_udt VALUES(001,23000);
Commit;
END;
IF
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 1;
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;
UPDATE test_udt t
ELSE
UPDATE test_udt t
END IF;
commit;
END;
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 2;
v_salary := v_salary+10005;
ELSE
v_salary := v_salary+20007;
END IF;
UPDATE test_udt t
commit;
END;
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');
v_salary := 3000;
dbms_output.put_line('3 inside');
v_salary := 4000;
dbms_output.put_line('4 inside');
END IF;
UPDATE test_udt t
commit;
END;
LOOP
--syntax
LOOP
--statements
--increment
--exit statement
END LOOP;
DECLARE
i NUMBER := 1;
x VARCHAR2(3);
BEGIN
LOOP
x := lpad(i,3,'0');
i := i+1;
IF MOD(i,100) = 0 THEN
commit;
dbms_output.put_line('commit executed');
END IF;
END LOOP;
END;
FOR LOOP
BEGIN
FOR I in 1..5
LOOP
END LOOP;
END;
BEGIN
LOOP
END LOOP;
END;
/
WHILE LOOP
DECLARE
i_val NUMBER:=0;
BEGIN
LOOP
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
0 Add a comment
OCT
21
Bulk Collect
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;
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
INTO dta;
CLOSE proddt_cur;
END LOOP;
END;
dta alldata_typ;
BEGIN
END LOOP;
END;
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
FOR i IN dta.FIRST .. dta.COUNT LOOP
END LOOP;
END;
DECLARE
dta1 alldata_typ1;
dta2 alldata_typ2;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
FOR i IN dta1.FIRST .. dta1.COUNT LOOP
END LOOP;
END LOOP;
END;
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.
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.
AS
BEGIN
OPEN dep_det_c
FOR
END;
DECLARE
dep_det_c SYS_REFCURSOR;
tab_data dep_details%ROWTYPE;
BEGIN
ref_c_sp(dep_det_c);
LOOP
END LOOP;
CLOSE dep_det_c;
END;
/*sample output*/
Department Name : HR
0 Add a comment
OCT
21
Cursor
SQL Private work Area where the query get passed and executed.
Types
******
Implicit(SQL)
Explicit
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
Cursor Stages
**************
OPEN cursor_name
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
Cursor Declaration
DECLARE
CURSOR <cursor_name>
IS
<SELECT statement>
BEGIN
END;
Cursor Loop
Loop
While Loop
For Loop
Cursor Clauses
Return
For update
Where current of
Bulk collect
p_id NUMBER,
p_name VARCHAR2(30),
p_order_dt DATE
);
-->-- Inserting data
BEGIN
FOR i IN 1 .. 75 LOOP
END LOOP;
commit;
END;
---------------------------------------------
---------------------------------------------
---------------------------------------------
----------------------------------------------
Implicit Cursor
----------------------------------------------
----------------------------------------------
Explicit Cursor
----------------------------------------------
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
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
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
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*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
**********************************************
**********************************************
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;
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
************************************************************
DECLARE
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
FOR i IN prod_detail_cur
LOOP
END LOOP;
END;
/*sample output*/
*********************
This was used when you are going to use the cursor in more than one place with different
values for the same where clause.
BEGIN
commit;
END;
----------------------------
1 Admin 1010
2 HR 1010
3 Sales 1020
4 Marketing 1020
----------------------------
DECLARE
all_data dep_details%ROWTYPE;
BEGIN
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1010);
LOOP
FETCH dep_det_c
INTO all_data;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1020);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
END;
/*sample output*/
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
0 Add a comment
OCT
21
Handling Exception
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
Predefined Exception
*********************
Oracle has predefined several exceptions that correspond to the most common oracle errors.
------------------------------------------------------------------------
------------------------------------------------------------------------
DUP_VAL_ON_INDEX ORA-00001 -1
------------------------------------------------------------------------
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
Single row SELECT returned no rows or your program referenced a deleted element in a nested
table
v_id NUMBER;
BEGIN
EXCEPTION
END;
commit;
BEGIN
EXCEPTION
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
DECLARE
num1 NUMBER(2);
BEGIN
num1 := 345;
EXCEPTION
END;
BEGIN
COMMIT;
END;
SELECT * FROM emp;
DECLARE
cursor emp_c IS
all_data emp%ROWTYPE;
BEGIN
OPEN emp_c;
OPEN emp_c;
NULL;
CLOSE emp_c;
EXCEPTION
END;
DECLARE
v_result NUMBER;
BEGIN
END;
**********************
User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,
DECLARE
gender_ex EXCEPTION;
BEGIN
RAISE gender_ex;
END IF;
dbms_output.put_line('Gender : '||v_gender);
EXCEPTION
END;
DECLARE
abort_ex EXCEPTION;
BEGIN
FOR i IN 1..100
LOOP
BEGIN
IF mod(i,10)=0 THEN
RAISE abort_ex;
END IF;
EXCEPTION
NULL;
END;
END LOOP;
COMMIT;
END;
SELECT * FROM test_insert;
********************
SQLCODE returns the current error code, and SQLERRM returns the current error message
text;
SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.
DECLARE
v_id NUMBER;
BEGIN
dbms_output.put_line(v_id);
EXCEPTION
END;
/*sample output*/
SQLCODE : 100
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:
DECLARE
v_result NUMBER;
BEGIN
SELECT 453 / 0 INTO v_result FROM dual;
EXCEPTION
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 :
DECLARE
BEGIN
END IF;
END;
1 View comments
How to get the two table data without using Joins and sub query,union?
Reply
OCT
Package
I) specification
II) Body
3. It allows the oracle server to read multiple object in to a memory once
5. Overloading
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;
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_sal_sp;
BEGIN
END;
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_hdt_sp;
BEGIN
RETURN NUMBER
IS
v_c NUMBER;
BEGIN
RETURN v_c;
END;
--Specification Part
IS
RETURN NUMBER;
END emp_pkg ;
--Body Part
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_sal_sp;
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_hdt_sp;
RETURN NUMBER
IS
v_c NUMBER;
BEGIN
RETURN v_c;
END;
END emp_pkg;
emp_pkg.emp_sal_sp(120);
END;
as
RETURN NUMBER;
IS
SELECT first_name, salary, hire_date, department_id
FROM employees;
End all_detail;
as
AS
BEGIN
SELECT salary
INTO c
FROM Employees
WHERE Employee_id = a;
EXCEPTION
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;
EXCEPTION
END emp2exep;
RETURN NUMBER
AS
BEGIN
c := a+b;
RETURN C;
END;
End all_detail;
/*Declaring a Bodiless Package */
IS
END global_constant;
BEGIN
END;
DECLARE
PROCEDURE P3;
PROCEDURE P1 IS
BEGIN
p2;
END P1;
PROCEDURE P2 IS
BEGIN
p3;
END P2;
PROCEDURE P3 IS
BEGIN
END P3;
BEGIN
p1;
END;
sample output:
From procedure p1
From procedure p2
From procedure p3
Interview Questions:
What is package?
Advantage of package
OCT
p_id NUMBER(3),
p_nm VARCHAR2(30),
p_qty NUMBER(8),
order_dt DATE
);
BEGIN
commit;
END;
------------------------------------
------------------------------------
------------------------------------
DECLARE
v_name VARCHAR2(4);
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
DECLARE
v_name VARCHAR2(5);
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
(106,
'name6',
700,
'26-Dec-12');
commit;
DECLARE
v_name VARCHAR2(5);
BEGIN
FROM product_details
--error
END;
/
DECLARE
v_name product_details.p_nm%TYPE;
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
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
END;
--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
END;
dept_id number(3) ,
dept_name varchar2(30),
dept_manager_name varchar2(30)
);
-------------------------------------------------------
+------------+-----------------------+-----------------
| 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
END;
---------------------------------------------------
---------------------------------------------------
| 20 | dept2 | manager_name2 |
---------------------------------------------------
Interview Question :
0 Add a comment
SEP
29
BULK Exceptions
/************************************************************************
* Reference : http://www.dba-oracle.com/plsql/t_plsql_exceptions.htm *
************************************************************************/
DECLARE
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
commit;
END;
COUNT(*)
-------
200
TRUNCATE TABLE bulk_tb;
DECLARE
BEGIN
FOR i in 1..200
LOOP
v_dat.EXTEND;
v_dat(v_dat.LAST) := i;
END LOOP;
v_dat(100) := NULL;
FORALL i IN v_dat.FIRST..v_dat.LAST
END;
/*
Error Message :
ORA-06512: at line 15
*/
DECLARE
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
BEGIN
FORALL i IN v_dat.FIRST..v_dat.LAST
COMMIT;
EXCEPTION
END;
END;
COUNT(*)
-------
99
SQL%BULK_EXCEPTIONS(i).ERROR_INDEX
Holds the iteration (not the subscript) of the original FORALL statement that raised the
exception.
the exception row must be found by looping through the original collection the correct
number of times.
SQL%BULK_EXCEPTIONS(i).ERROR_CODE
The total number of exceptions can be returned using the collections COUNT method,
DECLARE
v_ex_count NUMBER(4);
abort_ex EXCEPTION;
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;
BEGIN
COMMIT;
EXCEPTION
v_ex_count := SQL%BULK_EXCEPTIONS.COUNT;
END LOOP;
END;
END;
/*
Sample output:
*/
COUNT(*)
-------
198
SAVE EXCEPTIONS clause being removed, in the above script now traps a different error number.
/*
Sample output:
Error: 1 Array Index: 100 Message: -1400: non-ORACLE exception
*/
COUNT(*)
-------
99
0 Add a comment
SEP
29
************************************************************************/
BEGIN
END LOOP;
commit;
END;
DECLARE
CURSOR PROD_DTLS_C IS
V_PID PROD_DETAILS.P_ID%TYPE;
V_PRDNAME PROD_DETAILS.P_NAME%TYPE;
BEGIN
OPEN PROD_DTLS_C;
LOOP
IF PROD_DTLS_C%NOTFOUND THEN
EXIT;
ELSE
UPDATE PROD_DETAILS P
END IF;
END LOOP;
CLOSE PROD_DTLS_C;
COMMIT;
END;
select * from PROD_DETAILS;
BEGIN
END LOOP;
commit;
END;
DECLARE
CURSOR PROD_DTLS_C IS
V_PID PROD_DETAILS.P_ID%TYPE;
V_PRDNAME PROD_DETAILS.P_NAME%TYPE;
BEGIN
OPEN PROD_DTLS_C;
LOOP
IF PROD_DTLS_C%NOTFOUND THEN
EXIT;
ELSE
UPDATE PROD_DETAILS P
END IF;
COMMIT;
END LOOP;
CLOSE PROD_DTLS_C;
--COMMIT;
END;
MAY
28
FROM Dual;
FROM Dual;
SAL_DETAILS
---------------------------------------
FROM Dual;
Info
---------------------------------------
SELECT q'[some test ' some test ' some text ']' AS "In 10g"
FROM dual;
In 10g
------------------------------------
The '_' wild card character is used to match exactly one character
WITH mail_ids AS
UNION
UNION
----------------------------------
an_murugappan@gmail.com
WITH mail_ids AS
UNION
----------------------------------
an%murugappan@gmail.com
'23'
----
23
----
&a
'&A'
----
&a
'45'
----
45
0 Add a comment
MAY
28
Data Manipulation Language (DML) statements are used for managing data within schema
objects. Some examples:
DELETE - deletes all records from a table, the space for the records remain
prod_id NUMBER(4) ,
prod_name VARCHAR2(30) ,
comments VARCHAR2(300)
);
INSERT
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black
---------------------------------------------------------------------------
VALUES(103,'Moto X','11-May-14','13-May-14');
VALUES(103,'Moto X','11-May-14','13-May-14');
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--If you want to insert NULL value you can ignore that column at the time of inserting
VALUES(104,'Moto G','19-May-14','22-May-14',NULL);
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
--if you are not providing values for order_dt and deliver_dt column default value can be taken.
---------------------------------------------------------------------------
----------------------------------------------------------------------------
---------------------------------------------------------------------------
-------
WHERE id = 900;
COUNT(*)
-------
COUNT(*)
-------
UPDATE
Syntax :
UPDATE table_name
column2_name = column2_value,
column2_name = column3_value,
columnn_name = columnn_value
WHERE condition(s);
SELECT * FROM prod_details;
---------------------------------------------------------------------------
----------------------------------------------------------------------
---------------------------------------------------------------------------
UPDATE prod_details ps
SELECT *
FROM prod_details ps
--------------------------------------------------------------------
PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS
--------------------------------------------------------------------
--------------------------------------------------------------------
--If you try to execute update statement without condition it'll update all the records inside the
table.
UPDATE prod_details ps
SELECT *
---------------------------------------------------------------------------
---------------------------------------------------------------------------
----------------------------------------------------------------------
--if your update text contain ' means you can use following metnod (use '')
UPDATE prod_details ps
SELECT *
FROM prod_details ps
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
DELETE
Syntax:
DELETE FROM table_name
WHERE condition(s);
SELECT *
---------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------
100 Apple iphone 5s 5/21/2014 5/24/2014 Some product's are not available
---------------------------------------------------------------------------------------
no rows selected.
0 Add a comment
MAY
28
Data Definition Language (DDL) statements are used to define the database structure or schema.
Some examples:
CREATE - to create objects in the database.
ADD
RENAME
MODIFY
DROP
Creating Table
--------------------------------------------------------------------------
--------------------------------------------------------------------------
S: -84 to 127
VARCHAR2 4000 Bytes we can store 0-9, a-z, A-Z and special characters
--------------------------------------------------------------------------
CREATE
RENAME
DROP
TRUNCATE
--creating table
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)
-----------------------------
ADD : Used to add a column after the table hase been created
-----------------------------
NAME TYPE
-----------------------------
NAME VARCHAR2(30)
PHONE NUMBER(10)
GENDER CHAR(1)
DOB DATE
OTHER_DETAILS LONG
MAKE_DTM TIMESTAMP(6)
EMAIL VARCHAR2(30)
-----------------------------
SYNTAX
ADD (
column_1 Data_type(size),
column_2 Data_type(size),
column_3 Data_type(size),
column_4 Data_type(size)
);
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.
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)
-----------------------------
column_name_3 new_datatype(new_size)
);
DROP : Used to drop the column after the table has been created.
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)
-----------------------------
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
DROP : Used to drop the tabel (Data + stucture of the table get removed from the database )
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
0 Add a comment
MAY
28
Statements in Oracle
DDL statements are used to define the database structure or schema. Some examples:
CREATE - to create objects in the database
ADD
RENAME
MODIFY
DROP
DML statements are used for managing data within schema objects. Some examples:
DELETE - deletes all records from a table, the space for the records remain
TCL statements are used to manage the changes made by DML statements. It allows
statements to be grouped together into logical transactions.
SAVEPOINT - identify a point in a transaction to which you can later roll back
0 Add a comment
MAY
19
roll_no NUMBER(4) ,
Name VARCHAR2(30) ,
dept_cd VARCHAR2(20) ,
total_marks NUMBER(3)
);
BEGIN
END;
DECODE
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',
'IT',
'Information Technology',
FROM students;
Sample Output
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
CASE
Example
SELECT roll_no,
NAME,
dept_cd,
total_marks,
CASE
'A Grade'
'B Grade'
'C Grade'
ELSE
'U Grade'
END AS "GRADE"
FROM students;
-----------------------------------------------
-----------------------------------------------
2000 Rahul CSE 480 B Grade
-----------------------------------------------
Interview Questions:
What is DECODE?
What is CASE?
0 Add a comment
MAY
19
Sub Query
Want to fetch the person Who are all getting salary more than Neena's salary ?
From Employees
Sub Query :
From Employees
);
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
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
);
From Employees
);
From Employees
);
From Employees
);
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
FROM
Dual;
Where Department_id = 60
);
SELECT AVG(salary)
FROM employees
);
0 Add a comment
Loading
search
JUL
20
INLINE view in Oracle with 12c New Features
--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
, AVG(b.salary) avg_sal
FROM employees b
GROUP BY b.department_id
)b
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) ,
ttl_amt NUMBER(7,2)
);
BEGIN
COMMIT;
END;
SELECT c.*
FROM customer_order_det_tb c;
--------------------------------------------
--------------------------------------------
--------------------------------------------
--Writing a Quer to display all the customer who have placed maximum number of order
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
--------------------------------
--------------------------------
100 Murugappan 2
102 Ramesh 2
101 Raja 1
--------------------------------
----------
total_odr
----------
----------
Inline view to find all the customers who have placed maximum number of orders
/****************************************
Syntax
WHERE contition;
****************************************/
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
) query1,
) query2
-------------------------------
-------------------------------
100 Murugappan 2
102 Ramesh 2
-------------------------------
--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT
FROM employees e
Example :
--in 11g
SELECT *
FROM departments d
--in 12c
SELECT *
FROM departments d
);
--in 11g
WITH t
AS
( SELECT LEVEL a
FROM dual
SELECT *
FROM t, (SELECT *
FROM employees
);
--in 12c
WITH t
AS
SELECT * FROM t,
LATERAL(SELECT *
FROM employees
0 Add a comment
JAN
23
--creating table
eid NUMBER(4),
ename VARCHAR2(30),
depno NUMBER(3),
salary NUMBER(8)
);
BEGIN
--Inserting records
COMMIT;
END;
SELECT MAX(salary)
FROM employee_data
FROM employee_data);
SELECT MIN(salary)
FROM employee_data
SELECT MIN(salary)
FROM employee_data
ORDER BY salary DESC)
--query to select all the details of the employee whose getting nth maximum salary
SELECT *
rownum rn
FROM (SELECT *
FROM employee_data
WHERE rn = 9;
SELECT *
WHERE rank = 9;
SELECT *
FROM (SELECT emp.*,
WHERE rank = 4;
SELECT *
WHERE rank = 4;
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 employee_id,
first_name,
salary
FROM employees
--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,
first_name,
salary
FROM employees
7 View comments
JAN
22
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.
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.
14 rows selected.
Elapsed: 00:00:14.01
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.
0 Add a comment
DEC
21
Constraints
Format : [part_of_project_name-table_name-column_name-constraint_type]
Format : sys_cn
Example : SYS_C405323
We can create constraint after the table has been created
Types
Primary Key
Ex : Employee_id, Student_id
Unique Key
Ex : Contact_no, email
Foreign Key
c1(pk) : 1 2 3
Not Null
Check
------------------------------------
Duplicate NULL
------------------------------------
Primary Key X X
------------------------------------
S_id Number(2),
s_mail Varchar2(30),
s_gender char(1),
s_did Number(3),
);
DESC my_stu_details;
------------------------------------
------------------------------------
S_ID NUMBER(2)
S_NAME VARCHAR2(30)
S_MAIL VARCHAR2(30) Y
S_GENDER CHAR(1) Y
S_DID NUMBER(3) Y
------------------------------------
--Null Check
--------------------------------------------------------
--------------------------------------------------------
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
--------------------------------------------------------
------------------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
-------------------------------------------------
-------------------------------------------------
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
ON DELETE CASCADE
SELECT c.owner,
c.constraint_name,
c.constraint_type,
c.table_name,
c.r_constraint_name,
c.status
FROM user_constraints c
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.
Interview Questions
Which Data Dictionary table contains information about constraint with corresponding column
name?
1 View comments
good
Reply
DEC
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 :
BEGIN
commit;
END;
listagg(product,
',') within
FROM test_ins
GROUP BY empid;
-->-- Example 2
FROM employees
GROUP BY department_id;
-->-- Result set --<--
0 Add a comment
NOV
IF
IF ELSE
Multiple IF ELSE
LOOP
FOR LOOP
WHILE LOOP
create table test_udt(id NUMBER, salary NUMBER);
BEGIN
Commit;
END;
IF
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 1;
UPDATE test_udt t
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;
UPDATE test_udt t
SET t.salary = v_salary+10005
ELSE
UPDATE test_udt t
END IF;
commit;
END;
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 2;
v_salary := v_salary+10005;
ELSE
v_salary := v_salary+20007;
END IF;
UPDATE test_udt t
commit;
END;
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');
v_salary := 2000;
dbms_output.put_line('2 inside');
v_salary := 3000;
dbms_output.put_line('3 inside');
v_salary := 4000;
dbms_output.put_line('4 inside');
END IF;
UPDATE test_udt t
commit;
END;
LOOP
--syntax
LOOP
--statements
--increment
--exit statement
END LOOP;
DECLARE
i NUMBER := 1;
x VARCHAR2(3);
BEGIN
LOOP
x := lpad(i,3,'0');
i := i+1;
IF MOD(i,100) = 0 THEN
commit;
dbms_output.put_line('commit executed');
END IF;
END LOOP;
END;
FOR LOOP
BEGIN
FOR I in 1..5
LOOP
END LOOP;
END;
BEGIN
LOOP
Dbms_output.put_line('The value of i : '||i);
END LOOP;
END;
WHILE LOOP
DECLARE
i_val NUMBER:=0;
BEGIN
LOOP
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
0 Add a comment
OCT
21
Bulk Collect
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;
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
INTO dta;
CLOSE proddt_cur;
END LOOP;
END;
/
-->-- Bulk collect in SELECT clause --<--
DECLARE
dta alldata_typ;
BEGIN
END LOOP;
END;
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta1 alldata_typ1;
dta2 alldata_typ2;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END LOOP;
END;
0 Add a comment
OCT
21
Ref Cursor
This is unconstrained cursor which will return different types depends upon the user input.
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.
AS
BEGIN
OPEN dep_det_c
FOR
END;
DECLARE
dep_det_c SYS_REFCURSOR;
tab_data dep_details%ROWTYPE;
BEGIN
ref_c_sp(dep_det_c);
LOOP
END LOOP;
CLOSE dep_det_c;
END;
/*sample output*/
Department Name : HR
0 Add a comment
OCT
21
Cursor
SQL Private work Area where the query get passed and executed.
Types
******
Implicit(SQL)
Explicit
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
**************
OPEN cursor_name
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
Cursor Declaration
DECLARE
CURSOR <cursor_name>
IS
<SELECT statement>
BEGIN
END;
Cursor Loop
Loop
While Loop
For Loop
Cursor Clauses
Return
For update
Where current of
Bulk collect
p_id NUMBER,
p_name VARCHAR2(30),
p_order_dt DATE
);
BEGIN
FOR i IN 1 .. 75 LOOP
END LOOP;
commit;
END;
---------------------------------------------
---------------------------------------------
---------------------------------------------
----------------------------------------------
Implicit Cursor
----------------------------------------------
Explicit Cursor
----------------------------------------------
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
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
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
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*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
EXIT WHEN prod_detail_cur%NOTFOUND;
END LOOP;
CLOSE prod_detail_cur;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
END IF;
END;
/*sample output*/
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
FETCH prod_detail_cur
INTO all_data;
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
************************************************************
************************************************************
DECLARE
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
FOR i IN prod_detail_cur
LOOP
END LOOP;
END;
/*sample output*/
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.
BEGIN
commit;
END;
SELECT * FROM dep_details;
----------------------------
----------------------------
1 Admin 1010
2 HR 1010
3 Sales 1020
4 Marketing 1020
----------------------------
DECLARE
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;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1020);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
END;
/*sample output*/
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
0 Add a comment
OCT
21
Handling Exception
ERROR
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
Predefined Exception
*********************
Oracle has predefined several exceptions that correspond to the most common oracle errors.
------------------------------------------------------------------------
------------------------------------------------------------------------
DUP_VAL_ON_INDEX ORA-00001 -1
TOO_MANY_ROWS ORA-01422 -1422
OTHERS
------------------------------------------------------------------------
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
Single row SELECT returned no rows or your program referenced a deleted element in a nested
table
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
commit;
BEGIN
END;
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
DECLARE
num1 NUMBER(2);
BEGIN
num1 := 345;
EXCEPTION
END;
BEGIN
COMMIT;
END;
DECLARE
cursor emp_c IS
all_data emp%ROWTYPE;
BEGIN
OPEN emp_c;
OPEN emp_c;
NULL;
CLOSE emp_c;
EXCEPTION
END;
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
**********************
User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,
DECLARE
gender_ex EXCEPTION;
BEGIN
END IF;
dbms_output.put_line('Gender : '||v_gender);
EXCEPTION
END;
DECLARE
abort_ex EXCEPTION;
BEGIN
FOR i IN 1..100
LOOP
BEGIN
IF mod(i,10)=0 THEN
RAISE abort_ex;
END IF;
EXCEPTION
NULL;
END;
END LOOP;
COMMIT;
END;
********************
SQLCODE returns the current error code, and SQLERRM returns the current error message
text;
SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.
DECLARE
v_id NUMBER;
BEGIN
dbms_output.put_line(v_id);
EXCEPTION
END;
/*sample output*/
SQLCODE : 100
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:
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
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 :
DECLARE
v_gender CHAR := '&gender';
BEGIN
END IF;
END;
1 View comments
How to get the two table data without using Joins and sub query,union?
Reply
OCT
Package
I) specification
II) Body
5. Overloading
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_sal_sp;
BEGIN
END;
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_hdt_sp;
BEGIN
END;
RETURN NUMBER
IS
v_c NUMBER;
BEGIN
RETURN v_c;
END;
--Specification Part
IS
RETURN NUMBER;
END emp_pkg ;
--Body Part
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_sal_sp;
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_hdt_sp;
RETURN NUMBER
IS
v_c NUMBER;
BEGIN
RETURN v_c;
END;
END emp_pkg;
BEGIN
emp_pkg.emp_sal_sp(120);
END;
as
RETURN NUMBER;
IS
FROM employees;
End all_detail;
as
AS
BEGIN
SELECT salary
INTO c
FROM Employees
WHERE Employee_id = a;
EXCEPTION
AS
BEGIN
SELECT Round(Months_between(sysdate,hire_date)/12)
INTO c
FROM Employees
WHERE Employee_id = a;
EXCEPTION
END emp2exep;
RETURN NUMBER
AS
BEGIN
c := a+b;
RETURN C;
END;
End all_detail;
IS
END global_constant;
BEGIN
END;
DECLARE
PROCEDURE P2; -- forward declaration
PROCEDURE P3;
PROCEDURE P1 IS
BEGIN
p2;
END P1;
PROCEDURE P2 IS
BEGIN
p3;
END P2;
PROCEDURE P3 IS
BEGIN
END P3;
BEGIN
p1;
END;
sample output:
From procedure p1
From procedure p2
From procedure p3
Interview Questions:
What is package?
Advantage of package
0 Add a comment
OCT
p_id NUMBER(3),
p_nm VARCHAR2(30),
p_qty NUMBER(8),
order_dt DATE
);
BEGIN
commit;
END;
------------------------------------
------------------------------------
------------------------------------
DECLARE
v_name VARCHAR2(4);
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
DECLARE
v_name VARCHAR2(5);
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
VALUES
(106,
'name6',
700,
'26-Dec-12');
commit;
DECLARE
v_name VARCHAR2(5);
BEGIN
FROM product_details
--error
END;
/
DECLARE
v_name product_details.p_nm%TYPE;
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
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
END;
--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
END;
(
dept_id number(3) ,
dept_name varchar2(30),
dept_manager_name varchar2(30)
);
-------------------------------------------------------
+------------+-----------------------+-----------------
| 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
END;
---------------------------------------------------
---------------------------------------------------
| 20 | dept2 | manager_name2 |
---------------------------------------------------
Interview Question :
0 Add a comment
SEP
29
BULK Exceptions
/************************************************************************
* Reference : http://www.dba-oracle.com/plsql/t_plsql_exceptions.htm *
************************************************************************/
CREATE TABLE bulk_tb (ran_num NUMBER NOT NULL);
DECLARE
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
commit;
END;
-------
200
DECLARE
BEGIN
FOR i in 1..200
LOOP
v_dat.EXTEND;
v_dat(v_dat.LAST) := i;
END LOOP;
v_dat(100) := NULL;
commit;
END;
/*
Error Message :
ORA-06512: at line 15
*/
DECLARE
BEGIN
FOR i in 1..200
LOOP
v_dat.EXTEND;
v_dat(v_dat.LAST) := i;
END LOOP;
v_dat(100) := NULL;
BEGIN
FORALL i IN v_dat.FIRST..v_dat.LAST
COMMIT;
EXCEPTION
END;
END;
COUNT(*)
-------
99
SQL%BULK_EXCEPTIONS(i).ERROR_INDEX
Holds the iteration (not the subscript) of the original FORALL statement that raised the
exception.
the exception row must be found by looping through the original collection the correct
number of times.
SQL%BULK_EXCEPTIONS(i).ERROR_CODE
The total number of exceptions can be returned using the collections COUNT method,
DECLARE
v_ex_count NUMBER(4);
abort_ex EXCEPTION;
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;
BEGIN
COMMIT;
EXCEPTION
v_ex_count := SQL%BULK_EXCEPTIONS.COUNT;
END LOOP;
END;
END;
/*
Sample output:
*/
COUNT(*)
-------
198
SAVE EXCEPTIONS clause being removed, in the above script now traps a different error number.
Sample output:
*/
COUNT(*)
-------
99
0 Add a comment
SEP
29
/************************************************************************
************************************************************************/
BEGIN
END LOOP;
commit;
END;
CURSOR PROD_DTLS_C IS
V_PID PROD_DETAILS.P_ID%TYPE;
V_PRDNAME PROD_DETAILS.P_NAME%TYPE;
BEGIN
OPEN PROD_DTLS_C;
LOOP
IF PROD_DTLS_C%NOTFOUND THEN
EXIT;
ELSE
UPDATE PROD_DETAILS P
END IF;
END LOOP;
CLOSE PROD_DTLS_C;
COMMIT;
END;
BEGIN
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
IF PROD_DTLS_C%NOTFOUND THEN
EXIT;
ELSE
UPDATE PROD_DETAILS P
END IF;
COMMIT;
END LOOP;
CLOSE PROD_DTLS_C;
--COMMIT;
END;
select * from PROD_DETAILS;
0 Add a comment
MAY
28
FROM Dual;
FROM Dual;
SAL_DETAILS
---------------------------------------
FROM Dual;
Info
---------------------------------------
SELECT q'[some test ' some test ' some text ']' AS "In 10g"
FROM dual;
In 10g
------------------------------------
The '_' wild card character is used to match exactly one character
WITH mail_ids AS
UNION
UNION
----------------------------------
an_murugappan@gmail.com
WITH mail_ids AS
UNION
UNION
----------------------------------
an%murugappan@gmail.com
'23'
----
23
SQL> SET ESCAPE '\'
'&A'
----
&a
'&A'
----
&a
'45'
----
45
0 Add a comment
MAY
28
Data Manipulation Language (DML) statements are used for managing data within schema
objects. Some examples:
DELETE - deletes all records from a table, the space for the records remain
prod_id NUMBER(4) ,
prod_name VARCHAR2(30) ,
comments VARCHAR2(300)
);
SELECT * FROM prod_details;
no_data_found
INSERT
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
VALUES(103,'Moto X','11-May-14','13-May-14');
VALUES(103,'Moto X','11-May-14','13-May-14');
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
100 Apple iphone 5s 5/21/2014 5/24/2014 Color : Black
--------------------------------------------------------------------------------
--If you want to insert NULL value you can ignore that column at the time of inserting
VALUES(104,'Moto G','19-May-14','22-May-14',NULL);
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
--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)
---------------------------------------------------------------------------
----------------------------------------------------------------------------
---------------------------------------------------------------------------
COUNT(*)
-------
WHERE id = 900;
COUNT(*)
-------
COUNT(*)
-------
UPDATE
Syntax :
UPDATE table_name
column2_name = column2_value,
column2_name = column3_value,
columnn_name = columnn_value
WHERE condition(s);
---------------------------------------------------------------------------
----------------------------------------------------------------------
---------------------------------------------------------------------------
UPDATE prod_details ps
SELECT *
FROM prod_details ps
WHERE ps.prod_id = 100;
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--If you try to execute update statement without condition it'll update all the records inside the
table.
UPDATE prod_details ps
SELECT *
---------------------------------------------------------------------------
---------------------------------------------------------------------------
----------------------------------------------------------------------
--if your update text contain ' means you can use following metnod (use '')
UPDATE prod_details ps
SELECT *
FROM prod_details ps
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
DELETE
Syntax:
WHERE condition(s);
SELECT *
---------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------
100 Apple iphone 5s 5/21/2014 5/24/2014 Some product's are not available
---------------------------------------------------------------------------------------
DELETE FROM prod_details;
no rows selected.
0 Add a comment
MAY
28
Some examples:
ADD
RENAME
MODIFY
DROP
Creating Table
--------------------------------------------------------------------------
--------------------------------------------------------------------------
S: -84 to 127
VARCHAR2 4000 Bytes we can store 0-9, a-z, A-Z and special characters
CHAR 2000 Bytes 1
--------------------------------------------------------------------------
CREATE
RENAME
DROP
TRUNCATE
--creating table
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)
-----------------------------
ADD : Used to add a column after the table hase been created
ALTER TABLE friends_details_tb
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)
-----------------------------
SYNTAX
ADD (
column_1 Data_type(size),
column_2 Data_type(size),
column_3 Data_type(size),
column_4 Data_type(size)
);
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.
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)
-----------------------------
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.
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
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
DROP : Used to drop the tabel (Data + stucture of the table get removed from the database )
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
0 Add a comment
MAY
28
Statements in Oracle
ADD
RENAME
MODIFY
DROP
DML statements are used for managing data within schema objects. Some examples:
DELETE - deletes all records from a table, the space for the records remain
TCL statements are used to manage the changes made by DML statements. It allows
statements to be grouped together into logical transactions.
SAVEPOINT - identify a point in a transaction to which you can later roll back
0 Add a comment
MAY
19
roll_no NUMBER(4) ,
Name VARCHAR2(30) ,
dept_cd VARCHAR2(20) ,
total_marks NUMBER(3)
);
BEGIN
END;
DECODE
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',
'IT',
'Information Technology',
FROM students;
Sample Output
------------------------------------------------------------
------------------------------------------------------------
------------------------------------------------------------
CASE
Example
SELECT roll_no,
NAME,
dept_cd,
total_marks,
CASE
'A Grade'
'B Grade'
'C Grade'
ELSE
'U Grade'
END AS "GRADE"
FROM students;
-----------------------------------------------
-----------------------------------------------
-----------------------------------------------
Interview Questions:
What is DECODE?
What is CASE?
0 Add a comment
MAY
19
Sub Query
Query with in another query
Want to fetch the person Who are all getting salary more than Neena's salary ?
From Employees
Sub Query :
Select First_name, salary
From Employees
);
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
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
);
From Employees
);
Any : Minimum Value will be taken (3100)
From Employees
);
From Employees
);
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
FROM
Dual;
Where Department_id = 60
);
SELECT AVG(salary)
FROM employees
);
0 Add a comment
Loading
search
20
--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
, AVG(b.salary) avg_sal
FROM employees b
GROUP BY b.department_id
)b
( custm_id NUMBER ,
custm_nm VARCHAR2(30) ,
ttl_amt NUMBER(7,2)
);
BEGIN
COMMIT;
END;
SELECT c.*
FROM customer_order_det_tb c;
--------------------------------------------
--------------------------------------------
100 Murugappan 7/11/2015 45000.00
--------------------------------------------
--Writing a Quer to display all the customer who have placed maximum number of order
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
--------------------------------
--------------------------------
100 Murugappan 2
102 Ramesh 2
101 Raja 1
--------------------------------
----------
total_odr
----------
----------
Inline view to find all the customers who have placed maximum number of orders
/****************************************
Syntax
WHERE contition;
****************************************/
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
) query2
-------------------------------
-------------------------------
100 Murugappan 2
102 Ramesh 2
-------------------------------
--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT
FROM employees e
)
WHERE ROWNUM < 4;
Example :
--in 11g
SELECT *
FROM departments d
--in 12c
SELECT *
FROM departments d
--in 11g
WITH t
AS
( SELECT LEVEL a
FROM dual
SELECT *
FROM t, (SELECT *
FROM employees
);
--in 12c
WITH t
AS
SELECT * FROM t,
LATERAL(SELECT *
FROM employees
0 Add a comment
JAN
23
--creating table
eid NUMBER(4),
ename VARCHAR2(30),
depno NUMBER(3),
salary NUMBER(8)
);
BEGIN
--Inserting records
COMMIT;
END;
SELECT MAX(salary)
FROM employee_data
FROM employee_data);
SELECT MIN(salary)
FROM employee_data
SELECT MIN(salary)
FROM (SELECT salary
FROM employee_data
--query to select all the details of the employee whose getting nth maximum salary
SELECT *
rownum rn
FROM (SELECT *
FROM employee_data
WHERE rn = 9;
SELECT *
WHERE rank = 9;
--same query using rank( ) function
SELECT *
WHERE rank = 4;
SELECT *
WHERE rank = 4;
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
--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
--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,
first_name,
salary
FROM employees
7 View comments
JAN
22
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.
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.
14 rows selected.
Elapsed: 00:00:14.01
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.
DEC
21
Constraints
Format : [part_of_project_name-table_name-column_name-constraint_type]
Example : SYS_C405323
Types
Primary Key
Ex : Employee_id, Student_id
Unique Key
Ex : Contact_no, email
Foreign Key
Not Null
Check
------------------------------------
Duplicate NULL
------------------------------------
Primary Key X X
------------------------------------
creating table with all constraint type
S_id Number(2),
s_mail Varchar2(30),
s_gender char(1),
s_did Number(3),
);
DESC my_stu_details;
------------------------------------
------------------------------------
S_ID NUMBER(2)
S_NAME VARCHAR2(30)
S_MAIL VARCHAR2(30) Y
S_GENDER CHAR(1) Y
S_DID NUMBER(3) Y
------------------------------------
--Duplicate Check
--Null Check
--------------------------------------------------------
--------------------------------------------------------
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
--------------------------------------------------------
------------------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
-------------------------------------------------
-------------------------------------------------
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
ON DELETE CASCADE
SELECT c.owner,
c.constraint_name,
c.constraint_type,
c.table_name,
c.r_constraint_name,
c.status
FROM user_constraints c
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
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
Interview Questions
Which Data Dictionary table contains information about constraint with corresponding column
name?
1 View comments
good
Reply
DEC
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:
BEGIN
commit;
END;
listagg(product,
',') within
FROM test_ins
GROUP BY empid;
-->-- Example 2
GROUP BY department_id;
0 Add a comment
NOV
IF
IF ELSE
Multiple IF ELSE
LOOP
FOR LOOP
WHILE LOOP
create table test_udt(id NUMBER, salary NUMBER);
BEGIN
Commit;
END;
IF
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 1;
UPDATE test_udt t
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
ELSE
UPDATE test_udt t
END IF;
commit;
END;
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
commit;
END;
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');
v_salary := 2000;
dbms_output.put_line('2 inside');
v_salary := 3000;
dbms_output.put_line('3 inside');
v_salary := 4000;
dbms_output.put_line('4 inside');
END IF;
UPDATE test_udt t
commit;
END;
--syntax
LOOP
--statements
--increment
--exit statement
END LOOP;
DECLARE
i NUMBER := 1;
x VARCHAR2(3);
BEGIN
LOOP
x := lpad(i,3,'0');
i := i+1;
IF MOD(i,100) = 0 THEN
commit;
dbms_output.put_line('commit executed');
END IF;
END LOOP;
END;
FOR LOOP
BEGIN
FOR I in 1..5
LOOP
END LOOP;
END;
LOOP
END LOOP;
END;
WHILE LOOP
DECLARE
i_val NUMBER:=0;
BEGIN
LOOP
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
0 Add a comment
OCT
21
Bulk Collect
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.
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
INTO dta;
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta alldata_typ;
BEGIN
END LOOP;
END;
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta1 alldata_typ1;
dta2 alldata_typ2;
CURSOR proddt_cur IS
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END LOOP;
END;
0 Add a comment
OCT
21
Ref Cursor
This is unconstrained cursor which will return different types depends upon the user input.
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.
AS
BEGIN
OPEN dep_det_c
FOR
END;
DECLARE
dep_det_c SYS_REFCURSOR;
tab_data dep_details%ROWTYPE;
BEGIN
ref_c_sp(dep_det_c);
LOOP
END LOOP;
CLOSE dep_det_c;
END;
/*sample output*/
Department Name : HR
OCT
21
Cursor
SQL Private work Area where the query get passed and executed.
Types
******
Implicit(SQL)
Explicit
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
Cursor Stages
**************
OPEN cursor_name
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
Cursor Declaration
DECLARE
CURSOR <cursor_name>
IS
<SELECT statement>
BEGIN
END;
Cursor Loop
Loop
While Loop
For Loop
Cursor Clauses
Return
For update
Where current of
Bulk collect
p_id NUMBER,
p_name VARCHAR2(30),
p_order_dt DATE
);
BEGIN
FOR i IN 1 .. 75 LOOP
END LOOP;
commit;
END;
---------------------------------------------
---------------------------------------------
----------------------------------------------
Implicit Cursor
----------------------------------------------
----------------------------------------------
Explicit Cursor
----------------------------------------------
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
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 ||
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
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*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
FETCH prod_detail_cur
INTO all_data;
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 )
************************************************************
************************************************************
DECLARE
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
FOR i IN prod_detail_cur
LOOP
END LOOP;
END;
/*sample output*/
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.
BEGIN
commit;
END;
----------------------------
----------------------------
1 Admin 1010
2 HR 1010
3 Sales 1020
4 Marketing 1020
----------------------------
DECLARE
all_data dep_details%ROWTYPE;
BEGIN
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1010);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1020);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
END;
/
/*sample output*/
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
0 Add a comment
OCT
21
Handling Exception
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
Predefined Exception
*********************
Oracle has predefined several exceptions that correspond to the most common oracle errors.
------------------------------------------------------------------------
DUP_VAL_ON_INDEX ORA-00001 -1
OTHERS
------------------------------------------------------------------------
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
-->-- NO_DATA_FOUND --<--
Single row SELECT returned no rows or your program referenced a deleted element in a nested
table
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
commit;
BEGIN
EXCEPTION
END;
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
DROP TABLE test_tb;
DECLARE
num1 NUMBER(2);
BEGIN
num1 := 345;
EXCEPTION
END;
BEGIN
INSERT INTO emp VALUES(1,'Name1');
COMMIT;
END;
DECLARE
cursor emp_c IS
all_data emp%ROWTYPE;
BEGIN
OPEN emp_c;
OPEN emp_c;
NULL;
CLOSE emp_c;
EXCEPTION
END;
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
**********************
User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,
gender_ex EXCEPTION;
BEGIN
RAISE gender_ex;
END IF;
dbms_output.put_line('Gender : '||v_gender);
EXCEPTION
END;
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
NULL;
END;
END LOOP;
COMMIT;
END;
********************
SQLCODE returns the current error code, and SQLERRM returns the current error message
text;
SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.
v_id NUMBER;
BEGIN
dbms_output.put_line(v_id);
EXCEPTION
END;
/*sample output*/
SQLCODE : 100
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:
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
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
DECLARE
BEGIN
END IF;
END;
1 View comments
How to get the two table data without using Joins and sub query,union?
Reply
OCT
4
Package
I) specification
II) Body
5. Overloading
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_sal_sp;
BEGIN
END;
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_hdt_sp;
BEGIN
END;
RETURN NUMBER
IS
v_c NUMBER;
BEGIN
RETURN v_c;
END;
/
--Specification Part
IS
RETURN NUMBER;
END emp_pkg ;
--Body Part
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_sal_sp;
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
EXCEPTION
VALUES
(1,
USER,
v_error,
systimestamp);
commit;
END emp_hdt_sp;
RETURN NUMBER
IS
v_c NUMBER;
BEGIN
RETURN v_c;
END;
END emp_pkg;
BEGIN
emp_pkg.emp_sal_sp(120);
END;
as
RETURN NUMBER;
IS
FROM employees;
End all_detail;
as
AS
BEGIN
SELECT salary
INTO c
FROM Employees
WHERE Employee_id = a;
EXCEPTION
END emp2sal;
AS
BEGIN
SELECT Round(Months_between(sysdate,hire_date)/12)
INTO c
FROM Employees
WHERE Employee_id = a;
EXCEPTION
END emp2exep;
FUNCTION add2num (a IN NUMBER, b IN NUMBER)
RETURN NUMBER
AS
BEGIN
c := a+b;
RETURN C;
END;
End all_detail;
IS
END global_constant;
BEGIN
DECLARE
PROCEDURE P3;
PROCEDURE P1 IS
BEGIN
p2;
END P1;
PROCEDURE P2 IS
BEGIN
p3;
END P2;
PROCEDURE P3 IS
BEGIN
END P3;
BEGIN
p1;
END;
sample output:
From procedure p1
From procedure p2
From procedure p3
Interview Questions:
What is package?
Advantage of package
0 Add a comment
OCT
p_id NUMBER(3),
p_nm VARCHAR2(30),
p_qty NUMBER(8),
order_dt DATE
);
BEGIN
commit;
END;
------------------------------------
------------------------------------
------------------------------------
DECLARE
v_name VARCHAR2(4);
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
DECLARE
v_name VARCHAR2(5);
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
VALUES
(106,
'name6',
700,
'26-Dec-12');
commit;
DECLARE
v_name VARCHAR2(5);
BEGIN
--error
END;
DECLARE
v_name product_details.p_nm%TYPE;
BEGIN
SELECT p_nm
INTO v_name
FROM product_details
END;
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
--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
END;
/
DROP TABLE dept_details;
dept_id number(3) ,
dept_name varchar2(30),
dept_manager_name varchar2(30)
);
-------------------------------------------------------
+------------+-----------------------+-----------------
| 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
END;
---------------------------------------------------
| DEPT_ID | DEPT_NAME | DEPT_MANAGER_NAME|
---------------------------------------------------
| 20 | dept2 | manager_name2 |
---------------------------------------------------
Interview Question :
0 Add a comment
SEP
29
BULK Exceptions
/************************************************************************
* Reference : http://www.dba-oracle.com/plsql/t_plsql_exceptions.htm *
************************************************************************/
DECLARE
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
END;
COUNT(*)
-------
200
DECLARE
BEGIN
FOR i in 1..200
LOOP
v_dat.EXTEND;
v_dat(v_dat.LAST) := i;
END LOOP;
v_dat(100) := NULL;
FORALL i IN v_dat.FIRST..v_dat.LAST
commit;
END;
/*
Error Message :
ORA-06512: at line 15
*/
DECLARE
BEGIN
FOR i in 1..200
LOOP
v_dat.EXTEND;
v_dat(v_dat.LAST) := i;
END LOOP;
v_dat(100) := NULL;
BEGIN
FORALL i IN v_dat.FIRST..v_dat.LAST
COMMIT;
EXCEPTION
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.
the exception row must be found by looping through the original collection the correct
number of times.
SQL%BULK_EXCEPTIONS(i).ERROR_CODE
The total number of exceptions can be returned using the collections COUNT method,
v_ex_count NUMBER(4);
abort_ex EXCEPTION;
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;
BEGIN
COMMIT;
EXCEPTION
WHEN abort_ex THEN
v_ex_count := SQL%BULK_EXCEPTIONS.COUNT;
END LOOP;
END;
END;
/*
Sample output:
*/
COUNT(*)
-------
198
SAVE EXCEPTIONS clause being removed, in the above script now traps a different error number.
/*
Sample output:
*/
COUNT(*)
-------
99
/
Posted 29th September 2014 by Unknown
0 Add a comment
SEP
29
/************************************************************************
************************************************************************/
BEGIN
END LOOP;
commit;
END;
DECLARE
CURSOR PROD_DTLS_C IS
V_PID PROD_DETAILS.P_ID%TYPE;
V_PRDNAME PROD_DETAILS.P_NAME%TYPE;
BEGIN
OPEN PROD_DTLS_C;
LOOP
IF PROD_DTLS_C%NOTFOUND THEN
EXIT;
ELSE
UPDATE PROD_DETAILS P
SET P.P_ID = LPAD(P_ID, 10, 0)
END IF;
END LOOP;
CLOSE PROD_DTLS_C;
COMMIT;
END;
BEGIN
END LOOP;
commit;
END;
DECLARE
CURSOR PROD_DTLS_C IS
V_PID PROD_DETAILS.P_ID%TYPE;
V_PRDNAME PROD_DETAILS.P_NAME%TYPE;
BEGIN
OPEN PROD_DTLS_C;
LOOP
IF PROD_DTLS_C%NOTFOUND THEN
EXIT;
ELSE
UPDATE PROD_DETAILS P
END IF;
COMMIT;
END LOOP;
CLOSE PROD_DTLS_C;
--COMMIT;
END;
0 Add a comment
MAY
28
FROM Dual;
ORA-01756 : quoted string not properly terminated
FROM Dual;
SAL_DETAILS
---------------------------------------
FROM Dual;
Info
---------------------------------------
SELECT q'[some test ' some test ' some text ']' AS "In 10g"
FROM dual;
In 10g
------------------------------------
The '_' wild card character is used to match exactly one character
WITH mail_ids AS
UNION
UNION
----------------------------------
an_murugappan@gmail.com
WITH mail_ids AS
UNION
UNION
----------------------------------
an%murugappan@gmail.com
'23'
----
23
'&A'
----
&a
'&A'
----
&a
'45'
----
45
0 Add a comment
MAY
28
Data Manipulation Language (DML) statements are used for managing data within schema
objects. Some examples:
DELETE - deletes all records from a table, the space for the records remain
prod_id NUMBER(4) ,
prod_name VARCHAR2(30) ,
comments VARCHAR2(300)
);
no_data_found
INSERT
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
VALUES(103,'Moto X','11-May-14','13-May-14');
VALUES(103,'Moto X','11-May-14','13-May-14');
SELECT * FROM prod_details;
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--If you want to insert NULL value you can ignore that column at the time of inserting
VALUES(104,'Moto G','19-May-14','22-May-14',NULL);
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
--if you are not providing values for order_dt and deliver_dt column default value can be taken.
---------------------------------------------------------------------------
----------------------------------------------------------------------------
---------------------------------------------------------------------------
COUNT(*)
-------
WHERE id = 900;
-------
COUNT(*)
-------
UPDATE
Syntax :
UPDATE table_name
column2_name = column2_value,
column2_name = column3_value,
columnn_name = columnn_value
WHERE condition(s);
---------------------------------------------------------------------------
----------------------------------------------------------------------
---------------------------------------------------------------------------
UPDATE prod_details ps
SELECT *
FROM prod_details ps
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--If you try to execute update statement without condition it'll update all the records inside the
table.
UPDATE prod_details ps
SELECT *
---------------------------------------------------------------------------
----------------------------------------------------------------------
--if your update text contain ' means you can use following metnod (use '')
UPDATE prod_details ps
SELECT *
FROM prod_details ps
------------------------------------------------------------------------------------
PROD_ID PROD_NAME ORDER_DT DELIVER_DT COMMENTS
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
DELETE
Syntax:
WHERE condition(s);
SELECT *
---------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------
100 Apple iphone 5s 5/21/2014 5/24/2014 Some product's are not available
---------------------------------------------------------------------------------------
no rows selected.
0 Add a comment
MAY
28
Data Definition Language (DDL) statements are used to define the database structure or schema.
Some examples:
ADD
RENAME
MODIFY
DROP
Creating Table
--------------------------------------------------------------------------
--------------------------------------------------------------------------
S: -84 to 127
VARCHAR2 4000 Bytes we can store 0-9, a-z, A-Z and special characters
--------------------------------------------------------------------------
CREATE
RENAME
DROP
TRUNCATE
--creating table
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)
-----------------------------
ADD : Used to add a column after the table hase been created
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)
-----------------------------
ADD (
column_1 Data_type(size),
column_2 Data_type(size),
column_3 Data_type(size),
column_4 Data_type(size)
);
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.
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)
-----------------------------
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.
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)
-----------------------------
SYNTAX
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
DROP : Used to drop the tabel (Data + stucture of the table get removed from the database )
*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
0 Add a comment
MAY
28
Statements in Oracle
DDL statements are used to define the database structure or schema. Some examples:
ADD
RENAME
MODIFY
DROP
DML statements are used for managing data within schema objects. Some examples:
INSERT - insert data into a table
DELETE - deletes all records from a table, the space for the records remain
TCL statements are used to manage the changes made by DML statements. It allows
statements to be grouped together into logical transactions.
SAVEPOINT - identify a point in a transaction to which you can later roll back
MAY
19
roll_no NUMBER(4) ,
Name VARCHAR2(30) ,
dept_cd VARCHAR2(20) ,
total_marks NUMBER(3)
);
BEGIN
END;
/
SELECT * FROM students;
DECODE
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',
'IT',
'Information Technology',
FROM students;
Sample Output
------------------------------------------------------------
ROLL_NO NAME DEPT_CD DEPARTMENT NAME
------------------------------------------------------------
------------------------------------------------------------
CASE
Example
SELECT roll_no,
NAME,
dept_cd,
total_marks,
CASE
'A Grade'
'B Grade'
ELSE
'U Grade'
END AS "GRADE"
FROM students;
-----------------------------------------------
-----------------------------------------------
-----------------------------------------------
Interview Questions:
What is DECODE?
What is CASE?
MAY
19
Sub Query
Want to fetch the person Who are all getting salary more than Neena's salary ?
From Employees
Sub Query :
From Employees
);
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 :
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
);
From Employees
);
From Employees
);
From Employees
);
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
FROM
Dual;
);
SELECT AVG(salary)
FROM employees
);
0 Add a comment
Loading
Make sure that you guys learn all the topics before go through the Interview questions
Basic Questions:
What is SQL?
Which Data Dictionary Table contain information about all the objects in database?
Click here to learn Retriving data using SELECT statement
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.
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)
Choose a job you LOVE and you will never have to work a day in your life
- Confucius
Functions
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.
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.
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.
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?
What is the difference between inner and outer join? Explain with example.
If I try to Fetch data from 25 tables. How many number of join condition required?
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.
Write a query to display all the employees who are all getting salary more than the average
salary of the department 60.
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.
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)
How to add the column after the table has been created?
How to change the data type of the particular column after the table has been created.
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:
Views:
What is View?
What is a use of view WITH CHECK OPTION and WITH READ ONLY?
Index:
What is INDEX?
While creating a sequence, what does cache and nocache options mean?
Synonyms:
Set operators:
What is the difference between JOIN and UNION?
What are all the restriction we need to follow while using SET OPERATORS.
Analytical Functions:
What is the difference between inner and outer join? Explain with example.
search
JUL
20
--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
, AVG(b.salary) avg_sal
FROM employees b
GROUP BY b.department_id
)b
Display all the customer who have placed more number of orders by using INLINE view
( custm_id NUMBER ,
custm_nm VARCHAR2(30) ,
Basic Questions:
What is SQL?
Which Data Dictionary Table contain information about all the objects in database?
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)
Choose a job you LOVE and you will never have to work a day in your life
- Confucius
Functions
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.
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.
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.
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?
What is the difference between inner and outer join? Explain with example.
If I try to Fetch data from 25 tables. How many number of join condition required?
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.
Write a query to display all the employees who are all getting salary more than the average
salary of the department 60.
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.
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)
How to add the column after the table has been created?
How to change the data type of the particular column after the table has been created.
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:
Views:
What is View?
What is a use of view WITH CHECK OPTION and WITH READ ONLY?
Index:
What is INDEX?
While creating a sequence, what does cache and nocache options mean?
Synonyms:
Set operators:
What are all the restriction we need to follow while using SET OPERATORS.
Analytical Functions:
What is the difference between inner and outer join? Explain with example.
search
JUL
20
--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
, AVG(b.salary) avg_sal
FROM employees b
GROUP BY b.department_id
)b
Display all the customer who have placed more number of orders by using INLINE view
( custm_id NUMBER ,
custm_nm VARCHAR2(30) ,
ttl_amt NUMBER(7,2)
);
BEGIN
COMMIT;
END;
SELECT c.*
FROM customer_order_det_tb c;
--------------------------------------------
--------------------------------------------
--------------------------------------------
--Writing a Quer to display all the customer who have placed maximum number of order
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
--------------------------------
--------------------------------
100 Murugappan 2
102 Ramesh 2
101 Raja 1
--------------------------------
----------
total_odr
----------
----------
Inline view to find all the customers who have placed maximum number of orders
/****************************************
Syntax
WHERE contition;
****************************************/
SELECT query1.* FROM
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
) query1,
) query2
-------------------------------
-------------------------------
100 Murugappan 2
102 Ramesh 2
-------------------------------
--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 employees e
Example :
--in 11g
SELECT *
FROM departments d
SELECT *
FROM departments d
);
--in 11g
WITH t
AS
( SELECT LEVEL a
FROM dual
SELECT *
FROM t, (SELECT *
FROM employees
);
--in 12c
WITH t
AS
SELECT * FROM t,
LATERAL(SELECT *
FROM employees
0 Add a comment
JAN
23
--creating table
(
eid NUMBER(4),
ename VARCHAR2(30),
depno NUMBER(3),
salary NUMBER(8)
);
BEGIN
--Inserting records
COMMIT;
END;
/
SELECT * FROM employee_data
SELECT MAX(salary)
FROM employee_data
FROM employee_data);
SELECT MIN(salary)
FROM employee_data
SELECT MIN(salary)
FROM employee_data
--query to select all the details of the employee whose getting nth maximum salary
SELECT *
rownum rn
FROM (SELECT *
FROM employee_data
WHERE rn = 9;
WHERE rank = 9;
SELECT *
WHERE rank = 4;
SELECT *
WHERE rank = 4;
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
--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
--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,
first_name,
salary
FROM employees
7 View comments
JAN
22
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.
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.
14 rows selected.
Elapsed: 00:00:14.01
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.
0 Add a comment
DEC
21
Constraints
Format : [part_of_project_name-table_name-column_name-constraint_type]
Format : sys_cn
Example : SYS_C405323
Types
Primary Key
Ex : Employee_id, Student_id
Unique Key
allowed Null value
Ex : Contact_no, email
Foreign Key
c1(pk) : 1 2 3
Not Null
Check
Duplicate NULL
------------------------------------
Primary Key X X
------------------------------------
S_id Number(2),
s_mail Varchar2(30),
s_gender char(1),
s_did Number(3),
);
DESC my_stu_details;
------------------------------------
------------------------------------
S_ID NUMBER(2)
S_NAME VARCHAR2(30)
S_MAIL VARCHAR2(30) Y
S_GENDER CHAR(1) Y
S_DID NUMBER(3) Y
------------------------------------
--Duplicate Check
--Null Check
--------------------------------------------------------
--------------------------------------------------------
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
--------------------------------------------------------
------------------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
-------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
ON DELETE CASCADE
Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)
SELECT c.owner,
c.constraint_name,
c.constraint_type,
c.table_name,
c.r_constraint_name,
c.status
FROM user_constraints c
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.
Interview Questions
Which Data Dictionary table contains information about constraint with corresponding column
name?
1 View comments
DEC
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 :
--Example 1:
BEGIN
commit;
END;
listagg(product,
',') within
FROM test_ins
GROUP BY empid;
-->-- Example 2
select department_id "Department id", listagg(first_name,', ') WITHIN GROUP(ORDER BY
employee_id) "Employees"
FROM employees
GROUP BY department_id;
0 Add a comment
NOV
IF
IF ELSE
Multiple IF ELSE
LOOP
FOR LOOP
WHILE LOOP
BEGIN
Commit;
END;
IF
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 1;
UPDATE test_udt t
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;
UPDATE test_udt t
ELSE
UPDATE test_udt t
END IF;
commit;
END;
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 2;
v_salary := v_salary+10005;
ELSE
v_salary := v_salary+20007;
END IF;
UPDATE test_udt t
commit;
END;
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');
v_salary := 2000;
dbms_output.put_line('2 inside');
v_salary := 3000;
dbms_output.put_line('3 inside');
v_salary := 4000;
dbms_output.put_line('4 inside');
END IF;
UPDATE test_udt t
commit;
END;
/
select * from test_udt;
LOOP
--syntax
LOOP
--statements
--increment
--exit statement
END LOOP;
DECLARE
i NUMBER := 1;
x VARCHAR2(3);
BEGIN
LOOP
x := lpad(i,3,'0');
IF MOD(i,100) = 0 THEN
commit;
dbms_output.put_line('commit executed');
END IF;
END LOOP;
END;
FOR LOOP
BEGIN
FOR I in 1..5
LOOP
END LOOP;
END;
LOOP
END LOOP;
END;
WHILE LOOP
DECLARE
i_val NUMBER:=0;
BEGIN
LOOP
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
0 Add a comment
OCT
21
Bulk Collect
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.
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
INTO dta;
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta alldata_typ;
BEGIN
END LOOP;
END;
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta1 alldata_typ1;
dta2 alldata_typ2;
CURSOR proddt_cur IS
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END LOOP;
END;
0 Add a comment
OCT
21
Ref Cursor
This is unconstrained cursor which will return different types depends upon the user input.
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.
AS
BEGIN
OPEN dep_det_c
FOR
END;
DECLARE
dep_det_c SYS_REFCURSOR;
tab_data dep_details%ROWTYPE;
BEGIN
ref_c_sp(dep_det_c);
LOOP
END LOOP;
CLOSE dep_det_c;
END;
/*sample output*/
Department Name : HR
0 Add a comment
OCT
21
Cursor
SQL Private work Area where the query get passed and executed.
Types
******
Implicit(SQL)
Explicit
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
**************
OPEN cursor_name
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
Cursor Declaration
DECLARE
CURSOR <cursor_name>
IS
<SELECT statement>
BEGIN
END;
Cursor Loop
Loop
While Loop
For Loop
Cursor Clauses
Return
For update
Where current of
Bulk collect
(
p_id NUMBER,
p_name VARCHAR2(30),
p_order_dt DATE
);
BEGIN
FOR i IN 1 .. 75 LOOP
END LOOP;
commit;
END;
---------------------------------------------
---------------------------------------------
---------------------------------------------
----------------------------------------------
Implicit Cursor
----------------------------------------------
--will update soon
----------------------------------------------
Explicit Cursor
----------------------------------------------
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
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
CLOSE prod_detail_cur;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
dbms_output.put_line('Product id : ' || all_data.p_id ||
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*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
dbms_output.put_line('prod_detail_cur cursor closed');
ELSE
END IF;
END;
/*sample output*/
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
FETCH prod_detail_cur
INTO all_data;
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
************************************************************
************************************************************
DECLARE
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
FOR i IN prod_detail_cur
LOOP
END LOOP;
END;
/*sample output*/
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.
BEGIN
commit;
END;
----------------------------
----------------------------
1 Admin 1010
2 HR 1010
3 Sales 1020
4 Marketing 1020
----------------------------
DECLARE
all_data dep_details%ROWTYPE;
BEGIN
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1010);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1020);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
END;
/*sample output*/
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
0 Add a comment
OCT
21
Handling Exception
ERROR
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
Predefined Exception
*********************
Oracle has predefined several exceptions that correspond to the most common oracle errors.
------------------------------------------------------------------------
------------------------------------------------------------------------
DUP_VAL_ON_INDEX ORA-00001 -1
TOO_MANY_ROWS ORA-01422 -1422
OTHERS
------------------------------------------------------------------------
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
Single row SELECT returned no rows or your program referenced a deleted element in a nested
table
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
commit;
BEGIN
END;
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
DECLARE
num1 NUMBER(2);
BEGIN
num1 := 345;
EXCEPTION
END;
BEGIN
COMMIT;
END;
DECLARE
cursor emp_c IS
all_data emp%ROWTYPE;
BEGIN
OPEN emp_c;
OPEN emp_c;
NULL;
CLOSE emp_c;
EXCEPTION
END;
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
**********************
User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,
DECLARE
gender_ex EXCEPTION;
BEGIN
END IF;
dbms_output.put_line('Gender : '||v_gender);
EXCEPTION
END;
DECLARE
abort_ex EXCEPTION;
BEGIN
FOR i IN 1..100
LOOP
BEGIN
IF mod(i,10)=0 THEN
RAISE abort_ex;
END IF;
EXCEPTION
NULL;
END;
END LOOP;
COMMIT;
END;
********************
SQLCODE returns the current error code, and SQLERRM returns the current error message
text;
SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.
DECLARE
v_id NUMBER;
BEGIN
dbms_output.put_line(v_id);
EXCEPTION
END;
/*sample output*/
SQLCODE : 100
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:
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
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 :
DECLARE
v_gender CHAR := '&gender';
BEGIN
END IF;
END;
1 View comments
Loading
Basic Questions:
What is SQL?
Which Data Dictionary Table contain information about all the objects in database?
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.
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)
Choose a job you LOVE and you will never have to work a day in your life
- Confucius
Functions
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.
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.
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.
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?
What is the difference between inner and outer join? Explain with example.
If I try to Fetch data from 25 tables. How many number of join condition required?
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.
Write a query to display all the employees who are all getting salary more than the average
salary of the department 60.
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.
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)
How to add the column after the table has been created?
How to change the data type of the particular column after the table has been created.
Constraints:
Views:
What is View?
What is a use of view WITH CHECK OPTION and WITH READ ONLY?
Index:
What is INDEX?
While creating a sequence, what does cache and nocache options mean?
Synonyms:
Set operators:
What are all the restriction we need to follow while using SET OPERATORS.
Analytical Functions:
What is the difference between inner and outer join? Explain with example.
search
JUL
20
--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
, AVG(b.salary) avg_sal
FROM employees b
GROUP BY b.department_id
)b
Display all the customer who have placed more number of orders by using INLINE view
( custm_id NUMBER ,
custm_nm VARCHAR2(30) ,
ttl_amt NUMBER(7,2)
);
BEGIN
COMMIT;
END;
SELECT c.*
FROM customer_order_det_tb c;
--------------------------------------------
--------------------------------------------
--------------------------------------------
--Writing a Quer to display all the customer who have placed maximum number of order
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
--------------------------------
--------------------------------
100 Murugappan 2
102 Ramesh 2
101 Raja 1
--------------------------------
----------
total_odr
----------
----------
Inline view to find all the customers who have placed maximum number of orders
/****************************************
Syntax
WHERE contition;
****************************************/
SELECT query1.* FROM
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
) query1,
) query2
-------------------------------
-------------------------------
100 Murugappan 2
102 Ramesh 2
-------------------------------
--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT
FROM employees e
Example :
--in 11g
SELECT *
FROM departments d
SELECT *
FROM departments d
);
--in 11g
WITH t
AS
( SELECT LEVEL a
FROM dual
SELECT *
FROM t, (SELECT *
FROM employees
);
--in 12c
WITH t
AS
(SELECT LEVEL a FROM dual CONNECT BY LEVEL <= 30)
SELECT * FROM t,
LATERAL(SELECT *
FROM employees
0 Add a comment
JAN
23
--creating table
eid NUMBER(4),
ename VARCHAR2(30),
depno NUMBER(3),
salary NUMBER(8)
);
BEGIN
--Inserting records
COMMIT;
END;
SELECT MAX(salary)
FROM employee_data
FROM employee_data);
SELECT MIN(salary)
FROM employee_data
SELECT MIN(salary)
FROM employee_data
--query to select all the details of the employee whose getting nth maximum salary
SELECT *
rownum rn
FROM (SELECT *
FROM employee_data
WHERE rn = 9;
SELECT *
FROM (SELECT emp.*,
WHERE rank = 9;
SELECT *
WHERE rank = 4;
SELECT *
WHERE rank = 4;
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
--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
--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,
first_name,
salary
FROM employees
7 View comments
JAN
22
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.
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
14 rows selected.
Elapsed: 00:00:14.01
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.
0 Add a comment
DEC
21
Constraints
Format : sys_cn
Example : SYS_C405323
Types
Primary Key
Ex : Employee_id, Student_id
Unique Key
Ex : Contact_no, email
Foreign Key
c1(pk) : 1 2 3
Not Null
Check
------------------------------------
Duplicate NULL
------------------------------------
Primary Key X X
------------------------------------
S_id Number(2),
s_mail Varchar2(30),
s_gender char(1),
s_did Number(3),
);
DESC my_stu_details;
------------------------------------
------------------------------------
S_ID NUMBER(2)
S_NAME VARCHAR2(30)
S_MAIL VARCHAR2(30) Y
S_GENDER CHAR(1) Y
S_DID NUMBER(3) Y
------------------------------------
--Duplicate Check
--Null Check
--------------------------------------------------------
--------------------------------------------------------
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
--------------------------------------------------------
------------------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
-------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
ON DELETE CASCADE
SELECT c.owner,
c.constraint_name,
c.constraint_type,
c.table_name,
c.r_constraint_name,
c.status
FROM user_constraints c
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.
Interview Questions
Which Data Dictionary table contains information about constraint with corresponding column
name?
1 View comments
DEC
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:
BEGIN
commit;
END;
',') within
FROM test_ins
GROUP BY empid;
-->-- Example 2
select department_id "Department id", listagg(first_name,', ') WITHIN GROUP(ORDER BY
employee_id) "Employees"
FROM employees
GROUP BY department_id;
0 Add a comment
NOV
IF
IF ELSE
Multiple IF ELSE
LOOP
FOR LOOP
WHILE LOOP
create table test_udt(id NUMBER, salary NUMBER);
BEGIN
Commit;
END;
IF
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 1;
UPDATE test_udt t
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
ELSE
UPDATE test_udt t
END IF;
commit;
END;
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
commit;
END;
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');
v_salary := 2000;
dbms_output.put_line('2 inside');
v_salary := 3000;
dbms_output.put_line('3 inside');
v_salary := 4000;
dbms_output.put_line('4 inside');
END IF;
UPDATE test_udt t
commit;
END;
--syntax
LOOP
--statements
--increment
--exit statement
END LOOP;
DECLARE
i NUMBER := 1;
x VARCHAR2(3);
BEGIN
LOOP
x := lpad(i,3,'0');
i := i+1;
IF MOD(i,100) = 0 THEN
commit;
dbms_output.put_line('commit executed');
END IF;
END LOOP;
END;
FOR LOOP
BEGIN
FOR I in 1..5
LOOP
END LOOP;
END;
LOOP
END LOOP;
END;
WHILE LOOP
DECLARE
i_val NUMBER:=0;
BEGIN
LOOP
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
0 Add a comment
OCT
21
Bulk Collect
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.
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
INTO dta;
CLOSE proddt_cur;
END LOOP;
END;
/
DECLARE
dta alldata_typ;
BEGIN
END LOOP;
END;
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta1 alldata_typ1;
dta2 alldata_typ2;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END LOOP;
END;
0 Add a comment
OCT
21
Ref Cursor
This is unconstrained cursor which will return different types depends upon the user input.
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.
AS
BEGIN
OPEN dep_det_c
FOR
END;
DECLARE
dep_det_c SYS_REFCURSOR;
tab_data dep_details%ROWTYPE;
BEGIN
ref_c_sp(dep_det_c);
LOOP
END LOOP;
CLOSE dep_det_c;
END;
/*sample output*/
Department Name : HR
0 Add a comment
OCT
21
Cursor
SQL Private work Area where the query get passed and executed.
Types
******
Implicit(SQL)
Explicit
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
**************
OPEN cursor_name
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
Cursor Declaration
DECLARE
CURSOR <cursor_name>
IS
<SELECT statement>
BEGIN
END;
Cursor Loop
Loop
While Loop
For Loop
Cursor Clauses
Return
For update
Where current of
Bulk collect
p_id NUMBER,
p_name VARCHAR2(30),
p_order_dt DATE
);
BEGIN
FOR i IN 1 .. 75 LOOP
END LOOP;
commit;
END;
---------------------------------------------
---------------------------------------------
---------------------------------------------
----------------------------------------------
Implicit Cursor
----------------------------------------------
Explicit Cursor
----------------------------------------------
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
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
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
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*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
EXIT WHEN prod_detail_cur%NOTFOUND;
END LOOP;
CLOSE prod_detail_cur;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
END IF;
END;
/*sample output*/
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
FETCH prod_detail_cur
INTO all_data;
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
************************************************************
************************************************************
DECLARE
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
FOR i IN prod_detail_cur
LOOP
END LOOP;
END;
/*sample output*/
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.
BEGIN
commit;
END;
SELECT * FROM dep_details;
----------------------------
----------------------------
1 Admin 1010
2 HR 1010
3 Sales 1020
4 Marketing 1020
----------------------------
DECLARE
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;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1020);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
END;
/*sample output*/
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
0 Add a comment
OCT
21
Handling Exception
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
Predefined Exception
*********************
Oracle has predefined several exceptions that correspond to the most common oracle errors.
------------------------------------------------------------------------
------------------------------------------------------------------------
DUP_VAL_ON_INDEX ORA-00001 -1
OTHERS
------------------------------------------------------------------------
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
Single row SELECT returned no rows or your program referenced a deleted element in a nested
table
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
commit;
BEGIN
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
END;
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
num1 NUMBER(2);
BEGIN
num1 := 345;
EXCEPTION
END;
BEGIN
COMMIT;
END;
SELECT * FROM emp;
DECLARE
cursor emp_c IS
all_data emp%ROWTYPE;
BEGIN
OPEN emp_c;
OPEN emp_c;
NULL;
CLOSE emp_c;
EXCEPTION
END;
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
**********************
User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,
DECLARE
gender_ex EXCEPTION;
BEGIN
RAISE gender_ex;
END IF;
dbms_output.put_line('Gender : '||v_gender);
EXCEPTION
END;
DECLARE
abort_ex EXCEPTION;
BEGIN
FOR i IN 1..100
LOOP
BEGIN
IF mod(i,10)=0 THEN
RAISE abort_ex;
END IF;
EXCEPTION
NULL;
END;
END LOOP;
COMMIT;
END;
********************
SQLCODE returns the current error code, and SQLERRM returns the current error message
text;
SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.
DECLARE
v_id NUMBER;
BEGIN
dbms_output.put_line(v_id);
EXCEPTION
WHEN OTHERS THEN
END;
/*sample output*/
SQLCODE : 100
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:
DECLARE
v_result NUMBER;
PRAGMA EXCEPTION_INIT(Invalid, -1476);
BEGIN
EXCEPTION
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 :
DECLARE
END IF;
END;
1 View comments
Loading
search
JUL
20
--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
, AVG(b.salary) avg_sal
FROM employees b
GROUP BY b.department_id
)b
Display all the customer who have placed more number of orders by using INLINE view
( custm_id NUMBER ,
custm_nm VARCHAR2(30) ,
order_dt DATE DEFAULT SYSDATE ,
ttl_amt NUMBER(7,2)
);
BEGIN
COMMIT;
END;
SELECT c.*
FROM customer_order_det_tb c;
--------------------------------------------
--------------------------------------------
--------------------------------------------
--Writing a Quer to display all the customer who have placed maximum number of order
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
--------------------------------
--------------------------------
100 Murugappan 2
102 Ramesh 2
101 Raja 1
--------------------------------
----------
total_odr
----------
----------
Inline view to find all the customers who have placed maximum number of orders
/****************************************
Syntax
WHERE contition;
****************************************/
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
) query1,
) query2
-------------------------------
100 Murugappan 2
102 Ramesh 2
-------------------------------
--Display name and salary for top three money makers of the company and their designation
should not be SALESMAN and PRESIDENT
FROM employees e
Example :
--in 11g
SELECT *
FROM departments d
--in 12c
SELECT *
FROM departments d
);
--in 11g
WITH t
AS
( SELECT LEVEL a
FROM dual
SELECT *
FROM t, (SELECT *
FROM employees
);
--in 12c
WITH t
AS
SELECT * FROM t,
LATERAL(SELECT *
FROM employees
JAN
23
--creating table
eid NUMBER(4),
ename VARCHAR2(30),
depno NUMBER(3),
salary NUMBER(8)
);
BEGIN
--Inserting records
COMMIT;
END;
FROM employee_data
FROM employee_data);
SELECT MIN(salary)
FROM employee_data
SELECT MIN(salary)
FROM employee_data
SELECT *
rownum rn
FROM (SELECT *
FROM employee_data
WHERE rn = 9;
SELECT *
WHERE rank = 9;
SELECT *
SELECT *
WHERE rank = 4;
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
--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
--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,
first_name,
salary
FROM employees
7 View comments
JAN
22
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.
14 rows selected.
Elapsed: 00:00:14.01
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.
0 Add a comment
DEC
21
Constraints
Format : [part_of_project_name-table_name-column_name-constraint_type]
Format : sys_cn
Example : SYS_C405323
Types
Primary Key
Ex : Employee_id, Student_id
Unique Key
Ex : Contact_no, email
Foreign Key
c1(pk) : 1 2 3
Check
------------------------------------
Duplicate NULL
------------------------------------
Primary Key X X
------------------------------------
S_id Number(2),
s_mail Varchar2(30),
s_gender char(1),
s_did Number(3),
);
DESC my_stu_details;
------------------------------------
------------------------------------
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)
--Duplicate Check
Insert into my_stu_details (s_id, s_name , s_mail , s_gender, s_did)
--Null Check
--------------------------------------------------------
--------------------------------------------------------
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
--------------------------------------------------------
------------------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
-------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
ON DELETE CASCADE
SELECT c.owner,
c.constraint_name,
c.constraint_type,
c.table_name,
c.r_constraint_name,
c.status
FROM user_constraints c
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.
Interview Questions
Which Data Dictionary table contains information about constraint with corresponding column
name?
1 View comments
DEC
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 :
--Example 1:
BEGIN
commit;
END;
listagg(product,
',') within
FROM test_ins
GROUP BY empid;
-->-- Example 2
FROM employees
GROUP BY department_id;
0 Add a comment
NOV
IF
IF ELSE
Multiple IF ELSE
LOOP
FOR LOOP
WHILE LOOP
BEGIN
Commit;
END;
IF
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 1;
UPDATE test_udt t
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;
UPDATE test_udt t
ELSE
UPDATE test_udt t
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;
v_salary := v_salary+10005;
ELSE
v_salary := v_salary+20007;
END IF;
UPDATE test_udt t
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');
v_salary := 2000;
dbms_output.put_line('2 inside');
v_salary := 3000;
dbms_output.put_line('3 inside');
dbms_output.put_line('4 inside');
END IF;
UPDATE test_udt t
commit;
END;
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');
i := i+1;
IF MOD(i,100) = 0 THEN
commit;
dbms_output.put_line('commit executed');
END IF;
END LOOP;
END;
BEGIN
FOR I in 1..5
LOOP
END LOOP;
END;
BEGIN
LOOP
END LOOP;
END;
WHILE LOOP
DECLARE
i_val NUMBER:=0;
BEGIN
WHILE (i_val < 11)
LOOP
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
0 Add a comment
OCT
21
Bulk Collect
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.
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
INTO dta;
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta alldata_typ;
BEGIN
END LOOP;
END;
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END;
/
-->-- Multiple fetches in INTO clause --<--
DECLARE
dta1 alldata_typ1;
dta2 alldata_typ2;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END LOOP;
END;
0 Add a comment
OCT
21
Ref Cursor
This is unconstrained cursor which will return different types depends upon the user input.
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.
AS
BEGIN
OPEN dep_det_c
FOR
END;
DECLARE
dep_det_c SYS_REFCURSOR;
tab_data dep_details%ROWTYPE;
BEGIN
ref_c_sp(dep_det_c);
LOOP
END LOOP;
CLOSE dep_det_c;
END;
/*sample output*/
Department Name : Admin
Department Name : HR
0 Add a comment
OCT
21
Cursor
SQL Private work Area where the query get passed and executed.
Types
******
Implicit(SQL)
Explicit
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
Cursor Stages
**************
OPEN cursor_name
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
Cursor Declaration
DECLARE
CURSOR <cursor_name>
IS
<SELECT statement>
BEGIN
END;
Cursor Loop
Loop
While Loop
For Loop
Cursor Clauses
Return
For update
Where current of
Bulk collect
p_id NUMBER,
p_name VARCHAR2(30),
p_order_dt DATE
);
BEGIN
FOR i IN 1 .. 75 LOOP
END LOOP;
commit;
END;
---------------------------------------------
---------------------------------------------
---------------------------------------------
----------------------------------------------
Implicit Cursor
----------------------------------------------
----------------------------------------------
Explicit Cursor
----------------------------------------------
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
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
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
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*/
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
FETCH prod_detail_cur
INTO all_data;
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
************************************************************
************************************************************
DECLARE
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
FOR i IN prod_detail_cur
LOOP
END LOOP;
END;
/*sample output*/
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.
BEGIN
commit;
END;
----------------------------
----------------------------
1 Admin 1010
2 HR 1010
3 Sales 1020
4 Marketing 1020
----------------------------
DECLARE
all_data dep_details%ROWTYPE;
BEGIN
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1010);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1020);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
END;
/*sample output*/
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
0 Add a comment
OCT
21
Handling Exception
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
*********************
Oracle has predefined several exceptions that correspond to the most common oracle errors.
------------------------------------------------------------------------
------------------------------------------------------------------------
DUP_VAL_ON_INDEX ORA-00001 -1
OTHERS
------------------------------------------------------------------------
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
Single row SELECT returned no rows or your program referenced a deleted element in a nested
table
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
-->-- DUP_VAL_ON_INDEX --<--
commit;
BEGIN
EXCEPTION
END;
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
DECLARE
num1 NUMBER(2);
BEGIN
num1 := 345;
EXCEPTION
END;
BEGIN
COMMIT;
END;
DECLARE
cursor emp_c IS
all_data emp%ROWTYPE;
BEGIN
OPEN emp_c;
OPEN emp_c;
NULL;
CLOSE emp_c;
EXCEPTION
END;
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
**********************
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,
DECLARE
gender_ex EXCEPTION;
BEGIN
RAISE gender_ex;
END IF;
dbms_output.put_line('Gender : '||v_gender);
EXCEPTION
END;
DECLARE
abort_ex EXCEPTION;
BEGIN
FOR i IN 1..100
LOOP
BEGIN
IF mod(i,10)=0 THEN
RAISE abort_ex;
END IF;
EXCEPTION
NULL;
END;
END LOOP;
COMMIT;
END;
********************
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.
DECLARE
v_id NUMBER;
BEGIN
dbms_output.put_line(v_id);
EXCEPTION
END;
/*sample output*/
SQLCODE : 100
*********************
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:
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
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 :
DECLARE
BEGIN
END IF;
END;
1 View comments
Loading
search
JUL
20
--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 b
GROUP BY b.department_id
)b
Display all the customer who have placed more number of orders by using INLINE view
( custm_id NUMBER ,
custm_nm VARCHAR2(30) ,
ttl_amt NUMBER(7,2)
);
BEGIN
COMMIT;
END;
SELECT c.*
FROM customer_order_det_tb c;
--------------------------------------------
--------------------------------------------
--------------------------------------------
--Writing a Quer to display all the customer who have placed maximum number of order
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
--------------------------------
custm_id custm_nm total_odr
--------------------------------
100 Murugappan 2
102 Ramesh 2
101 Raja 1
--------------------------------
----------
total_odr
----------
----------
Inline view to find all the customers who have placed maximum number of orders
/****************************************
Syntax
****************************************/
FROM customer_order_det_tb c
GROUP BY c.custm_id,c.custm_nm
) query1,
) query2
-------------------------------
-------------------------------
100 Murugappan 2
102 Ramesh 2
-------------------------------
--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 employees e
Example :
--in 11g
SELECT *
FROM departments d
--in 12c
SELECT *
FROM departments d
);
--in 11g
WITH t
AS
( SELECT LEVEL a
FROM dual
SELECT *
FROM t, (SELECT *
FROM employees
);
WITH t
AS
SELECT * FROM t,
LATERAL(SELECT *
FROM employees
0 Add a comment
JAN
23
--creating table
CREATE TABLE employee_data
eid NUMBER(4),
ename VARCHAR2(30),
depno NUMBER(3),
salary NUMBER(8)
);
BEGIN
--Inserting records
COMMIT;
END;
/
SELECT * FROM employee_data
SELECT MAX(salary)
FROM employee_data
FROM employee_data);
SELECT MIN(salary)
SELECT MIN(salary)
FROM employee_data
--query to select all the details of the employee whose getting nth maximum salary
SELECT *
rownum rn
FROM (SELECT *
FROM employee_data
WHERE rn = 9;
--same query using row_numbr( ) function
SELECT *
WHERE rank = 9;
SELECT *
WHERE rank = 4;
SELECT *
WHERE rank = 4;
--query to display display maximum salary in all the department
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
--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
--query to display all the employees who are all getting salary more than their manager salary
SELECT employee_id,
first_name,
salary
FROM employees
7 View comments
JAN
22
Why prefer COALESCE over NVL
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.
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.
Elapsed: 00:00:14.01
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.
0 Add a comment
DEC
21
Constraints
Format : [part_of_project_name-table_name-column_name-constraint_type]
Format : sys_cn
Example : SYS_C405323
Types
Primary Key
Ex : Employee_id, Student_id
Unique Key
allowed Null value
Ex : Contact_no, email
Foreign Key
c1(pk) : 1 2 3
Not Null
Check
Duplicate NULL
------------------------------------
Primary Key X X
------------------------------------
S_id Number(2),
s_mail Varchar2(30),
s_gender char(1),
s_did Number(3),
);
DESC my_stu_details;
------------------------------------
------------------------------------
S_ID NUMBER(2)
S_NAME VARCHAR2(30)
S_MAIL VARCHAR2(30) Y
S_GENDER CHAR(1) Y
S_DID NUMBER(3) Y
------------------------------------
--Duplicate Check
--Null Check
--------------------------------------------------------
--------------------------------------------------------
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
--------------------------------------------------------
------------------------------------------------------------
-------------------------------------------------
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
-------------------------------------------------
-------------------------------------------------
-------------------------------------------------
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
ON DELETE CASCADE
Constraint my_stu_did_f FOREIGN KEY (s_did) References Departments(Department_id)
SELECT c.owner,
c.constraint_name,
c.constraint_type,
c.table_name,
c.r_constraint_name,
c.status
FROM user_constraints c
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
------------------------------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
-------------------------------------------------------------
In user_cons_columns table position if the column1 will be 1, position of column2 will be 2 and
column3 will be 3.
Interview Questions
Which Data Dictionary table contains information about constraint with corresponding column
name?
1 View comments
DEC
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 :
--Example 1:
BEGIN
commit;
END;
listagg(product,
',') within
FROM test_ins
GROUP BY empid;
FROM employees
GROUP BY department_id;
0 Add a comment
NOV
IF
IF ELSE
Multiple IF ELSE
LOOP
FOR LOOP
WHILE LOOP
BEGIN
Commit;
END;
IF
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 1;
UPDATE test_udt t
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;
UPDATE test_udt t
ELSE
UPDATE test_udt t
END IF;
commit;
END;
DECLARE
v_salary NUMBER;
v_id NUMBER;
BEGIN
SELECT id,salary
INTO v_id,v_salary
FROM test_udt
WHERE id = 2;
v_salary := v_salary+10005;
ELSE
v_salary := v_salary+20007;
END IF;
UPDATE test_udt t
commit;
END;
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');
v_salary := 2000;
dbms_output.put_line('2 inside');
v_salary := 3000;
dbms_output.put_line('3 inside');
v_salary := 4000;
dbms_output.put_line('4 inside');
END IF;
UPDATE test_udt t
commit;
END;
/
select * from test_udt;
LOOP
--syntax
LOOP
--statements
--increment
--exit statement
END LOOP;
DECLARE
i NUMBER := 1;
x VARCHAR2(3);
BEGIN
LOOP
x := lpad(i,3,'0');
i := i+1;
IF MOD(i,100) = 0 THEN
commit;
dbms_output.put_line('commit executed');
END IF;
END LOOP;
END;
FOR LOOP
BEGIN
FOR I in 1..5
LOOP
END LOOP;
END;
/
FOR LOOP - Reverse
BEGIN
LOOP
END LOOP;
END;
WHILE LOOP
DECLARE
i_val NUMBER:=0;
BEGIN
LOOP
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
0 Add a comment
OCT
21
Bulk Collect
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.
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
BEGIN
OPEN proddt_cur;
INTO dta;
CLOSE proddt_cur;
END;
DECLARE
dta alldata_typ;
BEGIN
END LOOP;
END;
DECLARE
dta alldata_typ;
CURSOR proddt_cur IS
SELECT * FROM product_details;
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END;
DECLARE
dta1 alldata_typ1;
dta2 alldata_typ2;
CURSOR proddt_cur IS
SELECT p_id, p_name FROM product_details;
BEGIN
OPEN proddt_cur;
CLOSE proddt_cur;
END LOOP;
END LOOP;
END;
0 Add a comment
OCT
21
Ref Cursor
This is unconstrained cursor which will return different types depends upon the user input.
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.
AS
BEGIN
OPEN dep_det_c
FOR
END;
DECLARE
dep_det_c SYS_REFCURSOR;
tab_data dep_details%ROWTYPE;
BEGIN
ref_c_sp(dep_det_c);
LOOP
END LOOP;
CLOSE dep_det_c;
END;
/*sample output*/
Department Name : HR
OCT
21
Cursor
SQL Private work Area where the query get passed and executed.
Types
******
Implicit(SQL)
Explicit
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
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
DECLARE
CURSOR <cursor_name>
IS
<SELECT statement>
BEGIN
END;
Cursor Loop
Loop
While Loop
For Loop
Cursor Clauses
Return
For update
Where current of
Bulk collect
p_id NUMBER,
p_name VARCHAR2(30),
p_order_dt DATE
);
BEGIN
FOR i IN 1 .. 75 LOOP
END LOOP;
commit;
END;
---------------------------------------------
---------------------------------------------
---------------------------------------------
----------------------------------------------
Implicit Cursor
----------------------------------------------
--will update soon
----------------------------------------------
Explicit Cursor
----------------------------------------------
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
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
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
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*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
LOOP
FETCH prod_detail_cur
INTO all_data;
END LOOP;
IF prod_detail_cur%ISOPEN THEN
CLOSE prod_detail_cur;
ELSE
END IF;
END;
/*sample output*/
**********************************************
**********************************************
DECLARE
all_data product_details%ROWTYPE;
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
OPEN prod_detail_cur;
FETCH prod_detail_cur
INTO all_data;
FETCH prod_detail_cur
INTO all_data;
END LOOP;
CLOSE prod_detail_cur;
END;
/*sample output*/
************************************************************
************************************************************
DECLARE
--cursor declaration
CURSOR prod_detail_cur IS
BEGIN
FOR i IN prod_detail_cur
LOOP
END LOOP;
END;
/*sample output*/
Product id : 1 Product Name : prod_name_1 ( Orderd on : 11-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.
BEGIN
END;
----------------------------
----------------------------
1 Admin 1010
2 HR 1010
3 Sales 1020
4 Marketing 1020
----------------------------
DECLARE
all_data dep_details%ROWTYPE;
BEGIN
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1010);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
OPEN dep_det_c(1020);
LOOP
FETCH dep_det_c
INTO all_data;
END LOOP;
CLOSE dep_det_c;
dbms_output.put_line('-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-');
END;
/
/*sample output*/
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
0 Add a comment
OCT
21
Handling Exception
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
Predefined Exception
*********************
Oracle has predefined several exceptions that correspond to the most common oracle errors.
------------------------------------------------------------------------
------------------------------------------------------------------------
OTHERS
------------------------------------------------------------------------
DECLARE
v_result NUMBER;
BEGIN
EXCEPTION
END;
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).
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
commit;
BEGIN
INSERT INTO test_tb VALUES (2);
EXCEPTION
END;
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
DECLARE
num1 NUMBER(2);
BEGIN
num1 := 345;
EXCEPTION
END;
BEGIN
END;
DECLARE
cursor emp_c IS
all_data emp%ROWTYPE;
BEGIN
OPEN emp_c;
OPEN emp_c;
NULL;
CLOSE emp_c;
EXCEPTION
END;
v_result NUMBER;
BEGIN
EXCEPTION
END;
**********************
User-defined exceptions are declared in the declarative section of a PL/SQL block. Just like
variables,
DECLARE
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
END;
DECLARE
abort_ex EXCEPTION;
BEGIN
FOR i IN 1..100
LOOP
BEGIN
IF mod(i,10)=0 THEN
RAISE abort_ex;
END IF;
EXCEPTION
NULL;
END;
END LOOP;
COMMIT;
END;
********************
SQLCODE returns the current error code, and SQLERRM returns the current error message
text;
SQLERRM will take only negative value except 100. If any positive value other than 100 returns
non-oracle exception.
DECLARE
v_id NUMBER;
BEGIN
EXCEPTION
END;
/*sample output*/
SQLCODE : 100
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:
v_result NUMBER;
BEGIN
EXCEPTION
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 :
BEGIN
END IF;
END;
1 View comments
Loading