Oracle
Oracle
Introduction to IM
What is a data
Any factual information in raw and disorganized form is called data.
What is a database
A database is a collection of related data organized in a way that data can be easily accessed
,managed and updated.
Database Management System
• A general-purpose Database Management System(DBMS) is a software system
designed to allow the definition, creation, querying, updating and administration of
databases.
• Well-known DBMS's include MySql,Oracle,Microsoft SQL server,Foxpro,SQLite,
FileMaker Pro.
• The primary goal of a Database Management System(DBMS) is to provide a way to store
and retrieve database information that is both convenient and efficient.
Traditional File Processing System
A file system is a method of storing and organizing computer files and the data they contain and
to make it easy to find and access them.
Limitations of File processing System:
1. Separated and Isolated Data
2. Data Redundancy
3. Data Dependence
4. Difficulty in representing data from the user's view
5. Inflexibility in retrieving the Data
6. Data Security
7. Transactional Problems
8. Concurrency problems
Need of a Database Management System
To overcome the limitations of the traditional file processing system , the modern DBMS was
created.
Functions of DBMS :
1. Minimal Data Redundancy
2. Data Consistency
3. Data Integration
4. Data Sharing
5. Application Development Ease
6. Better Controls
7. Data Independence
8. Reduced Maintenance
Types of DBMS
Commonly used databases are:
1. Hierarchical Database
2. Network model database
3. Object relational database
4. Relational database Model
Hierarchical DBMS:
1. A DBMS is said to be hierarchical if the relationships among data in the database are
established in such a way that one data item is present as the subordinate of another one
or a sub unit.
2. The data structure "tree" is followed by the DBMS to structure the database.
RDBMS terms
Relation:
The Relation is a collection of related data entries and it consists of columns and rows.
Tuple:
A tuple, also called a row of data, is each individual entry that exists in a table.
Fields:
• Every table is broken up into smaller entities called fields.
• A field is a column in a table that is designed to maintain specific information about
every record in the table.
Keys in DBMS
Keys are used to establish and identify relation between tables
Super Key:
A Super key is any combination of fields within a table that uniquely identifies each record within
that table.
Candidate Key:
2. A candidate key is a single field or the least combination of fields that uniquely identifies
each record in the table.
3. The least combination of fields distinguishes a candidate key from a super key.
Primary key:
1. A primary key is a candidate key that is most appropriate to be the main reference key for
the table.
Foreign key:
1. A foreign key is the field that generally references values from primary key field of other
table
Data Query Language
Introduction to SQL
Structured Query Language or SQL is a tool for organizing, managing, and retrieving data stored
in a computer database.
SQL Statements can be divided into following sub categories:
• Data Definition Language (DDL)
• Data Manipulation Language (DML)
• Data Query Language (DQL)
• Data Control Language (DCL)
• Transaction Control Language (TCL)
Data Query Language : SELECT
• The Data Query Language (DQL) is used to retrieve the data from one or more tables.
• The SELECT statement is the only DQL statement.
• Using SELECT statement the following operation can be performed
• Projection : The operation results subset of columns
• Selection : The operation results subset of rows
Projection means selecting set of columns from a table. In the below table, 3 columns marked
with yellow colour suggesting that those columns are selected.
Selection means selecting set of rows from a table. In the below table, 3 rows marked with yellow
colour suggesting that those rows are selected.
A Typical SELECT statement may consists of six clauses.
Syntax:
SELECT column_name [, column_list]
FROM table_name
[WHERE search_condition]
[GROUP BY grouping_column_name]
[HAVING aggregated_search_condition]
[ORDER BY sorting_column]
1. The SELECT and FROM clauses of the statement are mandatory. The remaining four
clauses are optional.
Consider the following table
The above query displays only id, name and salary columns from customer_details
The above query displays name and age of customers whose salary more than 50000 From
customer_details table
The above query displays name and location of customers who are from Kolkata and Delhi
Restrict based on pattern matching:
The above query displays name and location of customers whose name's second character is a.
'_' identifies that one character can appear before 'a' and ' % ' identifies that any numbers of
character can appear after 'a'.
The above query displays name and location of customers whose age ranging from 20 to 40
Based on database configuration, NULL value may not display anything but it should not be
misunderstood as zero or blank space.
The above query displays name and age of customers whose location not specified
The above query displays name and age of customers whose age available
ORDER BY Clause
GROUP BY Clause
The GROUP BY statement is used to group the result-set by one or more columns.
The above query displays number of customers present in particular age group.
The concatenation( || ) operator can be used to combine character strings and values from table.
The Name, age and the strings are displayed as single output columns
Column Alias
Column heading in the result set can be changed with Column aliases using the keyword AS.
1. The columns name and id are displayed as customer_name and customer_id in the
result set.
Data Types
A data type identifies or classifies a particular type of information or data.
Some commonly used data types are:
• CHAR (size) - Used to store character strings values of fixed length.
• VARCHAR2 (size) – Used to store variable length string data.
• NUMBER (size, precision) – Used to store numbers(fixed or floating point)
• DATE – Used to represent date and time.
• LONG – Used to store large variable length strings(upto 2GB).
DDL statement: CREATE
The CREATE keyword is used for creating database objects like tables, views, triggers, and
indexes.
Syntax:
CREATE TABLE table_name
(
column_name1 DATATYPE(Size) ,
column_name2 DATATYPE(Size),
column_name3 DATATYPE(Size)
);
Ex: Create Table Employee
(
Emp_id number(4) NOT NULL,
Name varchar2(20) NOT NULL,
Salary number(8),
E_Mail varchar2(30),
Country varchar2(20),
);
Table created.
The above statement creates a table named Employee with columns Emp_id,
Name,Salary,E_Mail and Country.
The above statement adds a new column 'age' of number data type with constraint not null.
Modifying the column:
Ex: ALTER TABLE Employee MODIFY salary number(10,2);
Table Altered.
Rename and Drop a Column:
Using the alter statement we can rename a column and also the drop any column.
The above statements renames the column name salary to em_sal and drops column age.
Introduction
1. Data Manipulation Language(DML) is a structured query language which is used for
inserting, updating and deleting data in the database objects like table or view.
2. DML comprises the SQL change statements which modifies the stored data but not the
database object.
3. DML consist of three SQL statements namely-
• Insert
• Update
• Delete
INSERT statement
• Insert statement is used for inserting data into table.
• Insertion of data can be done in multiple ways.
Syntax:
INSERT INTO table_name[(column1, column2,...)]
VALUES(value1, value2,....);
Ex:
• If values in all the columns inserted in proper order, column names are not mandatory.
Syntax-:INSERT INTO table_name VALUES(value1, value2,....);
Ex:
UPDATE statement
• Update command is used to change or modify data of one or more records in a table.
Syntax:
UPDATE Table_name SET Column_name1=value1 [,Column_name2=value2,...]
[WHERE Condition];
Ex.
DELETE statement
1. Delete statement is used to remove one or more records from a table.
2. A subset may be defined for deletion using a condition, otherwise all records are
removed.
Syntax:
DELETE FROM Table_Name
[WHERE Condition];
Delete statement using WHERE condition.
Ex:
Note: Delete statement without where condition deletes all the rows from table.
Example-
Transaction Control Language (TCL)
Introduction to Transaction
Oracle server ensures data consistency based upon transactions.
Transactions consist of DML statements that make up one consistent change to the data.
Conversion Functions
• NVL
• NVL2
• NULLIF
NVL: let us replace null with a string in the results of a query .
Syntax : NVL( string1, replace_with).
If string1 is null, then NVL returns replace_with .
If string1 is not null, then NVL returns string1.
Ex: SELECT NVL(emp_name,'NA') FROM Employee;
The above query will display 'NA' wherever emp_name is null.
We can also replace with another column.
Ex: SELECT NVL(emp_name,dep_name) FROM Employee;
The emp_name and dep_name should belongs to same data type family.
The above query will display dep_name wherever emp_name is NULL.
Ex: SELECT NVL(salary,0) FROM Employee;
The above query returns 0 only if the salary is defined as NUMBER and is NULL.
NVL2: NVL2 function extends the functionality found in the NVL Function.
It lets you substitutes a value when a null value is encountered as well as when a non-null value
is encountered.
Syntax : NVL2(string1,value_if_not_null,value_if_null)
if string1 is not null then NVL2 returns value_if_not_null.
if string1 is null then NVL2 returns value_if_null.
Ex: SELECT NVL2(emp_name,dep_name,'NOT AVAILABLE') FROM Employee;
NULLIF: NULLIF compares expr1 and expr2. If they are equal, then the function returns null. If
they are not equal, then the function returns expr1 .
Syntax : NULLIF(expr1,expr2)
Ex: SELECT NULLIF( dep_name,'HR') FROM Employee;
The above query returns NULL if dep_name field consists of 'HR', otherwise it returns job.
You cannot specify the literal NULL for expr1.
Character Functions
There are two types of character functions.
Character to character functions accept string as input and will give string as output.
• INITCAP
• LOWER
• UPPER
• CONCAT
• LPAD,RPAD
• TRIM
• SUBSTR
• REPLACE
Character to number functions accept string as input and will give number as output.
• LENGTH
• INSTR
INITCAP: This function sets the first character in each word to upper case and the rest to lower
case.
Syntax : INITCAP(expr1)
Ex: SELECT INITCAP(emp_name) FROM Employee:
Amit
Ajay
Sima
Dipa
Anuj
The above query returns all the employee names with the first letter in upper case and rest other
characters in lower case.
LOWER: This function converts all letters in the specified string to lower case. If there are
characters in the string that are not letters, they are unaffected by this function.
Syntax : LOWER(expr1)
Ex: SELECT LOWER (emp_name) FROM employee:
amit
ajay
sima
dipa
anuj
The above query returns all the characters of the employee name in lower case.
UPPER:This function converts all letters in the specified string to uppercase. If there are
characters in the string that are not letters, they are unaffected by this function.
Syntax : UPPER(expr1)
Ex: SELECT UPPER (emp_name) FROM Employee:
AMIT
AJAY
SIMA
DIPA
ANUJ
The above query returns all the characters of the employee name in upper case.
CONCAT: This function allows you to concatenate two strings together.
Syntax : CONCAT(expr1,expr2)
Ex: SELECT CONCAT(emp_name,dep_name) full_name FROM Employee;
The above query returns the emp_name & dep_name concatenated into a single string.
SUBSTR: Returns specified characters from a string, starting from specific position to required
characters length.
Syntax : SUBSTR(col/expr,m,n)
If 'm' is positive,oracle counts from beginning of string, If it is negative Oracle counts from the end
of string.
If 'n' is omitted, Oracle returns all characters to end of the string starting from m.
Ex: SELECT SUBSTR(emp_name,3,2) FROM Employee.
The above query starts searching from the third position of the employee name from the starting
of the string and displays two characters from there.
Ex: SELECT SUBSTR('abcdefg'-4,2) FROM dual;
dc
The above query starts searching from the fourth position of the given string from the end of the
string and display two characters from there.
REPLACE: It returns the every occurrence of search_string replaced by the
replacement_string.
If the replacement string is omitted or null all occurrences of search string will be removed.
Syntax : REPLACE(string,search_string,replace_string)
Ex: SELECT REPLACE(branch_name,'Mumbai','Kolkata') FROM Employee WHERE
dep_name = 'HR';
The above query replaces branch name to 'Kolkata' wherever 'Mumbai' is available for the HR
department .
LPAD,RPAD:
LPAD pads the character value right justified to a total width of n character positions.
Syntax : LPAD(expr1,padded_length,padded_string)
RPAD pads the character value left justified to a total width of n character positions.
Syntax : RPAD(expr1,padded_length,padded_string)
The default padding character is space.
Ex: SELECT LPAD('jhon',8) FROM dual;
jhon
Since the third parameter is not specified in the result of the above query will be by default space
padded for the previous four positions.
Ex2: SELECT LPAD('jhon',8 ,'x') FROM dual;
xxxxjhon
The above query fills the four blank spaces with 'x' left of the given string.
Ex3: SELECT RPAD('jhon',8 ,'x') FROM dual;
jhonxxxx
The above query fills the four blank spaces with 'x' right of the given string.
TRIM: It enables to trim leading or trailing characters or both from a string.
If we don’t specify anything, it will trim spaces.
Syntax : TRIM( [LEADING | TRAILING | BOTH] character FROM string)
LTRIM : Removes the leading characters
RTRIM : Removes the trailing characters
TRIM : Removes both
Ex: SELECT RTRIM('s' from 'ssmithss') FROM dual;
ssmith
The above query removes 'trailing' 's' from the given string.
Ex: SELECT LTRIM('s' from 'ssmithss') FROM dual;
mithss
The above query removes 'leading' 's' from the given string.
Ex: SELECT TRIM('s' from 'ssmiths') FROM dual;
mith
The above query removes 'trailing' & 'leading' 's' from the given string.
Ex: SELECT TRIM(' smith ') FROM dual;
Smith
The above query removes 'trailing' & 'leading' spaces from the given string.
INSTR: This function returns the location of a sub string in a given string.
Syntax : INSTR( string, sub_string [, start_position [, nth_appearance ] ] ).
start_position and nth_appearance are optional. If not specified, always INSTR starts with first
position and will give first appearance.
Ex: SELECT INSTR('internet','e') FROM dual;
4
The above query returns the first position of 'e' searched from the start of the given string.
Ex: SELECT INSTR('internet','e',1,2) FROM dual;
7
The above query returns the second position of 'e' searched from the start of the given string.
Ex: SELECT INSTR('internet','e',5,1) FROM dual;
3
The above query returns the first position of 'e' searched from the fifth position of the given string.
LENGTH: Returns number of characters in a value.
Syntax : LENGTH(column)
Ex: SELECT LENGTH(branch_name) FROM Employee;
The above query returns number characters in the branch_name field for each and every record.
Ex: SELECT LENGTH('jhon') FROM dual;
4
The above query returns the number of characters from the given string.
Numeric Functions & Dual table
Dual table
1. This is a single row and single column dummy table provided by oracle. This is used to
perform mathematical calculations without using a table.
2. Oracle presents the output of every operations in a tabular format so that it seems to the
user that the output comes from a table
ABS and MOD Function
The ABS function returns the absolute value of the parameter passed.
Syntax : ABS(number)
Ex: SELECT ABS(-10) FROM dual;
10
The above query returns the absolute value of the given 'number'.
The MOD function returns the remainder value of the parameter passed.
Syntax : MOD(number1,number2)
Ex: SELECT MOD(10,4) FROM dual;
2
The above query returns the remainder when 10 is divided by 4.
GROUP BY clause
Creates a data set, containing several sets of records grouped together based on a condition.
Syntax: SELECT <columnName1>[,<columnName2>], AGGREGATE
FUNCTION(<expression>) FROM Table_Name GROUP BY
<columnName1>[,<columName2>] ;
Ex: SELECT dep_name,COUNT(emp_id) "No of Employee" FROM Employee GROUP BY
dep_name;
HR 2
Marketing 2
Admin 1
The above query displays the number of employee in each department.
WHERE clause
Used to apply a filter condition before the Grouping the rows.
Syntax: SELECT <columnName1>[,<columnName2>], AGGREGATE
FUNCTION(<expression>) FROM Table_Name WHERE
<condition_before_grouping_rows> GROUP BY <columnName1>[,<columName2>] ;
Ex: SELECT Dep_Name,COUNT(Salary) FROM Employee WHERE Salary>15000 GROUP BY
Dep_Name;
HR 1
Marketing 1
Admin 1
The above query displays department wise count of salary more than 15000.
HAVING clause
Used to apply a filter condition on Aggregate values.
Syntax: SELECT <columnName1>[,<columnName2>], AGGREGATE
FUNCTION(<expression>) FROM Table_Name WHERE
<condition_before_grouping_rows> GROUP BY <columnName1>[,<columName2>]
HAVING <condition_on_grouped_result>;
Ex: SELECT Dep_Name, SUM(Salary) FROM Employee WHERE Salary>12000
GROUP BY Dep_Name HAVING SUM(Salary)<30000;
HR 16000
Marketing 20000
The above query displays the departments for which total salary is less 30000 excluding the
Admin department, total salary for which is 40000.
1.2. Connecting to Oracle
After successful login to putty, one can connect to oracle schema from any directory. For
example, in the below screen shot the user has connected to oracle schema from his “home”
directory.
Note:
-To avoid confusion better to input username and password in lowercase.
-Here, “pj01fac01” is username, “unixdb” is db name and “tcshyd” is password
-While connecting to oracle schema, one has to provide the schema details which are assigned
to them
For clearing the screen, we can use “cl scr” command at SQL prompt SQL> cl scr (Note: “cl” and
“scr” are two words separated by space) Or clear Screen can be used.
To switch from one user to another user, use “connect” command
To execute UNIX commands, use “!” before the command as shown below
Note : By using only !, you can go to unix shell prompt. To be back to oracle, exit is the
command.
We can also use “vi” editor for preparing the “.sql” files and editing SQL queries.
To view the buffer content use “L[IST]” Command at SQL prompt.
The last SQL query which is executed at SQL prompt will get store in buffer. i. To view the buffer
content use “L[IST]” Command at SQL prompt.
To edit the buffer content, use “E[DIT]” command at SQL prompt. Edit the content in insert mode
then save and quit from the editor by using “:wq” command in escape mode. iii. To execute the
buffer content use “/” or “R[UN]” command at SQL prompt.
To disconnect from SQL, use “exit” command as shown below
1.3. ER Diagrams
1.1 Objective
• Introduction
• Basic ER constructs
• Entity and entity types
• Relationship and relationship types
• Attribute and attribute types
• Cardinalities
1.2 Course Content
1.2.1 Introduction
Entity Relationship (ER) model proposed by Peter Chen in 1976 is a conceptual representation
of data. It is capable of describing the data requirements for a new information system in a direct
and easy to understand graphical notation. ER data model represents the overall logical structure
of the DB. ER diagram is a graphical representation of the logical structure of a database.
1.2.2 Basic ER constructs
The ER model is designed with the help of the below basic constructs:
• Entity
• Attribute
• Relationship
1.2.3 Entity and entity types
An entity is an instance of a physical object in the real world.
Represents the real world objects (eg., facts , things , people.,,,etc) that have properties in
common.
It is an object that exists and is distinguishable from other objects.
An entity may be
• concrete (eg., person,book, employee etc...)
• moderate (eg., holiday,disease etc...)
Entities have attributes.
Graphically an entity is represented by a rectangle.
A relationship can
a) recursive
b) binary
c) ternary
d) have attributes
1.2.4.1 Recursive relationship
A recursive relationship is the one which involves only one single entity.
The above representation specifies that 'books' are available in the 'library'.
1.2.4.3 Ternary Relationship
A relationship which involves three entities.
1.2.6 Cardinalities
These are specified for each entity participating in a relationship and describes the number of
relationship occurrences in which an entity occurrence can participate.
States how many times can an entity instance participate in instances of a given relationship.
4 types of cardinalities can be maintained:
a) 1 : 1 ( ONE to ONE )
Ex
The above representation indicates “one employee belongs to only one department”.
b) 1 : * ( ONE to MANY )
Ex:
The above representation indicates “One bank deals with many customers”.
c) * : 1 ( MANY to ONE )
Ex:
d) * : * ( MANY to MANY )
Ex
In the first table student id is primary key where as in second table the combination of student id
and unit code is defined as primary key.
Second Normal Form:
As shown above still in second table, we can see that data is repeating in first two columns
because of third column.
We can avoid this by subdividing into two tables using second normal form.
The above query returns 4 records which are nothing but the employees details who are working
along with RAJU in the same department.
Ex:
SELECT * FROM employee WHERE salary >
(SELECT salary FROM employee WHERE name='RAJU');
The above query returns 3 records which are nothing but the employee details who are earning
more than RAJU.
1.2.4.1 Group functions in sub query
Group functions can be used in the inner query and in turn the result is sent to the outer query to
display the matching values. When performing this logic GROUP BY clause should not be
available in the inner query.
Ex:
SELECT * FROM employee WHERE salary =
(SELECT MAX(salary) FROM employee);
The above query displays the details of those department numbers whose minimum salary is
more than the minimum salaried employee who is belonging to the department number 103.
1.2.4.3 Usage of joins
Ex:
SELECT e.* FROM employee e,grade g
WHERE did =
(SELECT did FROM employee WHERE name='SANTOSH')
AND g.grade='B' AND e.salary BETWEEN g.losal AND g.hisal;
The above displays the details of those employees who belongs to the SANTOSH department
and are falling in the salary range of grade 'B'.
1.2.5 Multi row sub query
Multi row sub queries are the queries which returns more than one row from the Inner SELECT
statement.
The operators that can be used :
IN ANY ALL
1.2.5.1 Usage of IN operator
IN → Matches with each and every values returned by the inner query.
Ex:
SELECT * FROM employee WHERE designation IN
(SELECT designation from employee e,department d
WHERE e.did=d.did AND d.deptname='PRODUCTION');
The inner query will return the different designated employee details who are working in the
PRODUCTION department. Since the inner query is returning more than one record, IN operator
is used to link between outer and inner query. Finally the outer query will retrieve all the records
whose designations are matching with the designations of PRODUCTION department.
Ex:
SELECT * FROM employee WHERE salary IN
(SELECT MAX(salary) FROM employee GROUP BY designation);
The above query displays the records of all the employees who are earning maximum salary for
each designation group.
1.2.5.2 Usage of ANY operator
ANY → Compares values to each value returned by the sub query.
<ANY → Less than the maximum value in the list
>ANY → More than the minimum value in the list
Ex:
SELECT * FROM employee WHERE salary >ANY
(SELECT salary FROM employee WHERE did=102)
AND did!=102;
The above query displays the details of those employees who are earning more than the
minimum salaried employee belonging to department number 102.
Ex:
SELECT * FROM employee WHERE salary <ANY
(SELECT salary FROM employee WHERE did=102)
AND did!=102;
The above query displays the details of those employees who are earning less than the
maximum salaried employee belonging to department number 102.
1.2.5.3 Usage of ALL operator
ALL → Compares values to every value returned by the sub query.
< ALL → Less than the minimum value in the list
> ALL → More than the maximum value in the list
Ex:
SELECT * FROM employee WHERE salary >ALL
(SELECT salary FROM employee WHERE designation='SENIOR PROGRAMMER');
The above query displays the details of those employees who are earning more than the
maximum salaried employee who is a SENIO PROGRAMMER.
Ex:
SELECT * FROM employee WHERE salary <ALL
(SELECT salary FROM employee WHERE designation='SENIOR PROGRAMMER');
The above query displays the details of those employees who are earning less than the minimum
salaried employee who is a SENIO PROGRAMMER.
1.2.6 Multi column sub query
Multi column sub queries are the sub queries which returns more than one column from the Inner
SELECT statement.
Ex:
SELECT * FROM employee WHERE (did,salary) IN
(SELECT did,salary FROM employee WHERE designation='EXECUTIVE')
AND designation!='EXECUTIVE;
The above query displays the details of those employees who belong to the same department
and earning the same salary as of the EXECUTIVE designated employees.
The same logic can even be written in the below format:
SELECT * FROM employee WHERE did IN
(SELECT did FROM employee WHERE designation='EXECUTIVE')
AND salary IN
(SELECT salary FROM employee WHERE designation='EXECUTIVE')
AND designation!='EXECUTIVE;
1.2.7 Co-related sub query
It is another way of performing queries upon the data with a simulation of joins. In this the
information from the Outer SELECT statement participate as a condition in the Inner SELECT
statement.
Syntax:
SELECT select_list FROM table_name alias1
WHERE operator
(SELECT column FROM table_name alias2
WHERE alias1.column=alias2.column);
Ex:
SELECT * FROM employee e1 WHERE salary =
(SELECT MIN(salary) FROM employee e2
WHERE e1.designation=e2.designation);
The above query displays the records of all the employees who are earning minimum salary for
each designation group.
1.2.7.1 Order of Precedence
• First the Outer query is executed.
• Passes the executed column value to the Inner queries WHERE clause.
• Now the Inner query is executed.
• The result of the Inner query is passed to the Outer queries WHERE clause.
• Depending on the provided value the condition is qualified for the specific record.
• If successful displays the output.
1.2.8 Sub queries in DML statements
Sub queries can be used in DML statements UPDATE & DELETE.
Ex:
UPDATE employee
SET did=(SELECT did FROM employee WHERE did='PURCHASE')
WHERE did=(SELECT did FROM employee WHERE did='SALES');
The above queries updates the department numbers of those employees who are belonging to
SALES department to PURCHASE department.
Ex:
DELETE FROM employee WHERE salary >
(SELECT AVG(salary) FROM employee);
The above query deletes all the records from the employee table whose salary is more than the
average salary of all the employees in the organization.
1.2.9 Sub queries with CREATE & INSERT statements
Sub queries can be used with CREATE statement as well.
Syntax:
CREATE TABLE table_name2 AS
SELECT * FROM table_name1;
Ex:
CREATE TABLE employee_bkp AS
SELECT name,designation FROM employee WHERE 1=2;
The above query creates an empty backup table to store only name and designations.
Sub queries can also be used with INSERT statement as well.
Syntax:
INSERT INTO table_name2
SELECT * FROM table_name1;
Ex:
INSERT INTO employee_bkp
SELECT name,designation FROM employee
WHERE did IN (101,103);
2.2. Joins
1.1 Objective
• Introduction
• Different SQL Joins
• Guidelines
• Cross Join
• Inner Join
• Outer Join
• Self Join
1.2 Course Content
1.2.1 Introduction
Join achieves the goal of creating a single SQL sentence that can manipulate data from two or
more tables.
A join is a query that combines rows from two or more tables.
A join is performed whenever multiple tables appear in the queries FROM clause.
The queries SELECT statement can select any of the columns from any of these tables.
1.2.2 Different SQL joins
There are four different types of joins:
• CROSS JOIN
• INNER JOIN
? EQUI JOIN
? NON EQUI JOIN
• OUTER JOIN
? LEFT OUTER JOIN
? RIGHT OUTER JOIN
? FULL OUTER JOIN
• SELF JOIN
1.2.3 Guidelines
When writing a SELECT statement that joins tables , precede the column name with the table
name.
If the same column name appears in more than one table, the column name must be prefixed
with the table name.
To join 'N' tables , a minimum of 'N-1' join conditions are required.
Consider the below tables:
1.2.4 Cross Join
The Cross join / Cartesian product is a join query , that does not contain a join condition. Oracle
combines each row of one table with each row of the other.
Syntax: SELECT * FROM tableA , tableB;
Ex: SELECT * FROM department,grade;
The above query returns 20 records. As per the department table DID 101 must appear only
once , but each row of department table is linked with each and every row of grade table , 101 is
appearing 4 times in the resultant set.
1.2.5 Inner Join
An inner is used when the join fields are guaranteed not to be NULL.
1.2.5.1 Equi Join
It is a join condition containing an equality operator ( = ). This join condition combines the rows
that have the same values for the specified columns.
Syntax : SELECT tableA.col1,tableA.col2,tableB.col1,..... FROM tableA,tableB WHERE
tableA.col1 = tableB.col1;
Ex: SELECT employee.eno “ENO” , employee.name “NAME”, employee.salary “SALARY”,
department.did “DID”, department.deptname “DEPTNAME” FROM employee,department
WHERE employee.did = department.did;
The above query returns all the rows that are matching with the join condition , i.e., the rows from
both the tables where DID is matching.
The above query can also be given with the alias names provided to the table names. Alias
names can be used wherever the table names are required.
Ex: SELECT e.eno, e.name, e.salary, d.did, d.deptname FROM employee e , department d
WHERE e.did = d.did;
1.2.5.2 Non Equi Join
It is a join condition that is executed when no column in one table is directly linked with a column
in another table. The data in the tables are logically related through appropriate values.
Syntax : SELECT tableA.col1,tableA.col2,tableB.col1,..... FROM tableA,tableB WHERE
tableA.col1 BETWEEN tableB.col2 AND tableB.col3;
Ex: SELECT eno,name,salary,grade FROM employee e,grade g WHERE e.salary BETWEEN
g.losal AND g.hisal;
The above query retrieves the employee details along with his salary grade based on the join
condition.
1.2.6 Outer Join
Outer join extends the result of Equi join. Outer join returns all the rows from both the tables that
satisfy the join condition and also the rows from one table which do not satisfy the join condition.
The Outer join operator is ( + ) , which is used on one side of the join condition.
1.2.6.1 Left Outer Join
It is a join which returns all the rows from the left hand side of the table specified at the join
condition and only those rows from the other table which are matching with the join condition.
Syntax : SELECT tableA.col1,tableA.col2,tableB.col1,..... FROM tableA,tableB WHERE
tableA.col1 = tableB.col1(+);
Ex: SELECT e.eno “ENO”, e.name “NAME”, e.salary “SALARY”, e.did “DEPTNO”,d.did
“DEPTID” , d.deptname “DEPTNAME” FROM employee e ,department d WHERE e.did =
d.did(+);
The above query displays all the records which are matching with the join condition from both the
tables along with the rows from employee table which are not matched with department table.
1.2.6.2 Right Outer Join
It is a join which returns all the rows from the right hand side of the table specified at the join
condition and only those rows from the other table which are matching with the join condition.
Syntax : SELECT tableA.col1,tableA.col2,tableB.col1,..... FROM tableA,tableB WHERE
tableA.col1(+) = tableB.col1;
Ex: SELECT e.eno “ENO”, e.name “NAME”, e.salary “SALARY”, e.did “DEPTNO”,d.did
“DEPTID” , d.deptname “DEPTNAME” FROM employee e ,department d WHERE e.did(+) =
d.did;
The above query displays all the records which are matching with the join condition from both the
tables along with the rows from department table which are not matched with employee table.
1.2.6.3 Full Outer Join
It is a join which returns all the rows from both the tables which are placed on either side of the
join condition.
Syntax : SELECT tableA.col1,tableA.col2,tableB.col1,..... FROM tableA,tableB WHERE
tableA.col1 = tableB.col1(+)
UNION
Syntax : SELECT tableA.col1,tableA.col2,tableB.col1,..... FROM tableA,tableB WHERE
tableA.col1(+) = tableB.col1;
Ex: SELECT e.eno “ENO”, e.name “NAME”, e.salary “SALARY”, e.did “DEPTNO”,d.did
“DEPTID” , d.deptname “DEPTNAME” FROM employee e ,department d WHERE e.did =
d.did(+)
UNION
SELECT e.eno “ENO”, e.name “NAME”, e.salary “SALARY”, e.did “DEPTNO”,d.did “DEPTID” ,
d.deptname “DEPTNAME” FROM employee e ,department d WHERE e.did(+) = d.did;
The above query displays all the records which are matching with the join condition from both the
tables along with the rows from both employee and department table which are not matched..
1.2.7 Self Join
It is a join used to join a table to itself. The table is logically considered as two tables and joined
to itself.
Syntax : SELECT A.* FROM tableA A,tableB B WHERE A.col1 = B.col1 AND condition;
Ex: SELECT e1.* FROM employee e1,employee e2 WHERE e2.name='SRIDHAR' AND
e1.did=e2.did;
The above query is going to display the details of all those employees who are working in the
same department of "SRIDHAR".
3.1. View and Synonyms
Synonym
1.1 Objective
• Introduction
• Purpose
• Prerequisites
• Syntax
• Resolution of Synonyms
1.2 Course Content
1.2.1 Introduction
• A synonym basically allows you to create a pointer to an object like
table,procedure,package,index,view that exists somewhere else.
• Synonyms provide both data independence and location transparency.
• Synonyms permit applications to function without modification regardless of which user
owns the table or view and regardless of which database holds the table or view.
1.2.2 Purpose
For example assume that , in our database we have two schemas SCOTT and TIGER.
Schema is collection of different database objects like
tables,views,procedures,functions,packages and indexes belonging to same application.
We can create more than one schema for an application and more than one schema in a
database.
If you login to scott schema and want to access the table employee, you can query as
follows.
select * from employee;
But, you want to see the employee table details residing in TIGER, you have to query as
follows.
select * from tiger.employee;
As shown above , we have to specify the schema name to access the other schema objects.
It would be a bit of a pain to have to always prefix all sql calls to the other schema objects with
schema name.
We can create and use synonyms for above scenario to make sql calls simpler.
We can create two types of synonyms,Private synonyms which can be accessible only to that
schema that owns it.
Other type is Public synonyms, which can be referred by multiple schema.
1.2.3 Prerequisites
• To create a private synonym in your own schema, you must have the CREATE SYNONYM
system privilege.
• To create a private synonym in another user's schema, you must have the CREATE ANY
SYNONYM system privilege.
• To create a PUBLIC synonym, you must have the CREATE PUBLIC SYNONYM system
privilege.
• To use the database object, you should have necessary privileges
(SELECT,INSERT,DELETE) on the base objects in the owner schema.
1.2.4 Syntax
CREATE <public/private> SYNONYM <synonym_name> FOR
schema_name.object_name.
Ex1: CREATE public SYNONYM emp_syn FOR tiger.employee.
Ex2: CREATE SYNONYM dept_syn FOR tiger.department.
Synonym can be created for any DB Object like table, view, index, synonym, stored function or
procedure.
If you are not specifying Public or Private in Synonym declaration,private synonym will be
created.
Private synonym means, we can use synonym in only the schema where we created it only.
Public synonyms can be used across the schemas.
Because of security and performance issues private synonyms are more preferable than
public synonyms.
We can drop the synonym using below mentioned syntax.
Syntax: DROP SYNONYM <synonym_name>
Ex: DROP SYNONYM dept_syn;
DROP PUBLIC SYNONYM emp_syn;
Synonyms will not be dropped on dropping of base objects.
1.2.5 Resolution of Synonyms
• Local objects will always be accessed first on issuing query statement.
• If a local object does not exist, the object with a private synonym will be accessed.
• If a private synonym does not exist or the object does not exist, then the public synonym will
be used.
Views
Objective
• Introduction to View
• Purpose
• Prerequisites
• Types of views
• Additional View types
2.2 Course Content
2.2.1 Introduction to View
• A view is a predefined, named query stored in the database.
• Once created, views can be queried in much the same way that tables can be queried .
• Views are not tables but representations of data stored in, or calculated from, one or more
other tables (business tables) or views .
• The columns of the view are the items from the select list of the query that defines the view.
2.2.2 Purpose
• Views are useful for security and information hiding.
• Reduce the complexity of SQL statements.
• Share only specific rows and columns in a table with other users
• Hide the NAME and OWNER of the base table
• Improve the query performance by storing the execution plan(execution plan will be
discussed in detail in later courses) in data dictionary.
2.2.3 Prerequisites
To create a view in your own schema, you must have the CREATE VIEW system privilege
To create a view in another user's schema, you must have the CREATE ANY VIEW system
privilege.
You can grant users access rights (such as SELECT and INSERT) to views in the same way as
to tables that it seems to the user that the output comes from a table
2.2.4 Types of Views
Basically views can be classified as two types. One as simple views and another as complex
views.
Simple views
Simple views are the views defined on single table.
One can perform DML operations directly against simple views.
These DML changes are then applied to the view's base table.
Ex:
CREATE VIEW v_emp AS
SELECT * FROM employee;
CREATE VIEW v_dept AS
SELECT ename,sal*12 annual_sal FROM employee
WHERE dep_name= 'HR';
Complex views
Complex views can be constructed on more than one base table.
In particular, complex views can contain:
• join conditions
• a group by clause
• a order by clause
One cannot perform DML operations against complex views directly.
DML Operations cant be performed directly on complex views.
We should use instead of triggers(we will discuss about instead of triggers in later courses) to
perform DML operations.
Ex:
CREATE VIEW v_complex1 AS
SELECT emp.empno, emp.ename, emp.job, emp.deptno, dept.dname, dept.loc FROM
empLOYEE, dept;
CREATE VIEW v_complex2 AS
SELECT emp.empno, emp.ename, emp.job, emp.deptno, dept.dname, dept.loc FROM
emp, dept
WHERE emp.deptno = dept.deptno;
2.2.5 Additional View Types
Read-only views
• Users can only run SELECT and DESCRIBE statements against read only views.
• DML operations are not allowed against read only views.
Ex:
READ ONLY clause on a simple view:
If we want to start the sequence with new value, then old sequence needs to be dropped and
recreated with new start value.
If we create an index on a column, each value of the column along with row id will be stored as
separate database object.
When we fire a query to fetch the data using this column in where clause, then the oracle engine
will scan the index instead of entire table and will get the other column values using row id.
Row id is a Pseudo column used by Oracle to locate a row in database.
Syntax:
CREATE BITMAP INDEX <INDEX_NAME> ON
TABLE_NAME(COLUMN_NAME)
Example:
CREATE BITMAP INDEX test_idx on employee(gender);
3.2.7 Function Based Index
Consider we have created index on product name in products table.
SELECT * FROM products WHERE upper(product_name) = 'APPLE';
Though we are having index on product name, oracle will do full table scan on products table as
we used function in the where clause.
In the above scenarios, to enable oracle to consider index on product name we can create
function based index as shown below.
CREATE INDEX product_idx ON products(UPPER(product_name));
3.2.8 Renaming And Dropping Index
The index can be renamed using the following command.
ALTER INDEX index_name RENAME TO new_index_name;
The index can be dropped using the following command.
DROP INDEX index_name;
If the base table is dropped, all the indexes defined on the table will be dropped.
4. DATA DICTIONARY
4.1 Objective
• Introduction
• Structure Of Data Dictionary
• Data Dictionary Types
4.2 Course Content
4.2.1 Introduction
One of the most important parts of an Oracle database is its data dictionary, which is a read-only
set of tables that provides information about the database.
A data dictionary contains:
•The definitions of all schema objects in the database (tables, views, indexes, clusters,
synonyms, sequences, procedures, functions, packages, triggers, and so on)
•How much space has been allocated for, and is currently used by, the schema objects
•Default values for columns
•Integrity constraint information
•The names of Oracle users
•Privileges and roles each user has been granted
•Auditing information, such as who has accessed or updated various schema objects
•Other general database information
The data dictionary is collection of tables and views On which users will have read only access.
All the data dictionary tables and views for a given database are stored in that database's
SYSTEM table space.
Not only is the data dictionary central to every Oracle database, it is an important tool for all
users, from end users to application designers and database administrators.
Use SQL statements to access the data dictionary. Because the data dictionary is read-only, you
can issue only queries (SELECT statements) against it's tables and views.
4.2.2 Structure of the Data Dictionary
The data dictionary consists of the following:
Base Tables
The underlying tables that store information about the associated database. Only Oracle should
write to and read these tables.
Users rarely access them directly because they are normalized, and most of the data is stored in
a encrypted format.
User-Accessible Views
The views that summarize and display the information stored in the base tables of the data
dictionary.
These views decode the base table data into useful information, such as user or table names,
using joins and WHERE clauses to simplify the information.
Most users are given access to the views rather than the base tables.
SYS, Owner of the Data Dictionary
The Oracle user SYS owns all base tables and user-accessible views of the data dictionary.
No Oracle user should ever alter (UPDATE, DELETE, or INSERT) any rows or schema objects
contained in the SYS schema, because such activity can compromise data integrity.
The security administrator must keep strict control of this central account.
4.2.3 Data Dictionary Types
We have three types of data dictionary objects in oracle.
USER - User's view (what is in the user's schema) -user owned objects
ALL - Expanded user's view (what the user can access)
DBA - Database administrator's view (what is in all users' schemas)
Sample Data Dictionary Objects:
ALL_CONS_COLUMNS : Stores information about all columns having constraints that user
can access.
ALL_CONSTRAINTS : Stores information about all constraints that user can access.
ALL_IND_COLUMNS : Stores information about all columns having indexes that user can
access.
ALL_INDEXES : Stores information about all indexes that user can access.
ALL_TAB_COLUMNS : Stores information about all columns
ALL_TABLES : Stores information about all tables
ALL_TRIGGERS : Stores information about all triggers
ALL_VIEWS:Stores information about all views
USER_SOURCE: Stores the information of stored pl/sql blocks code.
3.3. SQL Loader
SQL *LOADER
1.1 Objective
• Introduction
• SQL *LOADER Components
• SQL *LOADER Control File Examples
1.2 Course Content
1.2.1 Introduction
Utility that loads data from flat files into one or more tables in the database.
Manipulate data fields with SQL functions before inserting data into database columns.
Loading errors will be reported.
The data can be loaded into table by reading multiple files.
The data can be loaded into multiple tables also.
1.2.2 SQL *LOADER Components
As shown in the above figure, SQL *LOADER read the data from data files using loader control
file.
If it encounters any wrong data the wrong data will be discarded and captured as bad data.
If no errors, then the data will be loaded successfully to database and will create a log file with
the information of about the number of records loaded and at which time the data is loaded.
Control File:
Control files are very important component in SQL *LOADER.
The Control file contains information that describes from where we have to load the data, to
which table we need to load the data, to which columns we need to load the data and how the
data fields are separated in the files.
Sample control file:
in file we need tp specify the file name along with the path of the file.
load data
infile '/home/u495298/employee.txt'
into table employee
fields terminated by ","
( id, name, dept, salary )
Data Files:
Data files are the files that contain the data that is to be loaded to oracle database.
The files can be fixed record format file,variable record format file.
The files also can have different fields separated by space or comma or any other delimiter.
Bad File:
Bad file contains records rejected by SQL*Loader or by Oracle.
Records are rejected by SQL*Loader when the input format is invalid
If Oracle determines that the row is valid, then the row is inserted into the database. If not, the
record is rejected and SQL*Loader puts it into the bad file
Discard File:
The discard file contains records that were filtered out of the load because they did not match
any record selection criteria specified in the control file
SQLLDR:
One can load data into an Oracle database by using the sqlldr (sqlload on some platforms)
utility
sqlldr username@server/password control=loader.ctl
Example:
Example:
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;
/NT
1.2.4 Explicit Cursors
Explicit cursors are programmer defined cursors for gaining more control over the context area.
An explicit cursor should be defined in the declaration section of the PL/SQL Block.
It is created on a SELECT Statement which returns more than one row. O Explicit Cursors
are used in PL/SQL where we have a Select statement that returns multiple rows.
The set of rows returned by a multiple row query is called the Active Set.
The size of the active set meets the search criteria in the select statement.
1.2.5 Explicit Cursor Functions
Can do a row-by-row processing beyond the first row returned by a query.
• Keep track of which row is currently being processed.
• Enable the programmer to manually control explicit cursors in “PL/SQL block.
All the cursor attributes that we learns in case of implicit cursors will work on explicit cursors also
in the same manner.
1.2.6 Controlling Explicit cursors
Declare a Cursor
In the declarative section of PL/SQL block,declare the cursor by naming it and defining the
structure of Query to be associated with it.
Open the Cursor
Open statement executes the query and binds any variables that are referenced.
Fetch data from the Cursor
After each row fetched,we need to test for any other existing rows. If there are no more rows to
process then cursor needs to be closed.
Close the Cursor
This statement releases the active set of rows.
Structure of a Cursor
DECLARE
CURSOR <cursor_name> IS <select_statement>;
<variable declarations>
BEGIN
OPEN <cursor_name>;
LoopFETCH <cursor_name> INTO <variable>;
Executable statements;
End Loop;
CLOSE <cursor_name>;
END;
Declaring the Cursor -
Active set of cursor is determined by the Select statement in the Cursor Declaration.
If processing rows in a specific sequence is required,use the Order by clause in the Select
statement.
Opening the Cursor -
The Open statement executes the query associated with the cursor,identifies the active set and
positions the cursor pointer at the first row.
The Open statement is included in the executable section of PL/SQL block.
Open statement performs the following operations -
Dynamically allocates memory for a context area.
Identifies the active set.
Rows in the active set are not retrieved into variables when the Open statement is executed.
Fetch statement retrieves the rows from the cursor to the variables
Fetching Data from the Cursor -
The Fetch statement retrieves the rows from the cursor one at a time.
Advances the pointer to the next row in the active set.
Include the same number of variables in the INTO clause of Fetch Statement.
Closing the cursor -
Close statement disables the cursor,releases the context area and undefines the active set.
Example for Cursor
DECLARE
CURSOR c1 IS select * from employee;
c employee%rowtype;
BEGIN
OPEN c1;
Loop
FETCH c1 into c;
Exit when c1%notfound;
dbms_output.put_line('Employee Number: '||c.eno);
dbms_output.put_line('Employee Name: '||c.ename);
End Loop;
CLOSE c1;
END;
1.2.7 Cursor FOR Loops
• The Cursor FOR Loop is a shortcut to process explicit cursors.
• Implicit Open,Fetch,Exit and Close Occur.
• Record is implicitly declared.
Syntax
For record_name IN cursor_name Loop
Statement 1;
Statement 2;
…..
End Loop;
record_name - Name of the implicitly declared Record
cursor_name – Is a pl/sql identifier for the previously declared cursor.
Example:
BEGIN
FOR c1 in ( select * from employee)
LOOP
dbms_output.put_line('Employee Number: '||c1.eno);
dbms_output.put_line('Employee Name: '||c1.ename);
End Loop;
END;
1.2.8 Parameterized Cursor
We can send any number of parameters to cursors. Supplying a value to the query dynamically
in the where condition is cursor Parameter.
Declaring a Parameterized Cursor
CURSOR <cursor_name>(<variable_name datatype) IS <select_statement>;
Opening a Parameterized Cursor
OPEN <cursor_name>(Value/Variable/Expression);
Example:or F
DECLARE
CURSOR c1 (p_dept_id) IS select * from employee where deptno = p_deptid;
c employee%rowtype;
v_dept_id number;
BEGIN
v_dept_id :=20;
OPEN c1(v_dept_id);
Loop
FETCH c1 into c;
Exit when c1%notfound;
dbms_output.put_line('Employee Number: '||c.eno);
dbms_output.put_line('Employee Name: '||c.ename);
End Loop;
CLOSE c1;
END;OR L
4.4. Exception Handling
1.1 Objective
• Introduction
• Types Of Exceptions
• Named System Exceptions
• Unnamed System Exceptions
• User defined Exceptions
• RAISE_APPLICATION_ERROR
1.2 Course Content
1.2.1 Introduction
An error condition during an execution is called exception
An exception can be any of the following
• An error generated by the system
• An error caused by the user action
• A warning issued by the application to the user
•
PL/SQL traps and responds to errors using an architecture of exception handlers.
The exception handler mechanism allows to clearly separate error processing code from
executable statements
Using Exception Handling testing can be done on the code in order to avoid it from exiting
abruptly
When an exception occurs, a message which explains its cause is received
PL/SQL exception consists of three parts
• Type of exception
• Error Code
• Error Message
1.2.2 Types Of Exceptions
There are two types of exception
• System defined / Predefined exceptions
Named Exception, Unnamed Exceptions
• User defined exceptions
Basic Exception Block:
EXCEPTION
WHEN <exception_name> THEN
statements
RAISE_APPLICATION_ERROR (err_code,err_msg);
WHEN <exception_name> THEN
<Error_Handling_statements>
WHEN NO_DATA_FOUND THEN
<Error_Handling_Statements>
END;
1.2.3 Named System Exceptions
System exceptions are automatically raised by Oracle, when a program violates a RDBMS rule.
There are some system exceptions which are raised frequently, so they are pre-defined and
given a name in Oracle which are known as Named System Exceptions.
For example: NO_DATA_FOUND and ZERO_DIVIDE are called Named System exceptions.
Named system exceptions are:
• No need to declare explicitly.
• Raised implicitly when a predefined Oracle error occurs.
• caught by referencing the standard name within an exception-handling routine.
The functions SQLCODE and SQLERRM are useful in the OTHERS handler as they return the
Oracle error code and message text.
Examples
Example:
DECLARE
c_id customers.id%type := 8;
c_name customers.name%type;
c_addr customers.address%type;
BEGIN
SELECT name, address INTO c_name, c_addr FROM customers WHERE id =
c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
EXCEPTION
WHEN no_data_found THEN
DBMS_OUTPUT.put_line('No such customer!');
WHEN others THEN
DBMS_OUTPUT.put_line('Error Due To --
>'|| SQLCODE|| SQLERRM);
END;
1.2.4 Unnamed System Exceptions
Those system exception for which oracle does not provide a name is known as unnamed system
exception.
These exception do not occur frequently. These Exceptions have a code and an associated
message.
There are two ways to handle unnamed system exceptions:
• By using the WHEN OTHERS exception handler.
• By associating the exception code to a name and using it as a named exception.
We can assign a name to unnamed system exceptions using a PRAGMA (compiler directive)
called EXCEPTION_INIT.
EXCEPTION_INIT will associate a predefined Oracle error number to a programmer_defined
exception name.
Steps to be followed to use unnamed system exceptions are
• They are raised implicitly.
• If they are not handled in WHEN OTHERS they must be handled explicitly.
• To handle the exception explicitly, they must be declared using Pragma.
EXCEPTION_INIT as given above and handled referencing the user-defined exception name in
the exception section.
The general syntax to declare unnamed system exception using
EXCEPTION_INIT is:
DECLARE
exception_name EXCEPTION;
PRAGMA
EXCEPTION_INIT (exception_name, Err_code);
BEGIN
Execution section
EXCEPTION
WHEN exception_name THEN
handle the exception
END;
Example:
Lets consider the product table and order_items table .
Here product_id is a primary key in product table and a foreign key in order_items table.
If we try to delete a product_id from the product table when it has child records in order_id table
an exception will be thrown with oracle code number -2292.
We can provide a name to this exception and handle it in the exception section as given below.
DECLARE
Child_rec_exception EXCEPTION;
PRAGMA
EXCEPTION_INIT (Child_rec_exception, -2292);
BEGIN
Delete FROM product where product_id= 104;
EXCEPTION
WHEN Child_rec_exception
THEN DBMS_OUTPUT.put_line('Child records are present for this product_id.');
END;
/
1.2.5 User-defined Exceptions
Apart from system exceptions we can explicitly define exceptions based on business rules.
These are known as user-defined exceptions.
Steps to be followed to use user-defined exceptions:
• They should be explicitly declared in the declaration section.
• They should be explicitly raised in the Execution Section.
• They should be handled by referencing the user-defined exception name in the exception
section.
Example:
Lets consider the product table and order_items tables.
Lets create a business rule that if the total no of units of any particular product sold is more than
20, then it is a huge quantity and a special discount should be provided.
DECLARE
huge_quantity EXCEPTION;
CURSOR product_quantity is
SELECT p.product_name as name, sum(o.total_units) as units
FROM order_tems o, product p
WHERE o.product_id = p.product_id;
quantity order_tems.total_units%type;
up_limit CONSTANT order_tems.total_units%type := 20;
message VARCHAR2(50);
BEGIN
FOR product_rec in product_quantity LOOP
quantity := product_rec.units;
IF quantity > up_limit THEN
message := 'The number of units of product ' || product_rec.name ||
' is more than 20. Special discounts should be provided.
Rest of the records are skipped. '
RAISE huge_quantity;
ELSIF quantity < up_limit THEN
v_message:= 'The number of unit is below the discount limit.';
END IF;
DBMS_OUTPUT.put_line (message);
END LOOP;
EXCEPTION
WHEN huge_quantity THEN
DBMS_OUTPUT.put_line (message);
END;
/
1.2.6 RAISE_APPLICATION_ERROR ( )
RAISE_APPLICATION_ERROR is a built-in procedure in oracle which is used to display the
user-defined error messages along with the error number whose range is in between -20000 and
-20999.
Whenever a message is displayed using RAISE_APPLICATION_ERROR, all previous
transactions which are not committed within the PL/SQL Block are rolled back automatically (i.e.
change due to INSERT, UPDATE, or DELETE statements).
RAISE_APPLICATION_ERROR raises an exception but does not handle it.
RAISE_APPLICATION_ERROR is used for the following reasons.
• To create a unique id for an user-defined exception.
• To make the user-defined exception look like an Oracle error.
The General Syntax to use this procedure is:
RAISE_APPLICATION_ERROR (error_number, error_message);
Steps to be folowed to use RAISE_APPLICATION_ERROR procedure:
• Declare a user-defined exception in the declaration section.
• Raise the user-defined exception based on a specific business rule in the execution section.
• Finally, catch the exception and link the exception to a user-defined error number in
RAISE_APPLICATION_ERROR.
Example:
DECLARE
huge_quantity EXCEPTION;
CURSOR product_quantity is
SELECT p.product_name as name, sum(o.total_units) as units
FROM order_tems o, product p
WHERE o.product_id = p.product_id;
quantity order_tems.total_units%type;
up_limit CONSTANT order_tems.total_units%type := 20;
message VARCHAR2(50);
BEGIN
FOR product_rec in product_quantity LOOP
quantity := product_rec.units;
IF quantity > up_limit THEN
RAISE huge_quantity;
ELSIF quantity < up_limit THEN
v_message:= 'The number of unit is below the discount limit.';
END IF;
DBMS_OUTPUT.put_line (message);
END LOOP;
EXCEPTION
WHEN huge_quantity THEN
raise_application_error(-2100, 'The number of unit is above the discount limit.');
END;
5.1. Procedures
1.1 Objective
• Introduction
• Procedure and Function Differences
• Basic Structure
• Types Of Parameters
• Parameter Modes
• Execution
1.2 Course Content
1.2.1 Introduction
Procedures are Named set of PL/SQL statements designed for a specific action when invoked
explicitly with or without parameters.
Procedures are similar to functions except that return clause is not mandatory in the procedure.
1.2.2 Procedure and Function Differences
• Function is mainly used in the case where it must return a value. Where as a procedure may
or may not return a value or may return more than one value using the OUT parameter.
• Function can be called from SQL statements where as procedure can not be called from the
sql statements
• Functions are normally used for computations where as procedures are normally used for
executing business logic.
• You can have DML (insert,update, delete) statements in a function. But, you cannot call such
a function in a SQL query.
• A Function returns onevalue only. Procedure can return multiple values (max 1024).
• Stored Procedure: supports deferred name resolution. Example while writing a stored
procedure that uses table named tabl1 and tabl2 etc..but actually not exists in database is
allowed only in during creation but runtime throws error Function wont support deferred name
resolution.
• Stored procedure is precompiled execution plan called pcode where as functions are not.
• using execute immediate statement we can use ddl statements in procedure but not in
functions
1.2.3 Basic Structure
The basic syntax for writing a Procedure is
CREATE OR REPLACE PROCEDURE <procedure_name> [ <parameter> [ MODE] <data
type> ]
IS | AS
[ local variable declaration ]
BEGIN
PL/SQL Executable statements
[ EXCEPTION
Exception handlers ]
END [ procedure_name ];
CREATE OR REPLACE : indicates that if the procedure exists , it will be dropped and replaced
by the new version created by the statement or create new procedure.
<parameter> : Name of a PL/SQL variable whose value is passed to or populated by the calling
environment or both, depending upon the mode being used
[ MODE ] : Type of argument ( IN | OUT | INOUT )
<data type> : Data type of the argument (SQL | PL/SQL)
If we are not specifying any parameter,it will consider IN as default mode. We should specy
datatype family only, we should not specify the size of varaible in procedure delcaration.
1.2.4 Types Of Parameters
Formal Parameters : A procedure heading can declare formal parameters.
Each formal parameter can specify a mode and a default value.
They are the variables declared in the procedure header and referenced in the execution part.
Ex : CREATE OR REPLACE PROCEDURE p1(c IN number,c1 IN number)
Actual Parameters : When procedures are invoked , the actual parameters are passed to it.
They are the variables or expressions that pass to the subprogram when invoked.
Ex : p1(12,12)
Corresponding formal and actual parameters must have compatible data types. Both formal and
actual parameters should belongs to same datatype family.
1.2.5 Parameter Modes
Formal parameters can have three modes :
IN
• Default mode
• Read only parameter
• Cannot be assigned a value
• Can pass a constant, literal , initialized variable or expression
• Takes the value inside the subprogram •Cannot be changed inside the subprogram •Pass the
value as call by reference.
• We cannot modify these values in side pl/sql blocks or cannot used to assign values
OUT
• Returns a value to the calling program
• Takes the value out of the subprogram
• Can be changed inside the subprogram
• The actual parameter must be a variable and it is passed by a value •Pass the value as call by
value.
• We can modify these values in side pl/sql blocks or can used to assign values
INOUT
• Passes an initial value to a subprogram and returns an updated value to the caller
• Must be a variable
•Pass the value as call by reference.
•We can modify these values in side pl/sql blocks or can used to assign values
1.2.6 Execution
A standalone procedure can be called in two ways
Using the EXECUTE keyword
EXECUTE procedure_name(actual parameters)
Calling the procedure from a PL/SQL block
BEGIN
procedure_name(actual parameters) END;
Example1:
-- Program to show the usage of IN & OUT parameters
CREATE or REPLACE
PROCEDURE proc1(n IN number,n1 IN number,ou OUT number)
AS
BEGIN
ou:=n+n1; END proc1;
Example2:
CREATE or REPLACE PROCEDURE get_gpa(student_id IN NUMBER, gpa OUT
NUMBER) AS
n NUMBER; grade_temp number; gpa_temp number ;
CURSOR c1(sid) IS
SELECT grade FROM enrollment WHERE student_id = sid;
BEGIN n := 0; gpa := 0;
OPEN c1(student_id);
LOOP
FETCH c1 INTO grade_temp;
EXIT WHEN c1%NOTFOUND; gpa_temp := gpa_temp + grade_temp;
n := n + 1;
END LOOP;
IF n > 0 THEN
gpa := gpa_temp / n;
END IF;
CLOSE c1;
END PROCEDURE get_gpa;
5.2. Functions
1.1 Objective
• Sub program
• Block Structure
• Advantages
• Types
• Functions
• Basic Structure
• Execution
1.2 Course Content
1.2.1 Sub Program
Sub program is a program unit that performs specific task
These can be invoked by another sub program or program , which is called the calling program
and can be invoked with a set of parameters
These can be created
• At Schema Level
• Inside a Package
• Inside a PL/SQL Block
A Schema Level sub program is a standalone sub program that is created with
CREATE keyword and stored in the database and can be dropped using DROP keyword.
A subprogram created inside a package is a packaged subprogram. It is stored in the database
and can deleted only when the package is deleted.
PL/SQL subprograms are the named PL/SQL blocks that can be invoked with a set of
parameters.
1.2.2 Block Structure
<header>
IS | AS
- - Declaration Section
BEGIN
- - Executable Section
EXCEPTION (Optional)
- - Exception section
END;
<header> Specifies PL/SQL subprograms type , Name of a subprogram
Parameter list if exists , RETURN clause depending upon subprogram type
Declarative Part
• Optional part.
• Does not start with DECLARE keyword.
• Contains declarations of types , cursors , constants, variables, exceptions and nested sub
programs.
• The above declarations are local to the subprogram and cease to exist when the subprogram
completes execution.
Executable Part
• Contains statements that assigns values , control execution and manipulation data.
Exception Handling Part
• Contains code that handles run time erors.
1.2.3 Advantages
• Easy maintenance
• Improved data security and integrity
• Improved performance
• Improved code clarity
1.2.4 Types
PL/SQL provides two types of sub programs:
• Procedure
• Function
1.2.5 Functions
Functions are Sub program that always return a value
These needs to be declared and defined before invoking.
These can accept one , many or no parameters
Does not necessarily have parameters , but must have a RETURN value whose data type is
declared in the header.
1.2.6 Basic Structure
The basic syntax for writing a function is
CREATE OR REPLACE
FUNCTION FUNCTION <function_name> [ <parameter> [ MODE ] <data type> ]
RETURN return_data type
IS | AS
[ local variable declaration ]
BEGIN
PL/SQL executable statements
RETURN <v_val>
[ EXCEPTION
Exception handlers]
END [ function_name] ;