You are on page 1of 83

NETTUR TECHNICAL TRAINING FOUNDATION

DIPLOMA IN INFORMATION TECHNOLOGY – CP09

Lab Manual

for

ORACLE LAB

Semester IV

Subject Code: CP 09 04 07

Prepared by: Mrs. RIJINA P Approved by: Mr. Ramakrishnanand


Asst.Manager Training, NEC Course Coordinator CP-09

Rev .0 June-2017

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 1
Course Objectives:
At the end of the semester the Trainees are able to understand
 Concept of relational databases and Oracle 11g database technology.
 Learn advanced features of SQL.
 Learn PL/SQL concept.
 Understand benefits of PL/SQL.

Sl.No Programs ALLOTED


HOURS

1. Identify the syntax for creating a table. 1

2. Identify the syntax for defining constraints. 1

3. Identify the code for using the INSERT statement. .5

4. Identify the code for using the UPDATE statement. .5


5. Identify the code for using the DELETE statement. .5
6. Identify the SQL statement to retrieve data from tables. 1

7. Identify the arithmetic expressions used to perform .5


operations on data.
Identify the use of the WHERE clause in restricting 1
8. the result set of an SQL query.

Identify the use of the comparison operators used in a 1


9. WHERE clause to restrict the query results.

10. Identify the rules of precedence associated with 1


WHERE clause.
11. Identify the methods of the sorting result set of a query 1
using the ORDER BY clause.
Identify substitution variables that are used while 2
12. retrieving data by using SQL statements.

13. Identify guidelines for using the GROUP BY clause. 1


Identify the features of the ROLLUP operator and 1
14. CUBE operator.

15. Identify the syntax for altering and dropping a table. 1

16. Identify features of views. 1

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 2
17. Identify syntax for performing various tasks for 1
managing views.
18. Identify the syntax for creating and dropping synonyms. 2

19. Identify the syntax for creating and dropping indexes. 1

20. Identify the syntax for creating and using a sequence. 2

21. Identify the features of single row character functions. 3

22. Match the number functions with their purpose. 2


23. Identify the features of Date functions. 2

24. Identify features the functions used to convert data 3


types.(to_char,to_num,to_date)
25. Identify the syntax for displaying dates in different 2
formats.
26. Identify features of general functions.(NVL,NVL2) 2

27. Demonstrate the use of CASE expand DECODE 2


functions
Identify the use of nested functions in retrieving data 1
28. from tables.

Identify use of single row and multiple row sub queries 1


29. sub queries to retrieve from multiple tables.

30. Identify the syntax for performing multiple-column and 1


correlated sub queries.
Identify the use of different types of join to retrieve data 4
31. from multiple tables.

32. Identify the syntax of the unconditional INSERT ALL 2


statement.
33. Identify the syntax of the conditional INSERT ALL 2
statement.
34. Identify the syntax of the conditional INSERT FIRST 2
statement.
Identify the code for retrieving data hierarchically from 2
35. a table.

36. Generate a query using the following SET 2


OPERATORS
 UNION
 UNION ALL

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 3
 INTERSECT
 MINUS

Controlling User Access. 2


 Create User
37.  Grant
 Revoke

38. Identify features of various PL/SQL data types. 1

39. Identify the syntax for declaring PL/SQL variables using 1


the %type attributes.
40. Identify features of bind variables and substitution 1
variables
41. Identify the syntax of the % ROWTYPE attributes. 2

Identify the syntax for creating a PL/SQL table based 2


42. record.

Identify the syntax for creating a PL/SQL cursor based 3


43. record.

Identify the syntax for creating a PL/SQL user defined 3


44. record.

45. Identify the features of nested blocks. 2

46. Identify uses of PL/SQL operators. 1

Identify codes for manipulating data using DML 2


47. statements in PL/SQL block.

48. Identify the syntax of decision making statement. 4

49. Identify the syntax of looping statement. 3

50. Identify the syntax for controlling implicit cursors and 4


use the attributes.
51. Identify the syntax for controlling explicit cursors and 4
use the attributes.
52. Identify the syntax for using cursor FOR loops, FOR 4
UPDATE, WHERE CURRENT OF.

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 4
53. Identify guidelines for trapping system built in 2
exceptions.
54. Identify guidelines for trapping user defined exceptions. 2

55. Identify the syntax for raise_application_error. 1

56. Identify the syntax for passing parameters to a stored 1


procedure.
57. Identify tasks involved in using stored procedures. 3
(IN,OUT,IN OUT)
58. Identify the syntax for creating PL/SQL function. 3

Trapping predefined and user defined exception in 2


59. subprogram.

Identify sequence steps for developing PL/SQL 4


60. packages.

61. Identify the code to create a trigger. 4

Write program to show use of new and old keywords in 3


62. a trigger program.

Demonstrate the following TCL operations with suitable 2


example
63.  COMMIT
 SAVEPOINT
 ROLLBACK
Reference :
 SQL,PL/SQL The programming language
of Oracle by Ivan Byross
 Oracle PLSQL programming by Steven
Feuerstein
 www.tutorialspoint.com
 www.oracle.com
 www.plsqltutorials.com

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 5
1. Identify the syntax for creating a table.

CREATE:

(a)CREATE TABLE: This is used to create a new relation (table)


Syntax: CREATE TABLE <relation_name/table_name >
(field_1 data_type(size),field_2 data_type(size), .. . );

Example:
SQL> CREATE TABLE Student (sno NUMBER (3), sname CHAR (10), class CHAR
(5));

2. Identify the syntax for defining constraints.

There are 5 constraints available in ORACLE:


1. NOT NULL: When a column is defined as NOTNULL, then that column becomes a
mandatory column. It implies that a value must be entered into the column if the record
is to be accepted for storage in the table.
Syntax:
CREATE TABLE Table_Name(column_name data_type(size) NOT NULL, );
Example:
CREATE TABLE student (sno NUMBER(3)NOT NULL, name CHAR(10));
2. UNIQUE: The purpose of a unique key is to ensure that information in the column(s)
is unique i.e. a value entered in column(s) defined in the unique constraint must not be
repeated across the column(s). A table may have many unique keys.
Syntax:
CREATE TABLE Table_Name(column_name data_type(size) UNIQUE, ….);
Example:
CREATE TABLE student (sno NUMBER(3) UNIQUE, name CHAR(10));
3. CHECK: Specifies a condition that each row in the table must satisfy. To satisfy the
constraint, each row in the table must make the condition either TRUE or unknown (due
to a null).
Syntax:

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 6
CREATE TABLE Table_Name(column_name data_type(size) CHECK(logical
expression), ….);
Example: CREATE TABLE student (sno NUMBER (3), name CHAR(10),class
CHAR(5),CHECK(class IN(‘CSE’,’CAD’,’VLSI’));
4. PRIMARY KEY: A field which is used to identify a record uniquely. A column or
combination of columns can be created as primary key, which can be used as a
reference from other tables. A table contains primary key is known as Master Table.
 It must uniquely identify each record in a table.
 It must contain unique values.
 It cannot be a null field.
 It cannot be multi port field.
 It should contain a minimum no. of fields necessary to be called unique.
Syntax:
CREATE TABLE Table_Name(column_name data_type(size) PRIMARY KEY, ….);
Example:
CREATE TABLE faculty (fcode NUMBER(3) PRIMARY KEY, fname CHAR(10));
5. FOREIGN KEY: It is a table level constraint. We cannot add this at column level. To
reference any primary key column from other table this constraint can be used. The
table in which the foreign key is defined is called a detail table. The table that defines
the primary key and is referenced by the foreign key is called the master table.
Syntax: CREATE TABLE Table_Name(column_name data_type(size)
FOREIGN KEY(column_name) REFERENCES table_name);
Example:
CREATE TABLE subject (scode NUMBER (3) PRIMARY KEY,
subname CHAR(10),fcode NUMBER(3),
FOREIGN KEY(fcode) REFERENCE faculty );
Defining integrity constraints in the alter table command:
Syntax: ALTER TABLE Table_Name ADD PRIMARY KEY (column_name);
Example: ALTER TABLE student ADD PRIMARY KEY (sno);
(Or)

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 7
Syntax: ALTER TABLE table_name ADD CONSTRAINT constraint_name
PRIMARY KEY(colname)
Example: ALTER TABLE student ADD CONSTRAINT SN PRIMARY KEY(SNO)
Dropping integrity constraints in the alter table command:
Syntax: ALTER TABLE Table_Name DROP constraint_name;
Example: ALTER TABLE student DROP PRIMARY KEY;
(or)
Syntax: ALTER TABLE student DROP CONSTRAINT constraint_name;
Example: ALTER TABLE student DROP CONSTRAINT SN;

3. Identify the code for using the INSERT statement.

a) Inserting a single record


Syntax: INSERT INTO relationname(field_1,field_2,.field_n)VALUES
(data_1,data_2,........data_n);
Example: SQL>INSERT INTO student(sno,sname,class,address)VALUES
(1,’Ravi’,’M.Tech’,’Palakol’);
4. Identify the code for using the UPDATE statement.

. UPDATE-SET-WHERE: This is used to update the content of a record in a relation.


Syntax: SQL>UPDATE relation name SET Field_name1=data,field_name2=data,
WHERE field_name=data;
Example: SQL>UPDATE student SET sname = ‘kumar’ WHERE sno=1;
5. Identify the code for using the DELETE statement.
DELETE-FROM: This is used to delete all the records of a relation but it will retain the
structure of that relation.
a) DELETE-FROM: This is used to delete all the records of relation.
Syntax: SQL>DELETE FROM relation_name;
Example: SQL>DELETE FROM std;
b) DELETE -FROM-WHERE: This is used to delete a selected record from a relation.
Syntax: SQL>DELETE FROM relation_name WHERE condition;

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 8
Example: SQL>DELETE FROM student WHERE sno = 2;
6. Identify the SQL statement to retrieve data from tables.

1. SELECT FROM: To display all fields for all records.


Syntax : SELECT * FROM relation_name;
Example : SQL> select * from dept;
DEPTNO DNAME LOC
-------- ----------- ----------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
2. SELECT FROM: To display a set of fields for all records of relation.
Syntax: SELECT a set of fields FROM relation_name;
Example: SQL> select deptno, dname from dept;
DEPTNO DNAME
------- ----------
10 ACCOUNTING
20 RESEARCH
30 SALES
4. SELECT - FROM -GROUP BY: This query is used to group to all the records in a
relation together for each and every value of a specific key(s) and then display them for
a selected set of fields the relation.
Syntax: SELECT a set of fields FROM relation_name GROUP BY field_name;
Example: SQL> SELECT EMPNO, SUM (SALARY) FROM EMP GROUP BY
EMPNO;
EMPNO SUM (SALARY)
------ ----------
1 3000
2 4000
3 5000

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 9
4 6000
4 rows selected.
7. Identify the arithmetic expressions used to perform operations on data.
1. Count: COUNT following by a column name returns the count of tuple in that column.
If DISTINCT keyword is used then it will return only the count of unique tuple in the
column. Otherwise, it will return count of all the tuples (including duplicates) count (*)
indicates all the tuples of the column.
Syntax: COUNT (Column name)
Example: SELECT COUNT (Sal) FROM emp;
2. SUM: SUM followed by a column name returns the sum of all the values in that
column.
Syntax: SUM (Column name)
Example: SELECT SUM (Sal) From emp;
3. AVG: AVG followed by a column name returns the average value of that column
values.
Syntax: AVG (n1,n2..)
Example: Select AVG(10, 15, 30) FROM DUAL;
4. MAX: MAX followed by a column name returns the maximum value of that column.
Syntax: MAX (Column name)
Example: SELECT MAX (Sal) FROM emp;
SQL> select deptno,max(sal) from emp group by deptno;
DEPTNO MAX(SAL)
------ --------
10 5000
20 3000
30 2850
SQL> select deptno,max(sal) from emp group by deptno having max(sal)<3000;
DEPTNO MAX(SAL)
----- --------
30 2850

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 10
5. MIN: MIN followed by column name returns the minimum value of that column.
Syntax: MIN (Column name)
Example: SELECT MIN (Sal) FROM emp;
SQL>select deptno,min(sal) from emp group by deptno having min(sal)>1000;
DEPTNO MIN(SAL)
----- --------
10 1300
8. Identify the use of the WHERE clause in restricting the result set of an SQL query.

SELECT - FROM -WHERE: This query is used to display a selected set of fields for a
selected set of records of a relation.
Syntax: SELECT a set of fields FROM relation_name WHERE condition;
Example: SQL> select * FROM dept WHERE deptno<=20;
DEPTNO DNAME LOC
------ ----------- ------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS

9 Identify the use of the comparison operators used in a WHERE clause to restrict the
query results.

Comparison operators, such as: =, < >, <, and >

For example, the following query retrieves the rows from the Product table for the
products that are in class H.

SELECT ProductID, Name


FROM AdventureWorks2008R2.Production.Product
WHERE Class = 'H'
ORDER BY ProductID;

Ranges (BETWEEN and NOT BETWEEN)


For example, the following query retrieves rows from the Product table with list prices
from $100 to $500.

SELECT ProductID, Name


FROM AdventureWorks2008R2.Production.Product

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 11
WHERE ListPrice BETWEEN 100 and 500
ORDER BY ListPrice;

Lists (IN, NOT IN)

For example, the following query retrieves products that fall in a list of colors.

SELECT ProductID, Name


FROM AdventureWorks2008R2.Production.Product
WHERE Color IN ('Multi', 'Silver')
ORDER BY ProductID;

Pattern matches (LIKE and NOT LIKE)


For example, the following query retrieves rows from the Product table in which the
product name starts with the letters Ch.

SELECT ProductID, Name


FROM AdventureWorks2008R2.Production.Product
WHERE Name LIKE 'Ch%'
ORDER BY ProductID;

Null values (IS NULL and IS NOT NULL)


For example, the following query retrieves rows from the Customer table in which the
salesperson IDs of the customers are not NULL.

SELECT s.Name
FROM AdventureWorks2008R2.Sales.Customer c
JOIN AdventureWorks2008R2.Sales.Store s
ON c.CustomerID = S.CustomerID
WHERE c.CustomerID IS NOT NULL
ORDER BY s.Name;

10 Identify the rules of precedence associated with WHERE clause.

Expressions in where clause process in the following order:


Number Expression
1 Arithmetic Operators
2 Concatenation Operator
3 Comparision Condition
IS [NOT] NULL, LIKE,
4
[NOT] IN
5 [NOT] BETWEEN
6 Not Equal To
7 NOT Logical Condition

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 12
8 AND Logical Condition
9 OR Logical Condition

SQL> SELECT t.employee_id, t.first_name, t.last_name, t.salary  ,t.manager_id


  2    FROM employees t
  3   WHERE t.salary > 15000
  4         AND t.manager_id = 100
  5         OR t.manager_id = 103;
 
EMPLOYEE_ID FIRST_NAME           LAST_NAME                     SALARY
MANAGER_ID
----------- -------------------- ------------------------- ---------- ----------
        101 Neena                Kochhar                     17000,00        100
        102 Lex                  De Haan                     17000,00        100
        104 Bruce                Ernst                        6000,00        103
        105 David                Austin                       4800,00        103
        106 Valli                Pataballa                    4800,00        103
        107 Diana                Lorentz                      4200,00        103
 
6 rows selected
SQL> SELECT t.employee_id, t.first_name, t.last_name, t.salary  ,t.manager_id
  2    FROM employees t
  3   WHERE t.salary > 15000
  4         OR t.manager_id = 100
  5         AND t.manager_id = 103;
 
EMPLOYEE_ID FIRST_NAME           LAST_NAME                     SALARY
MANAGER_ID
----------- -------------------- ------------------------- ---------- ----------
        210 Sue                 Andreas                     20000,00        145
        100 Steven               Black                       24000,00
        101 Neena                Kochhar                     17000,00        100
        102 Lex                  De Haan                     17000,00        100
 
SQL>
In the first query, we try to find employees supply this condition => (salary>15000
and manager_id = 100) or (manager_id=103).
In the second query, we try to find employees supply this condition => (manager_id
= 100 and manager_id = 103) or (salary > 15000)

11 Identify the methods of the sorting result set of a query using the ORDER BY clause.

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 13
5. SELECT - FROM -ORDER BY: This query is used to display a selected set of fields
from a relation in an ordered manner base on some field.
Syntax: SELECT a set of fields FROM relation_name
ORDER BY field_name;
Example: SQL> SELECT empno,ename,job FROM emp ORDER BY job;
EMPNO ENAME JOB
------ --------- --------
4 RAVI MANAGER
2 aravind Manager
1 sagar clerk
3 Laki clerk
4rows selected.
12 Identify substitution variables that are used while retrieving data by using SQL
statements.

SELECT EMPLOYEE_ID, LAST_NAME, SALARY

FROM employees

WHERE LAST_NAME = &last_name

OR EMPLOYEE_ID = &EMPNO;

Enter value for last_name:

Enter value for empno:

13 Identify guidelines for using the GROUP BY clause.

(1) All the dependent columns or columns used in GROUP BY function must form the
basis of grouping, hence must be included in GROUP BY clause also.

SELECT DEPARTMENT_ID, SUM(SALARY)

FROM employees;

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 14
DEPARTMENT_ID,

ERROR at line 2:

ORA-00937: not a single-group group function

(2) GROUP BY clause does not support the use of column alias, but the actual names.

(3) GROUP BY clause can only be used with aggregate functions like SUM, AVG,
COUNT, MAX, and MIN.If it is used with single row functions,Oracle throws and
exception as "ORA-00979: not a GROUP BY expression".

(4) Aggregate functions cannot be used in a GROUP BY clause. Oracle will return the
"ORA-00934: group function not allowed" here error message.

Below query lists the count of employees working in each department.

SELECT DEPARTMENT_ID, COUNT (*)

FROM employees

GROUP BY DEPARTMENT_ID;

Similarly, below query to find sum of salaries for respective job ids in each department.
Note the group is established based on Department and Job id. So they appear in
GROUP BY clause.

SELECT DEPARTMENT_ID, JOB_ID, SUM (SAL)

FROM employees

GROUP BY DEPARTMENT_ID, JOB_ID;

The below query also produces the same result. Please note that grouping is based on
the department id and job id columns but not used for display purpose.

SELECT SUM (SALARY)

FROM employees

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 15
GROUP BY DEPARTMENT_ID, JOB_ID;

14 Identify the features of the ROLLUP operator and CUBE operator.


In addition to the regular aggregation results we expect from the GROUP BY clause,
the ROLLUP extension produces group subtotals from right to left and a grand total. If
"n" is the number of columns listed in the ROLLUP, there will be n+1 levels of subtotals.

SELECT fact_1_id,
fact_2_id,
SUM(sales_value) AS sales_value
FROM dimension_tab
GROUP BY ROLLUP (fact_1_id, fact_2_id)
ORDER BY fact_1_id, fact_2_id;

FACT_1_ID FACT_2_ID SALES_VALUE


---------- ---------- -----------
1 1 4363.55
1 2 4794.76
1 3 4718.25
1 4 5387.45
1 5 5027.34
1 24291.35
2 1 5652.84
2 2 4583.02
2 3 5555.77
2 4 5936.67
2 5 4508.74
2 26237.04
50528.39

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 16
13 rows selected.

CUBE
In addition to the subtotals generated by the ROLLUP extension, the CUBE extension
will generate subtotals for all combinations of the dimensions specified. If "n" is the
number of columns listed in the CUBE, there will be 2n subtotal combinations.

SELECT fact_1_id,
fact_2_id,
SUM(sales_value) AS sales_value
FROM dimension_tab
GROUP BY CUBE (fact_1_id, fact_2_id)
ORDER BY fact_1_id, fact_2_id;

FACT_1_ID FACT_2_ID SALES_VALUE


---------- ---------- -----------
1 1 4363.55
1 2 4794.76
1 3 4718.25
1 4 5387.45
1 5 5027.34
1 24291.35
2 1 5652.84
2 2 4583.02
2 3 5555.77
2 4 5936.67

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 17
2 5 4508.74
2 26237.04
1 10016.39
2 9377.78
3 10274.02
4 11324.12
5 9536.08
50528.39

18 rows selected.

15 Identify the syntax for altering and dropping a table.

The ALTER TABLE statement is used to add, delete, or modify columns in an existing
table.
The ALTER TABLE statement is also used to add and drop various constraints on an
existing table.
ALTER TABLE - ADD Column
To add a column in a table, use the following syntax:
ALTER TABLE table_name
ADD column_name datatype;

To delete a column in a table, use the following syntax (notice that some database
systems don't allow deleting a column):

ALTER TABLE table_name
DROP COLUMN column_name;

ALTER TABLE - ALTER/MODIFY COLUMN

ALTER TABLE table_name
MODIFY column_name datatype;

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 18
DROP COLUMN Example
we want to delete the column named "DateOfBirth" in the "Persons" table.
We use the following SQL statement:
ALTER TABLE Persons
DROP COLUMN DateOfBirth;

The SQL DROP TABLE Statement


The DROP TABLE statement is used to drop an existing table in a database.
Syntax
DROP TABLE table_name;

DROP TABLE Shippers;

16 Identify features of views.

Oracle View
In Oracle, view is a virtual table that does not physically exist. It is stored in Oracle data
dictionary and do not store any data. It can be executed when called.
A view is created by a query joining one or more tables.
17 Identify syntax for performing various tasks for managing views.
Oracle CREATE VIEW
Syntax:
1. CREATE VIEW view_name AS  
2. SELECT columns  
3. FROM tables  
4. WHERE conditions;  
Parameters:
oview_name: It specifies the name of the Oracle VIEW that you want to create.
Example:
Let's take an example to create view. In this example, we are creating two tables
suppliers and orders first.
Suppliers table:
1.    

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 19
2. CREATE TABLE  "SUPPLIERS"  
3.    (    "SUPPLIER_ID" NUMBER,   
4.     "SUPPLIER_NAME" VARCHAR2(4000),   
5.     "SUPPLIER_ADDRESS" VARCHAR2(4000)  
6.    )  
7. /  
8.    
Orders table:
1. CREATE TABLE  "ORDERS"   
2.    (    "ORDER_NO." NUMBER,   
3.     "QUANTITY" NUMBER,   
4.     "PRICE" NUMBER  
5.    )  
6. /  
Execute the following query to create a view name sup_orders.
Create View Query:
1. CREATE VIEW sup_orders AS  
2. SELECT suppliers.supplier_id, orders.quantity, orders.price  
3. FROM suppliers  
4. INNER JOIN orders  
5. ON suppliers.supplier_id = supplier_id  
6. WHERE suppliers.supplier_name = 'VOJO';  
Output:
View created.
0.21 seconds
You can now check the Oracle VIEW by this query:
1. SELECT * FROM sup_orders;  
Output:
SUPPLIER_ID QUANTITY PRICE
3 35 70
3 26 125
3 18 100
3 rows returned in 0.00 seconds
Oracle Update VIEW

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 20
In Oracle, the CREATE OR REPLACE VIEW statement is used to modify the definition
of an Oracle VIEW without dropping it.
Syntax:
1. CREATE OR REPLACE VIEW view_name AS  
2.   SELECT columns  
3.   FROM table  
4.   WHERE conditions;   
Example:
Execute the following query to update the definition of Oracle VIEW called sup_orders
without dropping it.
1. CREATE or REPLACE VIEW sup_orders AS  
2.   SELECT suppliers.supplier_id, orders.quantity, orders.price  
3.   FROM suppliers  
4.   INNER JOIN orders  
5.   ON suppliers.supplier_id = supplier_id  
6.   WHERE suppliers.supplier_name = 'HCL';  
You can now check the Oracle VIEW by this query:
1. SELECT * FROM sup_orders;  
Output:
SUPPLIER_ID QUANTITY PRICE
1 35 70
1 26 125
1 18 100
row(s) 1 - 3 of 3
Oracle DROP VIEW
The DROP VIEW statement is used to remove or delete the VIEW completely.
Syntax:
1. DROP VIEW view_name;  
Example:
1. DROP VIEW sup_orders;  

18 Identify the syntax for creating and dropping synonyms.

Create Synonym (or Replace)

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 21
Syntax
The syntax to create a synonym in Oracle is:

CREATE [OR REPLACE] [PUBLIC] SYNONYM [schema .] synonym_name


FOR [schema .] object_name [@ dblink];

OR REPLACE
Allows you to recreate the synonym (if it already exists) without having to issue a
DROP synonym command.
PUBLIC
It means that the synonym is a public synonym and is accessible to all users.
Remember though that the user must first have the appropriate privileges to the
object to use the synonym.
schema
The appropriate schema. If this phrase is omitted, Oracle assumes that you are
referring to your own schema.
object_name
The name of the object for which you are creating the synonym. It can be one of
the following:
 table
 view
 sequence
 stored procedure
 function
 package
 materialized view
 java class schema object
 user-defined object
 synonym

Example
For example:

CREATE PUBLIC SYNONYM suppliers


FOR app.suppliers;

This first CREATE SYNONYM example demonstrates how to create a synonym


called suppliers. Now, users of other schemas can reference the table

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 22
called suppliers without having to prefix the table name with the schema named app.
For example:

SELECT *
FROM suppliers;

If this synonym already existed and you wanted to redefine it, you could always use
the OR REPLACE phrase as follows:

CREATE OR REPLACE PUBLIC SYNONYM suppliers


FOR app.suppliers;

Drop synonym
Once a synonym has been created in Oracle, you might at some point need to drop the
synonym.

Syntax
The syntax to drop a synonym in Oracle is:

DROP [PUBLIC] SYNONYM [schema .] synonym_name [force];

PUBLIC
Allows you to drop a public synonym. If you have specified PUBLIC, then you
don't specify a schema.
force
It will force Oracle to drop the synonym even if it has dependencies. It is probably
not a good idea to use force as it can cause invalidation of Oracle objects.

Example
Let's look at an example of how to drop a synonym in Oracle.
For example:

DROP PUBLIC SYNONYM suppliers;

This DROP statement would drop the synonym called suppliers that we defined earlier.
19 Identify the syntax for creating and dropping indexes.

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 23
CREATE INDEX Syntax
CREATE INDEX index_name
ON table_name (column1, column2, ...);

CREATE UNIQUE INDEX Syntax


Creates a unique index on a table. Duplicate values are not allowed:

CREATE UNIQUE INDEX index_name
ON table_name (column1, column2, ...);

CREATE INDEX Example


The SQL statement below creates an index named "idx_lastname" on the "LastName"
column in the "Persons" table:
CREATE INDEX idx_lastname
ON Persons (LastName);
If you want to create an index on a combination of columns, you can list the column
names within the parentheses, separated by commas:
CREATE INDEX idx_pname
ON Persons (LastName, FirstName);

DROP INDEX Statement


The DROP INDEX statement is used to delete an index in a table.
DROP INDEX index_name;

20 Identify the syntax for creating and using a sequence.

Create Sequence

Syntax
The syntax to create a sequence in Oracle is:

CREATE SEQUENCE sequence_name

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 24
MINVALUE value
MAXVALUE value
START WITH value
INCREMENT BY value
CACHE value;

sequence_name
The name of the sequence that you wish to create.

Example
Let's look at an example of how to create a sequence in Oracle.
For example:

CREATE SEQUENCE supplier_seq


MINVALUE 1
MAXVALUE 999999999999999999999999999
START WITH 1
INCREMENT BY 1
CACHE 20;
CREATE SEQUENCE supplier_seq
MINVALUE 1
START WITH 1
INCREMENT BY 1
CACHE 20;

Now that you've created a sequence object to simulate an autonumber field, we'll cover
how to retrieve a value from this sequence object. To retrieve the next value in the
sequence order, you need to use nextval.
For example:

supplier_seq.NEXTVAL;

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 25
This would retrieve the next value from supplier_seq. The nextval statement needs to
be used in a SQL statement. For example:

INSERT INTO suppliers


(supplier_id, supplier_name)
VALUES
(supplier_seq.NEXTVAL, 'Kraft Foods');

This insert statement would insert a new record into the suppliers table.


The supplier_id field would be assigned the next number from
the supplier_seq sequence. The supplier_name field would be set to Kraft Foods.

Drop Sequence
Once you have created your sequence in Oracle, you might find that you need to
remove it from the database.

Syntax
The syntax to a drop a sequence in Oracle is:

DROP SEQUENCE sequence_name;

sequence_name
The name of the sequence that you wish to drop.

Example
Let's look at an example of how to drop a sequence in Oracle.
For example:

DROP SEQUENCE supplier_seq;

21 Identify the features of single row character functions.

General functions
The SELECT query below demonstrates the use of NVL function.

SELECT first_name, last_name, salary, NVL (commission_pct,0)

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 26
FROM employees

WHERE rownum < 5;

FIRST_NAME LAST_NAME SALARY NVL(COMMISSION_PCT,0)

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

Steven King 24000 0

Neena Kochhar 17000 0

Lex De Haan 17000 0

Alexander Hunold 9000 0

Case Conversion functions


The SELECT query below demonstrates the use of case conversion functions.

SELECT UPPER (first_name), INITCAP (last_name), LOWER (job_id)

FROM employees

WHERE rownum < 5;

UPPER(FIRST_NAME) INITCAP(LAST_NAME) LOWER(JOB_

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

STEVEN King ad_pres

NEENA Kochhar ad_vp

LEX De Haan ad_vp

ALEXANDER Hunold it_prog

Character functions
The SELECT query below demonstrates the use of CONCAT function to concatenate
two string values.

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 27
SELECT CONCAT (first_name, last_name)

FROM employees

WHERE rownum < 5;

CONCAT(FIRST_NAME,LAST_NAME)

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

EllenAbel

SundarAnde

MozheAtkinson

DavidAustin

The SELECT query below demonstrates the use of SUBSTR and INSTR functions.
SUBSTR function returns the portion of input string from 1st position to 5th position.
INSTR function returns the numeric position of character 'a' in the first name.

SELECT SUBSTR (first_name,1,5), INSTR (first_name,'a')

FROM employees

WHERE rownum < 5;

SUBST INSTR(FIRST_NAME,'A')

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

Ellen 0

Sunda 5

Mozhe 0

David 2

The SELECT query below demonstrates the usage of LPAD and RPAD to pretty print
the employee and job information.

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 28
SELECT RPAD(first_name,10,'_')||LPAD (job_id,15,'_')

FROM employees

WHERE rownum < 5;

RPAD(FIRST_NAME,10,'_')||

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

Steven____________AD_PRES

Neena_______________AD_VP

Lex_________________AD_VP

Alexander_________IT_PROG

22 Match the number functions with their purpose.


Number functions
The SELECT query below demonstrates the use of ROUND and TRUNC functions.

SELECT ROUND (1372.472,1)

FROM dual;

ROUND(1372.472,1)

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

1372.5

SELECT TRUNC (72183,-2)

FROM dual;

TRUNC(72183,-2)

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 29
---------------

72100

Date arithmetic operations


The SELECT query below shows a date arithmetic function where difference of
employee hire date and sysdate is done.

SELECT employee_id, (sysdate - hire_date) Employment_days

FROM employees

WHERE rownum < 5;

EMPLOYEE_ID EMPLOYMENT_DAYS

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

100 3698.61877

101 2871.61877

102 4583.61877

103 2767.61877

23 Identify the features of Date functions.

Date functions
The SELECT query below demonstrates the use of MONTHS_BETWEEN,
ADD_MONTHS, NEXT_DAY and LAST_DAY functions.

SELECT employee_id, MONTHS_BETWEEN (sysdate, hire_date)


Employment_months

FROM employees

WHERE rownum < 5;

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 30
EMPLOYEE_ID EMPLOYMENT_MONTHS

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

100 121.504216

101 94.3751837

102 150.633248

103 90.9558289

SELECT ADD_MONTHS (sysdate, 5), NEXT_DAY (sysdate), LAST_DAY (sysdate)

FROM dual;

ADD_MONTH NEXT_DAY( LAST_DAY(

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

01-JAN-14 05-AUG-13 31-AUG-13

24 Identify features the functions used to convert data types.(to_char,to_num,to_date)


TO_CHAR function
TO_CHAR function is used to typecast a numeric or date input to character type with a
format model (optional).

Syntax

TO_CHAR(number1, [format], [nls_parameter])

SELECT first_name,

TO_CHAR (hire_date, 'MONTH DD, YYYY') HIRE_DATE,

TO_CHAR (salary, '$99999.99') Salary

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 31
FROM employees

WHERE rownum < 5;

FIRST_NAME HIRE_DATE SALARY

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

Steven JUNE 17, 2003 $24000.00

Neena SEPTEMBER 21, 2005 $17000.00

Lex JANUARY 13, 2001 $17000.00

Alexander JANUARY 03, 2006 $9000.00

TO_NUMBER function
The TO_NUMBER function converts a character value to a numeric datatype. If the
string being converted contains nonnumeric characters, the function returns an error.

Syntax

TO_NUMBER (string1, [format], [nls_parameter])

The SELECT queries below accept numbers as character inputs and prints them
following the format specifier.

SELECT TO_NUMBER('121.23', '9G999D99')

FROM DUAL

TO_NUMBER('121.23','9G999D99')

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

121.23

SELECT TO_NUMBER('1210.73', '9999.99')

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 32
FROM DUAL;

TO_NUMBER('1210.73','9999.99')

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

1210.73

25 Identify the syntax for displaying dates in different formats.

TO_DATE function
The function takes character values as input and returns formatted date equivalent of
the same. 

Syntax:

TO_DATE( string1, [ format_mask ], [ nls_language ] )

SELECT TO_DATE('January 15, 1989, 11:00 A.M.', 'Month dd, YYYY, HH:MI A.M.',
'NLS_DATE_LANGUAGE = American')

FROM DUAL;

TO_DATE('

---------

15-JAN-89

26 Identify features of general functions.(NVL,NVL2)


The NVL function allows you to replace null values with a default value. If the value in
the first parameter is null, the function returns the value in the second parameter. If the
first parameter is any value other than null, it is returned unchanged.
We know that COL1 in the test table contains null in all rows except the first. Using
the NVL function we replace the null values with 'ZERO'.

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 33
SQL> SELECT id, NVL(col1, 'ZERO') AS output FROM null_test_tab ORDER
BY id;

ID OUTPUT
---------- ----------
1 ONE
2 ZERO
3 ZERO
4 ZERO

4 rows selected.

The NVL2 function accepts three parameters. If the first parameter value is not null it
returns the value in the second parameter. If the first parameter value is null, it returns
the third parameter.
The following query shows NVL2 in action.

SQL> SELECT id, NVL2(col1, col2, col3) AS output FROM null_test_tab


ORDER BY id;

ID OUTPUT
---------- ----------
1 TWO
2 THREE
3 THREE
4 THREE

4 rows selected.

27 Demonstrate the use of CASE expand DECODE functions

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 34
SELECT

SUM(CASE WHEN TO_CHAR(order_dt, 'DAY') = 'SUNDAY '

THEN sale_price ELSE 0 END) SUN,

SUM(CASE WHEN TO_CHAR(order_dt, 'DAY') = 'MONDAY '

THEN sale_price ELSE 0 END) MON,

SUM(CASE WHEN TO_CHAR(order_dt, 'DAY') = 'TUESDAY '

THEN sale_price ELSE 0 END) TUE,

SUM(CASE WHEN TO_CHAR(order_dt, 'DAY') = 'WEDNESDAY'

THEN sale_price ELSE 0 END) WED,

SUM(CASE WHEN TO_CHAR(order_dt, 'DAY') = 'THURSDAY '

THEN sale_price ELSE 0 END) THU,

SUM(CASE WHEN TO_CHAR(order_dt, 'DAY') = 'FRIDAY '

THEN sale_price ELSE 0 END) FRI,

SUM(CASE WHEN TO_CHAR(order_dt, 'DAY') = 'SATURDAY '

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 35
THEN sale_price ELSE 0 END) SAT

FROM cust_order

WHERE sale_price IS NOT NULL;

SUN MON TUE WED THU FRI SAT

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

396 112 0 180 0 50 50


SELECT

SUM(DECODE(TO_CHAR (order_dt, 'DAY'), 'SUNDAY ', sale_price, 0))


SUN,

SUM(DECODE(TO_CHAR (order_dt, 'DAY'), 'MONDAY ', sale_price, 0))


MON,

SUM(DECODE(TO_CHAR (order_dt, 'DAY'), 'TUESDAY ', sale_price, 0))


TUE,

SUM(DECODE(TO_CHAR (order_dt, 'DAY'), 'WEDNESDAY', sale_price, 0))


WED,

SUM(DECODE(TO_CHAR (order_dt, 'DAY'), 'THURSDAY ', sale_price, 0))


THU,

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 36
SUM(DECODE(TO_CHAR (order_dt, 'DAY'), 'FRIDAY ', sale_price, 0))
FRI,

SUM(DECODE(TO_CHAR (order_dt, 'DAY'), 'SATURDAY ', sale_price, 0))


SAT

FROM cust_order

WHERE sale_price IS NOT NULL;

SUN MON TUE WED THU FRI SAT

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

396 112 0 180 0 50 50

28 Identify the use of nested functions in retrieving data from tables.

CREATE OR REPLACE FUNCTION nested(some_date DATE) RETURN VARCHAR2


IS
yrstr VARCHAR2(4);
 
-- beginning of nested function in declaration section
FUNCTION turn_around (
year_string VARCHAR2)
RETURN VARCHAR2
IS
 
BEGIN
yrstr := TO_CHAR(TO_NUMBER(year_string)*2);
RETURN yrstr;
END;
-- end of nested function in declaration section

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 37
 
-- beginning of named function
BEGIN
yrstr := TO_CHAR(some_date, 'YYYY');
yrstr := turn_around(yrstr);
RETURN yrstr;
END nested;

29 Identify use of single row and multiple row sub queries sub queries to
retrieve from multiple tables.
Single-row subquery

You store information particular to products in one table, Products, and information
that pertains to sales orders in another table, SalesOrdersItems. The Products
table contains the information about the various products. The SalesOrdersItems
table contains information about customers' orders. If a company reorders products
when there are fewer than 50 of them in stock, then it is possible to answer the
question "Which products are nearly out of stock?" with this query:
SELECT ID, Name, Description, Quantity
FROM Products
WHERE Quantity < 50;
However, a more helpful result would take into consideration how frequently a
product is ordered, since having few of a product that is frequently purchased is
more of a concern than having few product that is rarely ordered.
You can use a subquery to determine the average number of items that a customer
orders, and then use that average in the main query to find products that are nearly
out of stock. The following query finds the names and descriptions of the products
which number less than twice the average number of items of each type that a
customer orders.
SELECT Name, Description
FROM Products WHERE Quantity < 2 * (
SELECT AVG( Quantity )
FROM SalesOrderItems
);
In the WHERE clause, subqueries help select the rows from the tables listed in the
FROM clause that appear in the query results. In the HAVING clause, they help
select the row groups, as specified by the main query's GROUP BY clause, that
appear in the query results.
The following example of a single-row subquery calculates the average price of the
products in the Products table. The average is then passed to the WHERE clause

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 38
of the outer query. The outer query returns the ID, Name, and UnitPrice of all
products that are less expensive than the average:
SELECT ID, Name, UnitPrice
FROM Products
WHERE UnitPrice <
( SELECT AVG( UnitPrice ) FROM Products )
ORDER BY UnitPrice DESC;

ID Name UnitPrice

401 Baseball Cap 10.00

300 Tee Shirt 9.00

400 Baseball Cap 9.00

500 Visor 7.00

501 Visor 7.00

 Example 3: Simple multiple-row subquery using IN


Suppose you want to identify items that are low in stock, while also identifying
orders for those items. You could execute a SELECT statement containing a
subquery in the WHERE clause, similar to the following:
SELECT *
FROM SalesOrderItems
WHERE ProductID IN
( SELECT ID
FROM Products
WHERE Quantity < 20 )
ORDER BY ShipDate DESC;
In this example, the subquery makes a list of all values in the ID column in the
Products table, satisfying the WHERE clause search condition. The subquery then
returns a set of rows, but only a single column. The IN keyword treats each value
as a member of a set and tests whether each row in the main query is a member of
the set.

 Example 4: Multiple-row subqueries comparing use of IN, ANY, and ALL


Two tables in the SQL Anywhere sample database contain financial results data.
The FinancialCodes table is a table holding the different codes for financial data
and their meaning. To list the revenue items from the FinancialData table, execute
the following query:

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 39
SELECT *
FROM FinancialData
WHERE Code IN
( SELECT Code
FROM FinancialCodes
WHERE type = 'revenue' );

Year Quarter Code Amount

1999 Q1 r1 1023

1999 Q2 r1 2033

1999 Q3 r1 2998

1999 Q4 r1 3014

2000 Q1 r1 3114

... ... ... ...

The ANY and ALL keywords can be used in a similar manner. For example, the
following query returns the same results as the previous query, but uses the ANY
keyword:
SELECT *
FROM FinancialData
WHERE FinancialData.Code = ANY
( SELECT FinancialCodes.Code
FROM FinancialCodes
WHERE type = 'revenue' );
While the =ANY condition is identical to the IN condition, ANY can also be used with
inequalities such as < or > to give more flexible use of subqueries.
The ALL keyword is similar to the word ANY. For example, the following query lists
financial data that is not revenue:
SELECT *
FROM FinancialData
WHERE FinancialData.Code <> ALL
( SELECT FinancialCodes.Code
FROM FinancialCodes
WHERE type = 'revenue' );
This is equivalent to the following command using NOT IN:

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 40
SELECT *
FROM FinancialData
WHERE FinancialData.Code NOT IN
( SELECT FinancialCodes.Code
FROM FinancialCodes
WHERE type = 'revenue' );
30 Identify the syntax for performing multiple-column and correlated sub
queries.

Multiple Column Subqueries

You can write subqueries that return multiple columns. The following example retrieves
the order amount with the lowest price, group by agent code.

Sample table : orders

SQL Code:

select ord_num, agent_code, ord_date, ord_amount


from orders
where(agent_code, ord_amount) IN
(SELECT agent_code, MIN(ord_amount)
FROM orders
GROUP BY agent_code);
Output:

ORD_NUM AGENT_CODE ORD_DATE ORD_AMOUNT


---------- ---------- --------- ----------
200104 A004 13-MAR-08 1500
200121 A004 23-SEP-08 1500
200126 A002 24-JUN-08 500
200120 A002 20-JUL-08 500
200123 A002 16-SEP-08 500
200124 A007 20-JUN-08 500
200116 A009 13-JUL-08 500
200105 A011 18-JUL-08 2500
200130 A011 30-JUL-08 2500
200131 A012 26-AUG-08 900

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 41
200135 A010 16-SEP-08 2000
200115 A013 08-FEB-08 2000
200117 A001 20-OCT-08 800
200111 A008 10-JUL-08 1000
200118 A006 20-JUL-08 500
200103 A005 15-MAY-08 1500
200100 A003 08-JAN-08 1000

The following correlated subqueries retrive ord_num, ord_amount, cust_code and


agent_code from the table orders ( 'a' and 'b' are the aliases of orders and agents table)
with following conditions -

the agent_code of orders table must be the same agent_code of agents table and
agent_name of agents table must be Alex,

the following SQL statement can be used:

Sample table: orders

Sample table: agents

SQL Code:

SELECT a.ord_num,a.ord_amount,a.cust_code,a.agent_code

FROM orders a

WHERE a.agent_code=(

SELECT b.agent_code

FROM agents b WHERE b.agent_name='Alex');

Output:

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 42
ORD_NUM ORD_AMOUNT CUST_CODE AGENT_CODE
---------- ---------- ---------- ----------
200127 2500 C00015 A003
200100 1000 C00015 A003
The inner of the above query returns the 'agent_code' A003.

The simplified form of above code is:

SQL Code:

SELECT a.ord_num,a.ord_amount,a.cust_code,a.agent_code
FROM orders a
WHERE a.agent_code='A003';
Pictorical Presentation:

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 43
NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB
MANUAL_REV0-Jun 2017 Page 44
Using EXISTS with a Correlated Subquery

We have already used the EXISTS operator to check the existence of a result of a
subquery. EXISTS operator can be used in correlated subqueries also. Using EXISTS
the following query display the employee_id, manager_id, first_name and last_name of
those employees who manage other employees.

SQL Code:

SELECT employee_id, manager_id, first_name, last_name


FROM employees a
WHERE EXISTS
(SELECT employee_id
FROM employees b
WHERE b.manager_id = a.employee_id)
Sample table: employees

Output:

EMPLOYEE_ID MANAGER_ID FIRST_NAME LAST_NAME


----------- ---------- -------------------- ---------------
100 Steven King
101 100 Neena Kochhar
102 100 Lex De Haan
103 102 Alexander Hunold
108 101 Nancy Greenberg
114 100 Den Raphaely
120 100 Matthew Weiss
121 100 Adam Fripp
122 100 Payam Kaufling
123 100 Shanta Vollman
124 100 Kevin Mourgos
145 100 John Russell
146 100 Karen Partners
147 100 Alberto Errazuriz
148 100 Gerald Cambrault

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 45
149 100 Eleni Zlotkey
201 100 Michael Hartstein
205 101 Shelley Higgins

Using NOT EXISTS with a Correlated Subquery

NOT EXISTS is logically opposite of EXISTS operator. NOT EXISTS is used when we
need to check if rows do not exist in the results returned by a subquery. Using NOT
EXISTS the following query display the employee_id, manager_id, first_name and
last_name of those employees who have no manager status. This query is opposite to
the previous one.

SQL Code:

SELECT employee_id, manager_id, first_name, last_name


FROM employees a
WHERE NOT EXISTS
(SELECT employee_id
FROM employees b
WHERE b.manager_id = a.employee_id);

31 Identify the use of different types of join to retrieve data from multiple
tables.

Natural Join
Consider the one-to-many relationship between the DEPARTMENTS and
EMPLOYEES tables.Each table has a column named DEPARTMENT_ID.This
column is the primary key of the DEPARTMENTS table and a foreign key of
the EMPLOYEES table.

SELECT E.first_name NAME,D.department_name DNAME

FROM employees E NATURAL JOIN departments D;

FIRST_NAME DNAME

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 46
---------- ------

MILLER DEPT 1

JOHN DEPT 1

MARTIN DEPT 2

EDWIN DEPT 2

The below SELECT query joins the two tables by explicitly specifying the
join condition with the ON keyword.

SELECT E.first_name NAME,D.department_name DNAME

FROM employees E JOIN departments D

ON (E.department_id = D.department_id);

USING Clause
Syntax:

SELECT <column list>

FROM TABLE1 JOIN TABLE2

USING (column name)

Consider the below SELECT query, EMPLOYEES table and DEPARTMENTS


table are joined using the common column DEPARTMENT_ID.

SELECT E.first_name NAME,D.department_name DNAME

FROM employees E JOIN departments D

USING (department_id);

Self Join
Consider EMPLOYEES table,which contains employee and their reporting
managers.To find manager's name for an employee would require a join on
the EMP table itself. This is a typical candidate for Self Join.

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 47
SELECT e1.FirstName Manager,e2.FirstName Employee

FROM employees e1 JOIN employees e2

ON (e1.employee_id = e2.manager_id)

ORDER BY e2.manager_id DESC;

Outer Joins
1. Right Outer Join

SELECT E.first_name, E.salary, D.department_id

FROM employees E, departments D

WHERE E.DEPARTMENT_ID (+) = D.DEPARTMENT_ID;

FIRST_NAME SALARY DEPARTMENT_ID

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

JOHN 6000 10

EDWIN 2000 20

MILLER 2500 10

MARTIN 4000 20

30

2 Left Outer Join

SELECT E.first_name, E.salary, D.department_id

FROM employees E, departments D

WHERE D.DEPARTMENT_ID = E.DEPARTMENT_ID (+);

FIRST_NAME SALARY DEPARTMENT_ID

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

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 48
JOHN 6000 10

EDWIN 2000 20

MILLER 2500 10

MARTIN 4000 20

30

3. Full Outer Join

SELECT nvl (e.first_name,'-') first_name, nvl (to_char


(d.department_id),'-') department_id

FROM employee e FULL OUTER JOIN department d

ON e. depARTMENT_ID = d. depARTMENT_ID;

FIRST_NAME DEPARTMENT_ID

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

MAN -

JOHN 10

EDWIN 20

MILLER 10

MARTIN 20

- 30

Cartesian product or Cross join


A Cartesian product result table is normally not very useful. In fact, such a
result table can be terribly misleading. If you execute the below query for
the EMPLOYEES and DEPARTMENTS tables, the result table implies that
every employee has a relationship with every department, and we know
that this is simply not the case!

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 49
SELECT E.first_name, D.DNAME

FROM employees E,departments D;

Cross join can be written as,

SELECT E.first_name, D.DNAME

FROM employees E CROSS JOIN departments D;

32 Identify the syntax of the conditional INSERT ALL statement.


Unconditional Oracle INSERT ALL statement
Insert multiple rows into a table

To insert multiple rows into a table, you use the following Oracle INSERT
ALL statement:
1 INSERT ALL
2     INTO table_name(col1,col2,col3) VALUES(val1,val2, val3)
3     INTO table_name(col1,col2,col3) VALUES(val4,val5, val6)
4     INTO table_name(col1,col2,col3) VALUES(val7,val8, val9)
5 Subquery;
In this statement, each value expression val1, val2, or val3 must refer to a column
returned by the select list of the subquery.

33 Identify the syntax of the conditional INSERT FIRST statement.


Home / Oracle Basics / The Ultimate Guide to Oracle INSERT ALL Statement
The Ultimate Guide to Oracle INSERT ALL Statement

Summary: in this tutorial, you will learn how to use the Oracle INSERT ALL statement to
insert multiple rows into a table or multiple tables.
In the previous tutorial, you have learned how to insert a row into a table. However, sometimes,
you may want to insert multiple rows into a table or multiple tables. In this case, you use the
Oracle INSERT ALL statement, which is also referred to as multitable insert statement.
Oracle provides you with two types of multitable insert statements: unconditional and
conditional.

Unconditional Oracle INSERT ALL statement


Insert multiple rows into a table

To insert multiple rows into a table, you use the following Oracle INSERT ALL statement:
1 INSERT ALL
2     INTO table_name(col1,col2,col3) VALUES(val1,val2, val3)

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 50
3     INTO table_name(col1,col2,col3) VALUES(val4,val5, val6)
4     INTO table_name(col1,col2,col3) VALUES(val7,val8, val9)
5 Subquery;
In this statement, each value expression val1, val2, or val3 must refer to a column returned by the
select list of the subquery.

If you want to use literal values instead of the values returned by the subquery, you use the
following subquery:

1 SELECT * FROM dual;


The following example demonstrates how to insert multiple rows into a table.

First, create a new table named fruits:


1 CREATE TABLE fruits (
2     fruit_name VARCHAR(100) PRIMARY KEY,
3     color VARCHAR(100) NOT NULL
4 );
Second, use the Oracle INSERT ALL statement to insert rows into the fruits table:
1 INSERT ALL
2     INTO fruits(fruit_name, color)
3     VALUES ('Apple','Red')
4  
5     INTO fruits(fruit_name, color)
6     VALUES ('Orange','Orange')
7  
8     INTO fruits(fruit_name, color)
9     VALUES ('Banana','Yellow')
10 SELECT 1 FROM dual;
Third, query data from the fruits table to verify the insertion:
1 SELECT
2     *
3 FROM
4     fruits;

As you can see, three rows were inserted as expected.

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 51
Insert multiple rows into multiple tables

You can also use the INSERT ALL statement to insert rows into multiple tables as shown
below.
1 INSERT ALL
2     INTO table_name1(col1,col2,col3) VALUES(val1,val2, val3)
3     INTO table_name2(col1,col2,col3) VALUES(val4,val5, val6)
4     INTO table_name3(col1,col2,col3) VALUES(val7,val8, val9)
5 Subquery;
Conditional Oracle INSERT ALL Statement
The conditional multitable insert statement allows you to insert rows into tables based on
specified conditions.

The following shows the syntax of the conditional multitable insert statement:

INSERT [ ALL | FIRST ]


1     WHEN condition1 THEN
2         INTO table_1 (column_list ) VALUES (value_list)
3     WHEN condition2 THEN
4         INTO table_2(column_list ) VALUES (value_list)
5     ELSE
6         INTO table_3(column_list ) VALUES (value_list)
7 Subquery
8

Conditional Oracle INSERT ALL example


The following CREATE TABLE statements create three
tables: small_orders, medium_orders, and big_orders with the same
structures:
1 CREATE TABLE small_orders (
2     order_id NUMBER(12) NOT NULL,
3     customer_id NUMBER(6) NOT NULL,
4     amount NUMBER(8,2)
5 );
6  
7 CREATE TABLE medium_orders AS
8 SELECT *
9 FROM small_orders;
10  
11 CREATE TABLE big_orders AS
12 SELECT *
13 FROM small_orders;

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 52
34

34

34 Identify the syntax of the conditional INSERT FIRST statement.

uses the FIRST clause to put orders greater than 2,900,000 into


the special_orders table and exclude those orders from the large_orders table:
INSERT FIRST

WHEN ottl < 100000 THEN

INTO small_orders

VALUES(oid, ottl, sid, cid)

WHEN ottl > 100000 and ottl < 200000 THEN

INTO medium_orders

VALUES(oid, ottl, sid, cid)

WHEN ottl > 290000 THEN

INTO special_orders

WHEN ottl > 200000 THEN

INTO large_orders

VALUES(oid, ottl, sid, cid)

SELECT o.order_id oid, o.customer_id cid, o.order_total ottl,

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 53
o.sales_rep_id sid, c.credit_limit cl, c.cust_email cem

FROM orders o, customers c

WHERE o.customer_id = c.customer_id;

35 Identify the code for retrieving data hierarchically from a table.

SELECT employee_id, last_name, manager_id

FROM employees

CONNECT BY PRIOR employee_id = manager_id;

EMPLOYEE_ID LAST_NAME MANAGER_ID

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

101 Kochhar 100

108 Greenberg 101

109 Faviet 108

110 Chen 108

111 Sciarra 108

112 Urman 108

113 Popp 108

200 Whalen 101

...

LEVEL Example The next example is similar to the preceding example, but uses
the LEVEL pseudocolumn to show parent and child rows:
SELECT employee_id, last_name, manager_id, LEVEL

FROM employees

CONNECT BY PRIOR employee_id = manager_id;

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 54
EMPLOYEE_ID LAST_NAME MANAGER_ID LEVEL

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

101 Kochhar 100 1

108 Greenberg 101 2

109 Faviet 108 3

110 Chen 108 3

111 Sciarra 108 3

112 Urman 108 3

113 Popp 108 3

...

START WITH Examples The next example adds a START WITH clause to specify a


root row for the hierarchy and an ORDER BY clause using the SIBLINGS keyword to
preserve ordering within the hierarchy:
SELECT last_name, employee_id, manager_id, LEVEL

FROM employees

START WITH employee_id = 100

CONNECT BY PRIOR employee_id = manager_id

ORDER SIBLINGS BY last_name;

LAST_NAME EMPLOYEE_ID MANAGER_ID LEVEL

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

King 100 1

Cambrault 148 100 2

Bates 172 148 3

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 55
Bloom 169 148 3

Fox 170 148 3

Kumar 173 148 3

Ozer 168 148 3

Smith 171 148 3

De Haan 102 100 2

Hunold 103 102 3

Austin 105 103 4

Ernst 104 103 4

Lorentz 107 103 4

Pataballa 106 103 4

Errazuriz 147 100 2

Ande 166 147 3

Banda 167 147 3

...

36 Generate a query using the following SET OPERATORS


 UNION
 UNION ALL
 INTERSECT
 MINUS

Example of UNION
The First table,

ID Name

1 abhi

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 56
2 adam

The Second table,

ID Name

2 adam

3 Chester

Union SQL query will be,


select * from First
UNION
select * from second
The result table will look like,

ID NAME

1 abhi

2 adam

3 Chester

Union All
This operation is similar to Union. But it also shows the duplicate rows.

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 57
Example of Union All
The First table,

ID NAME

1 abhi

2 adam

The Second table,

ID NAME

2 adam

3 Chester

Union All query will be like,

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 58
select * from First
UNION ALL
select * from second
The result table will look like,

ID NAME

1 abhi

2 adam

2 adam

3 Chester

Intersect
Intersect operation is used to combine two SELECT statements, but it only retuns the
records which are common from both SELECT statements. In case of Intersect the
number of columns and datatype must be same. MySQL does not support INTERSECT
operator.

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 59
Example of Intersect
The First table,

ID NAME

1 abhi

2 adam

The Second table,

ID NAME

2 adam

3 Chester

Intersect query will be,

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 60
select * from First
INTERSECT
select * from second
The result table will look like

ID NAME

2 adam

Minus
Minus operation combines result of two Select statements and return only those result
which belongs to first set of result. MySQL does not support INTERSECT operator.

Example of Minus
The First table,

ID NAME

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 61
1 abhi

2 adam

The Second table,

ID NAME

2 adam

3 Chester

Minus query will be,


select * from First
MINUS
select * from second
The result table will look like,

ID NAME

1 abhi

37 Controlling User Access.


 Create User
 Grant
 Revoke

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 62
SQL GRANT Command
SQL GRANT is a command used to provide access or privileges on the
database objects to the users.
The Syntax for the GRANT command is:
GRANT privileges ON object TO user;
GRANT SELECT, INSERT, UPDATE, DELETE ON employees TO smithj;
GRANT ALL ON employees TO smithj;
GRANT SELECT ON employees TO public;

Revoke Privileges on Table


REVOKE privilege-type ON [ TABLE ] { table-Name | view-Name }
FROM grantees

To revoke the SELECT privilege on table t from the authorization IDs maria and harry, use


the following syntax:
REVOKE SELECT ON TABLE t FROM maria,harry
To revoke the UPDATE and TRIGGER privileges on table t from the authorization
IDs anita and zhi, use the following syntax:
REVOKE UPDATE, TRIGGER ON TABLE t FROM anita,zhi

38 Identify features of various PL/SQL data types.

DECLARE

num1 INTEGER;

num2 REAL;

num3 DOUBLE PRECISION;

BEGIN

null;

END;

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 63
/

PL/SQL procedure successfully completed

39 Identify the syntax for declaring PL/SQL variables using the %type
attributes.

DECLARE

name VARCHAR(25) NOT NULL := 'Smith';

surname name%TYPE := 'Jones';

BEGIN

DBMS_OUTPUT.PUT_LINE('name=' || name);

DBMS_OUTPUT.PUT_LINE('surname=' || surname);

END;

name=Smith

surname=Jones

40 Identify features of bind variables and substitution variables

SQL> SELECT * FROM dual WHERE dummy = '&dummy';


Enter value for dummy: SUBSTITUTION_VARIABLE1
old 1: SELECT * FROM dual WHERE dummy = '&dummy'
new 1: SELECT * FROM dual WHERE dummy = 'SUBSTITUTION_VARIABLE1'

SQL> VARIABLE dummy VARCHAR2(30);


SQL> EXEC :dummy := 'BIND_VARIABLE1';

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 64
PL/SQL procedure successfully completed.

41 Identify the syntax of the % ROWTYPE attributes.

DECLARE
emp_rec employees%ROWTYPE;
my_empno employees.employee_id%TYPE := 100;
CURSOR c1 IS
SELECT department_id, department_name, location_id FROM
departments;
dept_rec c1%ROWTYPE;
BEGIN
SELECT * INTO emp_rec FROM employees WHERE employee_id =
my_empno;
IF (emp_rec.department_id = 20) AND (emp_rec.salary > 2000)
THEN
NULL;
END IF;
END;
/

42 Identify the syntax for creating a PL/SQL table based record.

DECLARE

customer_rec customers%rowtype;

BEGIN zzzzzzzzzzzzzzzz

SELECT * into customer_rec

FROM customers

WHERE id = 5;

dbms_output.put_line('Customer ID: ' || customer_rec.id);

dbms_output.put_line('Customer Name: ' || customer_rec.name);

dbms_output.put_line('Customer Address: ' || customer_rec.address);

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 65
dbms_output.put_line('Customer Salary: ' || customer_rec.salary);

END;

Customer ID: 5
Customer Name: Hardik
Customer Address: Bhopal
Customer Salary: 9000

PL/SQL procedure successfully completed.

43 Identify the syntax for creating a PL/SQL cursor based record.

DECLARE

CURSOR customer_cur is

SELECT id, name, address

FROM customers;

customer_rec customer_cur%rowtype;

BEGIN

OPEN customer_cur;

LOOP

FETCH customer_cur into customer_rec;

EXIT WHEN customer_cur%notfound;

DBMS_OUTPUT.put_line(customer_rec.id || ' ' ||


customer_rec.name);

END LOOP;

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 66
END;

/
1 Ramesh
2 Khilan
3 kaushik
4 Chaitali
5 Hardik
6 Komal

PL/SQL procedure successfully completed.


44 Identify the syntax for creating a PL/SQL user defined record.

TYPE
type_name IS RECORD
( field_name1 datatype1 [NOT NULL] [:= DEFAULT EXPRESSION],
field_name2 datatype2 [NOT NULL] [:= DEFAULT EXPRESSION],
...
field_nameN datatypeN [NOT NULL] [:= DEFAULT EXPRESSION);
record-name type_name;
The Book record is declared in the following way −

DECLARE

TYPE books IS RECORD

(title varchar(50),

author varchar(50),

subject varchar(100),

book_id number);

book1 books;

book2 books;

45 Identify the features of nested blocks.

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 67
46 Identify uses of PL/SQL operators.

DECLARE

a number (2) := 21;

b number (2) := 10;

BEGIN

IF (a = b) then

dbms_output.put_line('Line 1 - a is equal to b');

ELSE

dbms_output.put_line('Line 1 - a is not equal to b');

END IF;

IF (a < b) then

dbms_output.put_line('Line 2 - a is less than b');

ELSE

dbms_output.put_line('Line 2 - a is not less than b');

END IF;

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 68
IF ( a > b ) THEN

dbms_output.put_line('Line 3 - a is greater than b');

ELSE

dbms_output.put_line('Line 3 - a is not greater than b');

END IF;

-- Lets change value of a and b

a := 5;

b := 20;

IF ( a <= b ) THEN

dbms_output.put_line('Line 4 - a is either equal or less than


b');

END IF;

IF ( b >= a ) THEN

dbms_output.put_line('Line 5 - b is either equal or greater than


a');

END IF;

IF ( a <> b ) THEN

dbms_output.put_line('Line 6 - a is not equal to b');

ELSE

dbms_output.put_line('Line 6 - a is equal to b');

END IF;

END;
Line 1 - a is not equal to b
Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either equal or less than b

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 69
Line 5 - b is either equal or greater than a
Line 6 - a is not equal to b

PL/SQL procedure successfully completed

47 Identify codes for manipulating data using DML statements in PL/SQL


block.

SET SERVEROUTPUT ON

DECLARE

v_average_cost VARCHAR2(10);

BEGIN

SELECT TO_CHAR(AVG(cost), '$9,999.99')

INTO v_average_cost

FROM course;

DBMS_OUTPUT.PUT_LINE('The average cost of a '||

'course in the CTA program is '||

v_average_cost);

END;

48 Identify the syntax of decision making statement.

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 70
49 Identify the syntax of looping statement.

DECLARE

i number(1);

j number(1);

BEGIN

<< outer_loop >>

FOR i IN 1..3 LOOP

<< inner_loop >>

FOR j IN 1..3 LOOP

dbms_output.put_line('i is: '|| i || ' and j is: ' || j);

END loop inner_loop;

END loop outer_loop;

END;

i is: 1 and j is: 1


i is: 1 and j is: 2

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 71
i is: 1 and j is: 3
i is: 2 and j is: 1
i is: 2 and j is: 2
i is: 2 and j is: 3
i is: 3 and j is: 1
i is: 3 and j is: 2
i is: 3 and j is: 3

PL/SQL procedure successfully completed.

50 Identify the syntax for controlling implicit cursors and use the
attributes.

DECLARE

total_rows number(2);

BEGIN

UPDATE customers

SET salary = salary + 500;

IF sql%notfound THEN

dbms_output.put_line('no customers selected');

ELSIF sql%found THEN

total_rows := sql%rowcount;

dbms_output.put_line( total_rows || ' customers selected ');

END IF;

END;

/
6 customers selected

PL/SQL procedure successfully completed.


51 Identify the syntax for controlling explicit cursors and use the
attributes.

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 72
DECLARE

c_id customers.id%type;

c_name customerS.No.ame%type;

c_addr customers.address%type;

CURSOR c_customers is

SELECT id, name, address FROM customers;

BEGIN

OPEN c_customers;

LOOP

FETCH c_customers into c_id, c_name, c_addr;

EXIT WHEN c_customers%notfound;

dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);

END LOOP;

CLOSE c_customers;

END;

1 Ramesh Ahmedabad
2 Khilan Delhi
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP

PL/SQL procedure successfully completed.


52 Identify the syntax for using cursor FOR loops, FOR UPDATE, WHERE
CURRENT OF.

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 73
Syntax
The syntax for the WHERE CURRENT OF statement in Oracle/PLSQL is either:

UPDATE table_name
SET set_clause
WHERE CURRENT OF cursor_name;
DELETE FROM table_name
WHERE CURRENT OF cursor_name;

53 Identify guidelines for trapping system built in exceptions.

General Syntax for coding the exception section


DECLARE
Declaration section
BEGIN
Exception section
EXCEPTION
WHEN ex_name1 THEN
-Error handling statements
WHEN ex_name2 THEN
-Error handling statements
WHEN Others THEN
-Error handling statements
END;

DECLARE

stock_price NUMBER := 9.73;

net_earnings NUMBER := 0;

pe_ratio NUMBER;

BEGIN

-- Calculation might cause division-by-zero error.

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 74
pe_ratio := stock_price / net_earnings;

DBMS_OUTPUT.PUT_LINE('Price/earnings ratio = ' || pe_ratio);

EXCEPTION -- exception handlers begin

-- Only one of the WHEN blocks is executed.

WHEN ZERO_DIVIDE THEN -- handles 'division by zero' error

DBMS_OUTPUT.PUT_LINE('Company must have had zero


earnings.');

pe_ratio := NULL;

WHEN OTHERS THEN -- handles all other errors

DBMS_OUTPUT.PUT_LINE('Some other kind of error occurred.');

pe_ratio := NULL;

END; -- exception handlers and block end here

54 Identify guidelines for trapping user defined exceptions.


DECLARE

past_due EXCEPTION;

acct_num NUMBER;

BEGIN

DECLARE ---------- sub-block begins

past_due EXCEPTION; -- this declaration prevails

acct_num NUMBER;

due_date DATE := SYSDATE - 1;

todays_date DATE := SYSDATE;

BEGIN

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 75
IF due_date < todays_date THEN

RAISE past_due; -- this is not handled

END IF;

END; ------------- sub-block ends

EXCEPTION

-- Does not handle raised exception

WHEN past_due THEN

DBMS_OUTPUT.PUT_LINE

('Handling PAST_DUE exception.');

WHEN OTHERS THEN

DBMS_OUTPUT.PUT_LINE

('Could not recognize PAST_DUE_EXCEPTION in this scope.');

END;

55 Identify the syntax for raise_application_error.

SQL> create or replace procedure test_var


2 (n_test IN number := 0,
3 n_result OUT number)
4 as
5 begin
6 if n_test > 100 then
7 raise_application_error(-20010,'Number Too 
Large');
8 end if;
9 n_result := n_test;
10 end;
11 /
Procedure created.
56 Identify the syntax for passing parameters to a stored procedure.

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 76
CREATE OR REPLACE Procedure UpdateCourse
( name_in IN varchar2 )

IS
cnumber number;

cursor c1 is
SELECT course_number
FROM courses_tbl
WHERE course_name = name_in;

BEGIN

open c1;
fetch c1 into cnumber;

if c1%notfound then
cnumber := 9999;
end if;

INSERT INTO student_courses


( course_name,
course_number )
VALUES
( name_in,
cnumber );

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 77
commit;

close c1;

EXCEPTION
WHEN OTHERS THEN
raise_application_error(-20001,'An error was encountered - '||
SQLCODE||' -ERROR- '||SQLERRM);
END;

57 Identify tasks involved in using stored procedures.(IN,OUT,IN OUT)


Using IN and OUT parameter:
Let’s create a procedure which gets the name of the employee when the employee id
is passed.
1> CREATE OR REPLACE PROCEDURE emp_name (id IN NUMBER, emp_name
OUT NUMBER)
2> IS
3> BEGIN
4> SELECT first_name INTO emp_name
5> FROM emp_tbl WHERE empID = id;
6> END;
7> /

58 Identify the syntax for creating PL/SQL function.


CREATE [OR REPLACE] FUNCTION function_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
END [function_name];

CREATE OR REPLACE FUNCTION totalCustomers

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 78
RETURN number IS

total number(2) := 0;

BEGIN

SELECT count(*) into total

FROM customers;

RETURN total;

END;

/
Function created.

59 Trapping predefined and user defined exception in subprogram.


SET SERVEROUTPUT ON;

DECLARE
stock_price NUMBER := 9.73;
net_earnings NUMBER := 0;
pe_ratio NUMBER;
BEGIN
-- Calculation might cause division-by-zero error.
pe_ratio := stock_price / net_earnings;
dbms_output.put_line('Price/earnings ratio = ' || pe_ratio);

EXCEPTION -- exception handlers begin

-- Only one of the WHEN blocks is executed.

WHEN ZERO_DIVIDE THEN -- handles 'division by zero' error


dbms_output.put_line('Company must have had zero
earnings.');
pe_ratio := null;

WHEN OTHERS THEN -- handles all other errors


dbms_output.put_line('Some other kind of error occurred.');
pe_ratio := null;

END; -- exception handlers and block end here

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 79
/

60 Identify sequence steps for developing PL/SQL packages.

CREATE PACKAGE cust_sal AS

PROCEDURE find_sal(c_id customers.id%type);

END cust_sal;

/
Package created.

CREATE OR REPLACE PACKAGE BODY cust_sal AS

PROCEDURE find_sal(c_id customers.id%TYPE) IS

c_sal customers.salary%TYPE;

BEGIN

SELECT salary INTO c_sal

FROM customers

WHERE id = c_id;

dbms_output.put_line('Salary: '|| c_sal);

END find_sal;

END cust_sal;

Package body created.

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 80
61 Identify the code to create a trigger.
The syntax for creating a trigger is −

CREATE [OR REPLACE ] TRIGGER trigger_name

{BEFORE | AFTER | INSTEAD OF }

{INSERT [OR] | UPDATE [OR] | DELETE}

[OF col_name]

ON table_name

[REFERENCING OLD AS o NEW AS n]

[FOR EACH ROW]

WHEN (condition)

DECLARE

Declaration-statements

BEGIN

Executable-statements

EXCEPTION

Exception-handling-statements

END;

CREATE OR REPLACE TRIGGER display_salary_changes

BEFORE DELETE OR INSERT OR UPDATE ON customers

FOR EACH ROW

WHEN (NEW.ID > 0)

DECLARE

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 81
sal_diff number;

BEGIN

sal_diff := :NEW.salary - :OLD.salary;

dbms_output.put_line('Old salary: ' || :OLD.salary);

dbms_output.put_line('New salary: ' || :NEW.salary);

dbms_output.put_line('Salary difference: ' || sal_diff);

END;

62 Write program to show use of new and old keywords in a trigger program.
CREATE or REPLACE TRIGGER price_history_trigger
BEFORE UPDATE OF unit_price
ON product
FOR EACH ROW
BEGIN
INSERT INTO product_price_history
VALUES
(:old.product_id,
:old.product_name,
:old.supplier_name,
:old.unit_price);
END;
/
63 Demonstrate the following TCL operations with suitable example
 COMMIT
 SAVEPOINT
 ROLLBACK

 SQL> DELETE FROM CUSTOMERS

 WHERE AGE = 25;

 SQL> COMMIT;

 The syntax for a ROLLBACK command is as follows −


 ROLLBACK

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 82
 SQL> DELETE FROM CUSTOMERS

 WHERE AGE = 25;

 SQL> ROLLBACK;

The syntax for a SAVEPOINT command is as shown below.

SAVEPOINT SAVEPOINT_NAME;

SQL> SAVEPOINT SP1;

Savepoint created.

SQL> DELETE FROM CUSTOMERS WHERE ID=1;

1 row deleted.

SQL> SAVEPOINT SP2;

Savepoint created.

SQL> DELETE FROM CUSTOMERS WHERE ID=2;

1 row deleted.

SQL> SAVEPOINT SP3;

Savepoint created.

SQL> DELETE FROM CUSTOMERS WHERE ID=3;

1 row deleted.

NTTF _Diploma in INFORMATION TECHNOLOGY_SEM4_ORACLE LAB


MANUAL_REV0-Jun 2017 Page 83

You might also like