Sunteți pe pagina 1din 103

1.1.

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.

Network Model DBMS:


1. A DBMS is said to be a Network DBMS if the relationships among data in the database
are of type many-to-many and appears in the form of a network.
2. Thus the structure of a network database is extremely complicated because of these
many-to-many relationships in which one record can be used as a key of the entire
database.
Object Oriented Relational Database :
1. Object Oriented DBMS add database functionality to object oriented programming
languages.
2. They bring much more than persistent storage of programming language objects.
3. As a result, applications require less code, use more natural data modelling, and code
bases are easier to maintain.

Relational Database Management System:


1. A Data Base Management System that is based on a relational model is called as
Relational Database Management System.
2. Relational model is the most successfully used Data Base Management System Model
(DBMS) model.
3. Relational model represents data in the form of tables.
4. Some popular examples are Oracle, Microsoft SQL Server and Microsoft Access.

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:

1. A candidate is a subset of a super 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.

2. It is a key that uniquely identifies a record in a 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

SELECT Statement (Projection & Selection)


To display all records from table SELECT keyword with asterisk(*) is used:
The above query displays all the records from customer_details
• To retrieve selected columns from the table, specific column names separated by
commas(,) are used

The above query displays only id, name and salary columns from customer_details

SELECT Statement (selection)


The where clause can be used to refine selection results by adding a search criteria.

Restricting Selection using comparison operators:

SELECT name, age FROM customer_details WHERE salary>50000;

The above query displays name and age of customers whose salary more than 50000 From
customer_details table

Restricting Selection using IN keyword:

SELECT name,location FROM customer_details WHERE location IN ('Kolkata','Delhi');

The above query displays name and location of customers who are from Kolkata and Delhi
Restrict based on pattern matching:

SELECT name,location FROM customer_details WHERE name LIKE '_a%';

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'.

Restricting Selection using BETWEEN … AND keyword:

SELECT name,location FROM customer_details WHERE age BETWEEN 20 AND 40;

The above query displays name and location of customers whose age ranging from 20 to 40

Restricting based on NULL value:

In Database terminology NULL is referred as value which is unspecified or unavailable

Based on database configuration, NULL value may not display anything but it should not be
misunderstood as zero or blank space.

Condition on NULL value can be given using the keyword IS.

SELECT name, age FROM customer_details WHERE location IS NULL;

The above query displays name and age of customers whose location not specified

SELECT name, age FROM customer_details WHERE age IS NOT NULL;

The above query displays name and age of customers whose age available

DISTINCT Keyword & GROUP -ORDER BY Clause

To eliminate duplicate rows DISTINCT keyword is used in the SELECT statement.

The above query displays only the different age values.

ORDER BY Clause

ORDER BY clause in the SELECT statement is used to sort the results.


1. Name, age and salary of the customers displayed as per the ascending order of their
salary.

2. DESC keyword can be used to display the list in descending order

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.

Note: Group By Statements will be discussed in detail later

Concatenation Operator & Column Alias

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.

2. Column headings in the table is unchanged.

Data Definition Language (DDL)


DDL statements define the data structure such as tables, views etc.. that make up the database.
All DDL statements are auto committed means the changes will become permanent and
database objects created are available to all users.
Commonly used DDL statements are:
• CREATE
• ALTER
• DROP
• RENAME
• TRUNCATE

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.

DDL statement: ALTER


Alter statement is used to modify the structure of database or database objects like tables, views
etc..
Alter table statement - to add column to a table:

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.

DDL statements: TRUNCATE, DROP, RENAME


Truncate Table:
Remove all the rows and resets schema of the table.
TRUNCATE TABLE Employee;
Drop table :
Deletes table entirely from the database.
DROP TABLE Employee;
Renaming a Table:
RENAME Employee to Emp_table;
Data Manipulation Language(DML)

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:

Insertion can also be done in interactive way.


The records can be inserted in interactive manner also
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.

Transaction Start and End Scenarios:


A Transaction begins when the first executable sql statement is encountered.
The Transaction terminates when the following specifications occur.
A COMMIT or ROLL BACK issued.
A DDL statement issued
A DCL statement issued
Failure of machine or system crashes
A DDL or DCL statement is automatically committed and hence implicitly ends a Transaction.

Explicit Transaction Control Statements


• COMMIT
• SAVEPOINT
• ROLLBACK
COMMIT:
It ends the current Transaction by making all pending data changes permanent.
Syntax:COMMIT;
Once commit is issued, data changes will become permanent.
The previous state of the data is permanently lost.
All users can view the results of the recent transactional changes.
Ex: UPDATE employee SET salary =1000 WHERE emp_id = 10;
COMMIT;
SAVEPOINT:
It marks a savepoint with in the current Transaction.
We can create multiple savepoints in single Transaction.
Savepoints can be used to control the reverting of changes.
Syntax:SAVEPOINT <NAME>;
Ex: SAVEPOINT S1;
ROLLBACK:
It ends the current Transaction by discarding all pending data changes.
The data changes are undone.
The previous state of data is restored.
The locks on the affected rows are automatically released.
Syntax: ROLLBACK or ROLLBACK to <SAVEPOINT NAME>;
Ex: UPDATE employee SET salary =1000 WHERE emp_id = 10;
ROLLBACK;
using savepoint the Transaction can be discarded up to the marker by using rollback statement.
Ex: INSERT INTO employee VALUES(10,'JHON',3000);
INSERT INTO employee VALUES(10,'KELLY',2000);
SAVEPOINT S1;
INSERT INTO employee VALUES(10,'WILSON',4000);
ROLLBACK TO S1;
Single Row Functions in SQL
Introduction to Oracle Built-in Functions
Oracle Built-in Functions are the functions supplied by Oracle that can be used to manipulate
data items and return a result.
There are two types of Built-in functions available in Oracle.
Single Row Functions: Single row or Scalar functions return a value for every row that is
processed.
Group Functions: These functions group the rows of data based on the values returned by the
query, performs the aggregate function(sum,avg etc.) on each group and return one value per
group of rows.
Single Row Functions
Single row or Scalar functions return a value for every row that is processed .
There are four different types of single row functions-
1)Conversion Functions: These are functions that help us to convert a value in one form to
another form. For Example: a null value into an actual value, or a value from one data type to
another data type like NVL,TO_CHAR, TO_NUMBER, TO_DATE etc...
2)Character or Text Functions: These are functions that accept character input and can return
both character and number values.
3)Numeric Functions: These are functions that accept numeric input and return numeric values.
4)Date Functions: These are functions that take values that are of data type DATE as input and
return values of data type DATE, except for the MONTHS_BETWEEN function, which returns a
number.
Consider the following table Employee:

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

1. Numeric functions are used to perform operations on numbers.


2. They accept numeric values as input and return numeric values as output.
3. Following are the few examples of Numeric functions available in Oracle.

a. ABS and MOD


b. POW and SQRT
c. FLOOR and CEIL
d. TRUNC and ROUND

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.

POWER and SQRT Function


POWER function returns the argument raised to the specified power.
Syntax : POWER(number1,number2)
Ex: SELECT POWER(4,3) As Cube FROM dual;
64
The above query returns the output when 4 is raised to the power of 3.
SQRT function returns the square root of a number passed as parameter.
Syntax: SQRT(number)
Ex: SELECT SQRT(64) As “Square Root” FROM dual;
8
The above query returns the square root value of 64.

FLOOR and CEIL Function


The FLOOR function returns the largest integer less than or equal to the value
passed in parameter.
Syntax: FLOOR(decimal number)
Ex: SELECT FLOOR(7.14), FLOOR(7.84) FROM dual;
7 7
The above query returns the largest integer nearest to 7.14 & 7.84.
Ex: SELECT FLOOR(-7.14) FROM dual;
-8
The above query returns the largest integer nearest to -7.14.
The CEIL function returns the smallest integer greater than or equal to the value
mentioned in parameter.
Syntax: CEIL(decimal number)
Ex: SELECT CEIL(7.14), CEIL(7.84) FROM dual;
8 8
The above query returns the smallest integer nearest to 7.14 & 7.84.
Ex: SELECT CEIL(-7.14) FROM dual;
-7
The above query returns the smallest integer nearest to -7.14.

TRUNC and ROUND Function


1) The TRUNC function truncates the value present in the column, expression up to decimal
places mentioned in first parameter.
2) If the second argument is 0 or is missing, the value is truncated to zero decimal places.
Syntax: TRUNC(decimal number,number of places)
Ex: SELECT TRUNC(137.5738,3) As Rounded FROM dual;
137.573
The above query returns the decimal number with three digits after the decimal point.
Ex: SELECT TRUNC(137.5738,0) As Rounded FROM dual;
137
The above query returns the integer value.
The ROUND function round off the value present in the column, expression up to decimal places
mentioned in first parameter.
If the second argument is 0 or is missing, the value is rounded to zero decimal places.
Syntax: ROUND(decimal number,number of places)
Ex: SELECT ROUND(137.5738,3) As Rounded FROM dual;
137.574
The above query returns the decimal number with three digits after the decimal point where
4th digit is rounded.
SQL> SELECT ROUND(137.5738,0) As Rounded FROM dual;
138
The above query returns the integer value rounded to the next highest value.
If the second argument is negative number, the value is rounded up specified decimal places to
the left (rounded to the nearest unit of 10).
Ex: SELECT ROUND(137.5748,-1) As Rounded FROM dual;
140
The above query returns the integer value which is the nearest tens value.
Ex: SELECT ROUND(137.5748,-2) As Rounded FROM DUAL;
100
The above query returns the integer value which is the nearest hundreds value.
Aggregate/Group functions

Aggregate / Group Functions


• Group Functions, as the name suggests, are functions that operate on groups(sets) of
values and returns one result per group.
• Group function returns a single result row for every group of queried rows.
• Based on the query statement it may return single or multiple rows.
The functions that are used as Aggregate Functions are:
• SUM
• AVG
• MAX
• MIN
• COUNT
Consider the following table: Employee

AVG: Returns an average value, ignoring null values.


Syntax: AVG([DISTINCT] column_name)
Ex: SELECT AVG(salary) as “Average Salary” FROM Employee;
21500
The above query displays the average salary of all the employees in the table Employee
MAX: Returns the maximum value, ignoring null values.
Syntax: MAX([DISTINCT] column_name)
Ex: SELECT MAX(salary) as “Maximum Salary” FROM Employee where Dep_Name='HR';
16000
The above query displays the maximum salary of all the employees in HR Department in the
table Employee.
MIN: Returns the minimum value, ignoring null values.
Syntax: MIN([DISTINCT] column_name)
Ex: SELECT MIN(salary) as “Minimum Salary” FROM Employee where Dep_Name='HR';
10000
The above query displays the minimum salary of all the employees in HR Department in the table
Employee.
COUNT: Returns the count of not null values ignoring null values.
Syntax: COUNT([DISTINCT] column_name)
Ex: SELECT COUNT(DISTINCT Dep_name) Departments FROM Employee;
3
The above query displays the count of different departments in the table Employee.
COUNT:(*) Count function with asterisk returns the count of total number of rows including null
values
Syntax: COUNT(*)
Ex: SELECT COUNT(*) FROM Employee;
5
The above query displays the total number of rows in table Employee.

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.

1.2.3.1 Weak Entity


• Weak entity is an entity that depends on another entity.
• A weak entity cannot be uniquely identified by its attributes alone, hence it must use a foreign
key along with its attributes which is a primary key of the entity on which the weak entity depends
upon.
• Graphically weak entity is represented by double rectangle.
1.2.4 Relationship and relationship types
A relationship is a logical link between entities.
A relationship is graphically represented by a diamond.

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 specified , a person will be marrying another person.


1.2.4.2 Binary relationship
A relationship which involves two entities.

The above representation specifies that 'books' are available in the 'library'.
1.2.4.3 Ternary Relationship
A relationship which involves three entities.

The above representation indicates that a ternary relationship.


1.2.4.4 Relationship with attributes
A relationship can also contain an attribute.
The above representation indicates 'store is selling goods and maintaining the price and sold
date of all the goods sold'.
1.2.5 Attribute and attribute types
• An attribute is a property / feature of an entity.
• Attributes are nothing but properties of entities and relationships that describe their
characteristics.
• The value of an attribute is an element of a data type like number, date etc..
• An attribute is graphically represented by an ellipse.

1.2.5.1 Key attribute


An attribute that represents the main characteristics of an entity.
Key attribute is used to represent the primary key.
Key attribute uniquely identifies the entity.
Key attribute is graphically represented by ellipse with an attribute name underlined.

1.2.5.2 Composite attribute


An attribute which has its own characteristics.
An attribute which consists of several simple attributes. (eg. Address consists of :
street,city,postal code etc..)
An attribute which groups attributes of the same entity or relationship that have closely
connected uses.

1.2.5.3 Derived attribute


An attribute which is derived from the composite attribute. (Eg . Street , city , state, pincode)
Derived attribute is graphically represented as dashed ellipse.
1.2.5.4 Multivalued attribute
An attribute with a set of possible values for the same entity. (Eg. Phone no - can have mobile
no , land number)
A multivalued attribute is graphically represented by double ellipse.

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

The above representation indicates 'many stores sells many goods'.


Note :
( * ) specifies many
1.4. Database Normalization
1.1 Objective
• Introduction
• Database Dependencies
• Normal Forms
• Demonstration of Normalization with an Example
1.2 Course Content
1.2.1 Introduction
Normalization is a series of steps followed to obtain a database design that
allows efficient access and storage of data.
With Normalization we can –
• Eliminate data redundancy(storing the same data in more than one table)
• Ensure Data Dependencies(only storing related data in a table)
• Ensure Data Consistency
• Reduces the amount of space a database consumes
• Ensure that data is logically stored.
1.2.2 Database Dependencies
Functional Dependency
Is a relationship where knowing the value of one attribute (or a set of attributes) is enough to tell
you the value of another attribute (or set of attributes) in the same table.
If there is a dependency in a database such that attribute B is dependent upon attribute A, you
would write this as “A -> B”.
Here B is functionally dependent on A and A is called as determinant
Example:
stuId→lastName
Partial Dependency or Trivial Functional Dependency
It occurs when functional dependency of an attribute defined on a collection of attributes that
includes the original attribute.
For Example, “{A, B} -> B” is a trivial functional dependency
Example:
{name, SSN} -> SSN

Full Functional Dependency


A full functional dependency occurs when you already meet the requirements for a functional
dependency and the set of attributes on the left side of the functional dependency statement
cannot be reduced any farther.
Ex: {shipmentno,partno}-->Qty
Author, Title→Publication Date
Shakespeare’s Hamlet was published in 1600
Transitive Dependency
Transitive dependency occur when there is an indirect relationship that causes a functional
dependency.
For Example, ”A -> C” is a transitive dependency when it is true only because both “A -> B” and
“B -> C” are true.
Example:
{Book} → {Author}
{Author} → {Author Nationality}
Therefore {Book} → {Author Nationality} is a transitive dependency.
Multivalued Dependency
Multivalued dependency occurs when the presence of one or more rows in a table implies the
presence of one or more other rows in that same table.
Basically , the existence of one row forces the resistance of another row in the table.
For Example, if a car model is having an entry in database with one colour, there will be another
entry in the table with all the fields same except with different color as shown below.
Model Year Color
Altolxi 2014 Blue
Altolxi 2014 Red
1.2.3 Normal Forms
The database community has developed a series of guidelines for ensuring that databases are
normalized.
These are referred to as normal forms.
• First Normal Form
• Second Normal Form
• Third Normal Form
• Boyce Codd Normal Form
• Fourth Normal Form
• Fifth Normal Form
In most practical applications normalization achieves its best in 3NF.
1.2.4 Demonstration of Normalization with an Example
Consider student table containing student details along with his semester subjects as shown
below.
First Normal Form:
As shown in the highlighted boxes, the data in some columns is repeating because of other
columns.
To avoid this, we need to make this table into two tables as shown below and can identify a
primary key for each table using first normal form.

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.

Third Normal Form:


As shown in the above figure, in third normal form we will establish relation between two tables
using foreign key.
Also in 3NF we will remove the transitive dependant if any.
1.5. Constraints & Keys
1.1 Objective
• Introduction
• Constraint Types
• Declaration Style
• Primary Key
• Unique Key
• Foreign Key
• Check
• Not Null
• Default
1.2 Course Content
1.2.1 Introduction
• SQL Constraints are used to specify rules for the data in the table, ensuring the data
conforms to the requirements defined. They are critical to the integrity , flexibility and scalability
of the data in the table.
• Constraints can defined when the table is created (with the CREATE statement) or after the
table is created (with the ALTER statement).
• Every constraint is maintained with a name (CONSTRAINT_NAME) in the database. Hence
when we declare a constraint on a column , if we do not provide a constraint name , Oracle
associates the constraint with the name.
• The same constraint is name is not allowed within one user login. For example , a constraint
name c1_pk is created , constraints should not be defined again with the same name.
1.2.2 Constraint Types
There are six types of constraints available to provide rules to the tables.
• PRIMARY KEY
• UNIQUE
• FOREIGN KEY
• CHECK
• NOT NULL
• DEFAULT
1.2.3 Declaration Style
Syntactically constraints can be defined on columns of tables in 2 different ways
• Column Level (OR) In-line style : Constraint is defined as part of the definition of an individual
column or attribute. Constraints can be defined at column level using both the CREATE and
ALTER statements. They are usually specified when the constraint is specific to the column
only.
Syntax:
CREATE TABLE sample
(col1 DATATYPE(size) CONSTRAINT_NAME,col2
DATATYPE(size) CONSTRAINT_NAME,…......);
• Table Level (OR) Out-of-lilne style : Constraint is defined as part of the table definition.
Constraints can be defined at table level only with the help of CREATE statement. They are
usually specified when the constraint need to be applied on the combination of columns together.
Syntax:
CREATE TABLE sample
(col1 DATATYPE(size), col2 DATATYPE(size), col3 DATATYPE(size),
CONSTRAINT_NAME(col1), CONSTRAINT_NAME(col2),…......);
1.2.4 Primary Key
• A PRIMARY KEY constraint uniquely identifies each record in the table. A PRIMARY KEY
column cannot have duplicate values.
• A PRIMARY KEY column cannot have null values.
• A PRIMARY KEY can consist of one or more columns.
• Since PRIMARY KEY can be defined only once, if at all multiple columns need to be defined
as a PRIMARY KEY, it is possible. This is called as COMPOSITE PRIMARY KEY.
1.2.4.1 Restrictions
• Only one PRIMARY KEY can be defined on a table.
• PRIMARY KEY cannot be defined on the columns having LOB,LONG,LONG RAW,BFILE
etc... data types.
• A Composite PRIMARY KEY can be defined only as a table level definition. A composite
PRIMARY KEY cannot have more than 32 columns.
1.2.4.2 Primary key with Create statement (Column Level)
A PRIMARY KEY constraint can be defined on a table with the help of a CREATE statement.
PRIMARY KEY can be defined immediately after the column definition.
Syntax :
CREATE TABLE table1 (col1 DATATYPE(size) CONSTRAINT cons_name PRIMARY KEY, col2
DATATYPE(size), col3 DATATYPE(size),........);
Ex: CREATE TABLE location( loc_id NUMBER(4) CONSTRAINT loc_pk PRIMARY
KEY, street_address VARCHAR2(20), city VARCHAR2(15), state VARCHAR2(15), pincode
NUMBER(6));
The above example specifies that every location must have a unique value to identify the location
and that should not be left blank.
1.2.4.3 Primary key with Create statement (Table Level)
A PRIMARY KEY can be defined as a table level definition once finishing all the column
definitions.
Syntax :
CREATE TABLE table1 (col1 DATATYPE(size), col2 DATATYPE(size), col3 DATATYPE(size),
........, CONSTRAINT cons_name PRIMARY KEY(col1));
Ex: CREATE TABLE location ( loc_id NUMBER(4), street_address VARCHAR2(20), city
VARCHAR2(15), state VARCHAR2(15), pincode NUMBER(6) CONSTRAINT loc_pk PRIMARY
KEY(loc_id));
The above example specifies that every location must have a unique value to identify the location
and that should not be left blank.
1.2.4.4 Composite Primary key
A PRIMARY KEY can be defined on multiple columns if required. This type of defining on
multiple columns is called as composite PRIMARY KEY.
Syntax :
CREATE TABLE table1 (col1 DATATYPE(size), col2 DATATYPE(size), ........, CONSTRAINT
cons_name PRIMARY KEY(col1,col2));
Ex: CREATE TABLE sales (sales_id NUMBER(6), cust_id NUMBER(4), prod_id
NUMBER(5), qnty NUMBER(6), sold_date DATE, CONSTRAINT sales_pk PRIMARY
KEY(sales_id,cust_id,prod_id));
The above example specifies that for a sales transaction need to happen , an individual sales_id
, cust_id to whom the products has been sold and prod_id for each and every product need to be
given. Since all the three attributes need to maintain the uniqueness and should not be null, a
composite PRIMARY KEY has been defined.
1.2.4.5 Primary key with Alter statement
Suppose a table has been created without a PRIMARY KEY and later it was identified to
maintain a PRIMARY KEY in the table , this can be achieved with the help of ALTER statement.
If the existing table consists of records , the table need to be taken as a back up and then need
to be truncated. After truncating the table , table structure can be altered.
Syntax:
ALTER TABLE table2 ADD CONSRAINT cons_name PRIMARY KEY(col1);
Ex: CREATE TABLE person ( aadhar_id VARCHAR2(10), name VARCHAR2(30), dob DATE,
phone_number NUMBER(12), address VARCHAR2(30));
ALTER TABLE person ADD CONSTRAINT aadhar_pk PRIMARY KEY (aadhar_id);
The above example specifies that, the Central government wants to maintain the persons details
in order to issue the aadhar card. They have created a table with the person details. Since
aadhar number should be different for each and every individual , with the help of ALTER
statement the aadhar_id is maintained as a PRIMARY KEY.
In order to remove a PRIMARY KEY constraint which is defined on a table , we need to drop the
constraint defined.
Syntax:
ALTER TABLE table1 DROP CONSTRAINT cons_name;
Ex: ALTER TABLE location DROP CONSTRAINT loc_pk;
From the above example we can observe that if at all the location table does not want to maintain
a PRIMARY KEY, that can be removed.
1.2.5 Unique Key
• A UNIQUE KEY constraint allows to maintain uniqueness in the table column on which it is
defined.
• A column can have null values though it is defined as a UNIQUE.
• A UNIQUE KEY constraint can consist of one or more columns.
• When required to define multiple columns as UNIQUE KEY , a COMPOSITE UNIQUE
constraint can be defined.
1.2.5.1 Restrictions
• Only one UNIQUE KEY constraint can be defined on a table.
• UNIQUE KEY constraint cannot be defined on the columns having LOB,LONG,LONG
RAW,BFILE etc... data types.
• Composite UNIQUE KEY constraint can be defined only as a table level definition.
• A composite UNIQUE KEY constraint cannot have more than 32 columns.
1.2.5.2 Unique with Create statement (Column Level)
A UNIQUE KEY constraint can be defined on a table with the help of a CREATE statement.
UNIQUE KEY can be defined immediately after the column definition.
Syntax :
CREATE TABLE table1 (col1 DATATYPE(size) CONSTRAINT cons_name UNIQUE, col2
DATATYPE(size), col3 DATATYPE(size),........);
Ex: CREATE TABLE supplier ( supp_id NUMBER(4) CONSTRAINT supid_unq UNIQUE, name
VARCHAR2(20), contact_number NUMBER(15));
The above example specifies that every supplier must have a unique value to identify the
supplier.
1.2.5.3 Unique with Create statement (Table Level)
A UNIQUE KEY constraint can be defined as a table level definition once finishing all the column
definitions.
Syntax :
CREATE TABLE table1 (col1 DATATYPE(size), col2 DATATYPE(size), col3 DATATYPE(size),
........, CONSTRAINT cons_name UNIQUE(col1));
Ex: CREATE TABLE supplier( supp_id NUMBER(4), name VARCHAR2(20),
contact_number NUMBER(15), CONSTRAINT supid_unq UNIQUE(supp_id));
The above example specifies that every supplier must have a unique value to identify the
supplier.
1.2.5.4 Composite Unique constraint
A UNIQUE KEY constraint can be defined on multiple columns if required. This type of defining
on multiple columns is called as composite UNIQUE constraint.
Syntax :
CREATE TABLE table1 (col1 DATATYPE(size), col2 DATATYPE(size), col3 DATATYPE(size),
........, CONSTRAINT cons_name UNIQUE(col1,col2));
Ex: CREATE TABLE warehouse(id NUMBER(6), name VARCHAR2(20), address
VARCHAR2(20), contact_number NUMBER(12), CONSTRAINT warehouse_unq
UNIQUE(id,name));
The above example specifies that every warehouse need to have a specific id and specific name,
which is possible with composite UNIQUE constraint.
1.2.5.5 Unique with Alter statement
Suppose a table has been created without a UNIQUE KEY constraint and later it was identified to
maintain a UNIQUE constraint in the table , this can be achieved with the help of ALTER
statement.
Syntax:
ALTER TABLE table2 ADD CONSRAINT cons_name UNIQUE(col1);
Ex: CREATE TABLE new_sim_registration(name VARCHAR2(20), gender CHAR(1), dob
DATE, existing_contact_no NUMBER(12), new_sim_no NUMBER(12), address_proof
VARCHAR2(10));
ALTER TABLE new_sim_registration ADD CONSTRAINT newsim_unq UNIQUE(new_sim_no);
The above example specifies that, whenever a customer wants to take a new sim card , the
telephone service provider will collect all the details of the customer and makes the new_sim_no
as UNIQUE so that the new_sim_no can be filled later once the address_proof submitted is
verified.
In order to remove a UNIQUE KEY constraint which is defined on a table , we need to drop the
constraint defined.
Syntax:
ALTER TABLE table1 DROP CONSTRAINT cons_name;
Ex: ALTER TABLE location DROP CONSTRAINT newsim_unq;
From the above example we can observe that if at all the government does not want to maintain
a UNIQUE constraint, that can be removed.
1.2.6 Foreign Key
• A FOREIGN KEY means establishing the relationship between parent and child tables.
(parent – PRIMARY / UNIQUE defined table , child – FOREIGN KEY defined table)
• A FOREIGN KEY in one table points to a PRIMARY KEY / UNIQUE in another table.
• The PRIMARY KEY and the FOREIGN KEY can exist in the same table.
• A composite FOREIGN KEY should be defined at table level. A composite FOREIGN KEY
must refer to the composite PRIMARY KEY / UNIQUE constraint.
1.2.6.1 Restrictions
• The child and parent tables must be in the same database.
• The PRIMARY KEY / UNIQUE and FOREIGN KEY fields must be of same data type.
1.2.6.2 Referential Integrity
• It preserves the defined relationship between the tables when the records are inserted or
deleted.
• It ensures that key values are consistent across the tables.
• When referential integrity is enforced , it prevents from
1. Adding records to a child table if there is no associated record available in the parent
table.
2. Changing values in the parent table is associated records available in the child table.
3. Deleting records from the parent table if there are matching records available in the
child table.
1.2.6.3 Foreign key with Create statement (Column Level)
A FOREIGN KEY constraint can be defined on a table with the help of a CREATE
statement. FOREIGN KEY can be defined immediately after the column definition with the help
of REFERENCES keyword to refer the parent table.
Syntax :
CREATE TABLE table2 (col4 DATATYPE(size) CONSTRAINT cons_name REFERENCES
table1(col1), col5 DATATYPE(size), col6 DATATYPE(size) , ........);
Ex: CREATE TABLE person(name VARCHAR2(30),dob DATE,gender CHAR(1),address
NUMBER(4) REFERENCES location(loc_id),gender CHAR(1));
The above example specifies that in order to maintain the address for each and every person,
the address's which are available in the location table are linked into the address field of the
person table.
1.2.6.4 Foreign key with Create statement (Table Level)
A FOREIGN KEY constraint can be defined as a table level definition once finishing all the
column definitions.
Syntax :
CREATE TABLE table2 (col4 DATATYPE(size), col5 DATATYPE(size), col6 DATATYPE(size),
........, CONSTRAINT cons_name FOREIGN KEY(col4) REFERENCES table1(col1));
Ex: CREATE TABLE person(name VARCHAR2(30),dob DATE,gender CHAR(1),address
NUMBER(4),gender CHAR(1),FOREIGN KEY(address) REFERENCES location(loc_id));
The above example specifies that in order to maintain the address for each and every person,
the address's which are available in the location table are linked into the address field of the
person table.
1.2.6.5 Composite Foreign key
A FOREIGN KEY constraint can be defined on multiple columns if required. This type of defining
on multiple columns is called as composite FOREIGN KEY.
Syntax :
CREATE TABLE table2 (col4 DATATYPE(size), col5 DATATYPE(size), col6
DATATYPE(size), ........, CONSTRAINT cons_name FOREIGN KEY (col4,col5) REFERENCES
table1(col1,col2));
Ex: CREATE TABLE production(suppl_id NUMBER(4),warehouse_id NUMBER(6),
warehouse_name VARCHAR2(20),product_name VARCHAR2(20),qnty NUMBER(4),unit_price
NUMBER(6,2),CONSTRAINT suppl_fk FOREIGN KEY(suppl_id) REFERENCES
supplied(supp_id),CONSTRAINT warehouse_fk (warehouse_id,warehouse_name)
REFERENCES (id,name));
The above example specifies the in order to maintain the production details, who is the supplier
of the products and in which warehouse they are been stored, the details of supplier and
warehouse need to be maintained which are in turn taken from the supplier table and warehouse
table.
1.2.6.6 Foreign key with Alter statement
Suppose a table has been created without a FOREIGN KEY constraint and later it was identified
to maintain a FOREIGN KEY constraint in the table , this can be achieved with the help of
ALTER statement.
Syntax:
ALTER TABLE table2 ADD CONSRAINT cons_name FOREIGN KEY (col4) REFERENCES
table1(col1);
Ex: CREATE TABLE person(name VARCHAR2(30),dob DATE,gender CHAR(1),address
NUMBER(4) ,gender CHAR(1));
ALTER TABLE person ADD CONSTRAINT location_fk FOREIGN KEY(address) REFERENCES
location(loc_id);
The above example specifies that in order to maintain the address for each and every person,
the address's which are available in the location table are linked into the address field of the
person table.
In order to remove a FOREIGN KEY constraint which is defined on a table , we need to drop the
constraint defined.
Syntax:
ALTER TABLE table1 DROP CONSTRAINT cons_name;
Ex:ALTER TABLE person DROP CONSTRAINT location_fk;
From the above example we can observe that if at all the government does not want to maintain
a FOREIGN KEY constraint, that can be removed.
1.2.6.7 Maintaining referential integrity
1.2.6.7.1 ON DELETE SET NULL
A foreign key with CASCADE DELETE means that if a record in the parent table is deleted , then
the corresponding records in the child table will be automatically deleted.
Syntax:
CREATE TABLE table2 (col4 DATATYPE(size), col5 DATATYPE(size), ........, CONSTRAINT
cons_name FOREIGN KEY (col4,col5) REFERENCES table1(col1,col2) ON DELETE SET
NULL);
Ex: CREATE TABLE production(suppl_id NUMBER(4),warehouse_id NUMBER(6),
warehouse_name VARCHAR2(20),product_name VARCHAR2(20),qnty NUMBER(4),unit_price
NUMBER(6,2),CONSTRAINT suppl_fk FOREIGN KEY(suppl_id) REFERENCES
supplied(supp_id), CONSTRAINT warehouse_fk (warehouse_id,warehouse_name)
REFERENCES (id,name) ON DELETE SET NULL);
The above example specifies that if at all the records available in the warehouse table (id,name)
are deleted then automatically the records in the production table (warehouse_id ,
warehouse_name) will be set to null.
Syntax:
ALTER TABLE table2 ADD CONSRAINT cons_name FOREIGN KEY (col4) REFERENCES
table1(col1) ON DELETE SET NULL;
Ex: CREATE TABLE person(name VARCHAR2(30),dob DATE,gender CHAR(1), address
NUMBER(4) ,gender CHAR(1));
ALTER TABLE person ADD CONSTRAINT location_fk FOREIGN KEY(address) REFERENCES
location(loc_id) ON DELETE SET NULL;
The above example specifies that if at all the records available in the location table (loc_id) are
deleted then automatically the records in the person table (address) will be set to null.
1.2.6.7.2 ON DELETE CASCADE
A FOREIGN KEY with SET NULL ON DELETE means that if a record in the parent table is
deleted , then the corresponding records in the child table will have the foreign key fields set to
null. The records in the child table will not be deleted.
Syntax :
CREATE TABLE table2 (col4 DATATYPE(size) CONSTRAINT cons_name REFERENCES
table1(col1) ON DELETE CASCADE,col5 DATATYPE(size), col6 DATATYPE(size) , ........);
Ex: CREATE TABLE person(name VARCHAR2(30),dob DATE,gender CHAR(1),address
NUMBER(4) REFERENCES location(loc_id) ON DELETE CASCADE,gender CHAR(1));
The above example specifies that, If the data is deleted from the location table location id ,
automatically they will be removed from person table address field.
Syntax:
CREATE TABLE table2 (col4 DATATYPE(size), col5 DATATYPE(size), col6
DATATYPE(size), ........, CONSTRAINT cons_name FOREIGN KEY (col4,col5) REFERENCES
table1(col1,col2) ON DELETE CASCADE);
Ex: CREATE TABLE production(suppl_id NUMBER(4),warehouse_id NUMBER(6),
warehouse_name VARCHAR2(20),product_name VARCHAR2(20),qnty NUMBER(4),unit_price
NUMBER(6,2),CONSTRAINT suppl_fk FOREIGN KEY(suppl_id) REFERENCES
supplied(supp_id), CONSTRAINT warehouse_fk (warehouse_id,warehouse_name)
REFERENCES (id,name) ON DELETE CASCADE);
The above example specifies that, If the data is deleted from the warehouse table id and name ,
automatic deletion will happen in production table warehouse id and name.
Syntax:
ALTER TABLE table2 ADD CONSRAINT cons_name FOREIGN KEY (col4) REFERENCES
table1(col1) ON DELETE CASCADE;
Ex: CREATE TABLE person(name VARCHAR2(30),dob DATE,gender CHAR(1), address
NUMBER(4) ,gender CHAR(1));
ALTER TABLE person ADD CONSTRAINT location_fk FOREIGN KEY(address) REFERENCES
location(loc_id) ON DELETE CASCADE;
The above example specifies that , If the data is deleted from the location table location id ,
automatically they will be removed from person table address field.
1.2.7 Check
• CHECK constraint allows to specify conditions that each row in a column must satisfy.
• CHECK constraint validates the values in a given column to meet the specified criteria.
• CHECK constraint is used to limit the value range that can be placed in a column.
1.2.7.1 Restrictions
• The CHECK constraint can refer any columns of the table , but cannot refer any columns of
another table.
• CHECK constraint condition cannot include any view or sub query.
1.2.7.2 Check constraint with Create statement (Column Level)
A CHECK constraint can be defined on a table with the help of a CREATE statement.
Syntax :
CREATE TABLE table1 (col1 DATATYPE(size) CONSTRAINT cons_name CHECK (condition),
col2 DATATYPE(size) , ........);
Ex:CREATE TABLE person(name VARCHAR2(10), dob DATE, gender CHAR(1) CONSTRAINT
gndr_chk CHECK(gender IN ('M','F'));
The above example specified in the gender fields only the values 'M' or 'F' only need to be
entered.
1.2.7.3 Check constraint with Create statement (Table Level)
A CHECK constraint can be defined as a table level definition once finishing all the column
definitions.
Syntax :
CREATE TABLE table1 (col1 DATATYPE(size),col2 DATATYPE(size), ........, CONSTRAINT
cons_name CHECK (condition),CONSTRAINT cons_name CHECK (condition));
Ex:CREATE TABLE person(name VARCHAR2(10), gender CHAR(1),dob DATE, CONSTRAINT
gndr_chk CHECK(gender IN ('M','F'));
The above example specifies that gender fields only the values 'M' or 'F' only need to be entered.
1.2.7.4 Check constraint with Alter statement
Suppose a table has been created without a CHECK constraint and later it was identified to
maintain a CHECK constraint in the table , this can be achieved with the help of ALTER
statement.
Syntax:
ALTER TABLE table2 ADD CONSRAINT cons_name CHECK (condition);
Ex: CREATE TABLE person(name VARCHAR2(10), gender CHAR(1),dob DATE);
ALTER TABLE person ADD CONSTRAINT gndr_chk CHECK(gender IN ('M','F'));
The above example specifies that gender fields only the values 'M' or 'F' only need to be entered.
In order to remove a CHECK constraint which is defined on a table , we need to drop the
constraint defined.
Syntax:
ALTER TABLE table1 DROP CONSTRAINT cons_name;
Ex:ALTER TABLE person DROP CONSTRAIN gndr_chk;
From the above example we can observe that if at all the government does not want to maintain
a CHECK constraint for the gender field, that can be removed.
1.2.8 Not Null
• NOT NULL are the in-line constraints which specify that a column cannot contain null values.
• It should be defined at column level.
• NOT NULL constraint specifies that the column cannot contain null values.
1.2.8.1 Not Null constraint with Create statement
Syntax :
CREATE TABLE table1 (col1 DATATYPE(size) CONSTRAINT cons_name NOT NULL,col2
DATATYPE(size) CONSTRAINT cons_name NOT NULL, col3 DATATYPE(size) , ........);
Ex:CREATE TABLE student (sid NUMBER(4) CONSTRAINT sid_pk PRIMARY KEY, sname
VARCHAR2(30) CONSTRAINT name_nn NOT NULL,dob DATE CONSTRAINT dob_nn NOT
NULL,gender CHAR(1) CONSTRAINT gndr-chk CHECK (gender ='M' OR gender='F'));
The above example specifies that student id should not contain any duplicate and null values ,
student name and date of birth should always be entered with a value and gender field is
restricted with the specified values.
1.2.8.2 Not Null constraint with Alter statement
Suppose a table has been created without a CHECK constraint and later it was identified to
maintain a CHECK constraint in the table , this can be achieved with the help of ALTER
statement.
Syntax:
ALTER TABLE table2 MODIFY (col1 DATATYPE(size) NOT NULL);
Ex: CREATE TABLE student (sid NUMBER(4) CONSTRAINT sid_pk PRIMARY KEY, sname
VARCHAR2(30) ,dob DATE,gender CHAR(1) CONSTRAINT gndr-chk CHECK (gender ='M' OR
gender='F'));
ALTER TABLE student MODIFY(sname VARCHAR2(30) NOT NULL,dob DATE NOT NULL);
The above example specifies that student id should not contain any duplicate and null values ,
student name and date of birth should always be entered with a value and gender field is
restricted with the specified values.
In order to remove a NOT NULL constraint which is defined on a table , we need to drop the
constraint defined.
Syntax:
ALTER TABLE table1 DROP CONSTRAINT cons_name;
Ex:ALTER TABLE person DROP CONSTRAIN dob_nn;
From the above example we can observe that if at all the government does not want to maintain
a NOT NULL constraint for the dob field, that can be removed.
1.2.9 Default
• The DEFAULT constraint provides a default value to a column when the INSERT INTO
statement does not provide a specific value.
• The default value will be added to all the records if no other values is specified.
1.2.9.1 Default constraint with Create statement
Syntax :
CREATE TABLE table1 (col1 DATATYPE(size) DEFAULT value,col2 DATATYPE(size)
DEFAULT value, col3 DATATYPE(size) , ........);
Ex: CREATE TABLE student (sid NUMBER(4), sname VARCHAR2(30), dob DATE,doa DATE
DEFAULT '10-MAR-13'));
INSERT INTO student VALUES(1,'A','10-MAR-86','21-MAR-13');
INSERT INTO student (sid,sname,dob) VALUES(2,'B','10-APR-85');
COMMIT;
SELECT * FROM student;
sid sname dob doa
1 A 10-MAR-86 21-MAR-13
2 B 10-APR-85 10-MAR-13
The above example specifies that the date of admission of a student is by default the specified
values.
1.2.9.2 Default constraint with Alter statement
Suppose a table has been created without a CHECK constraint and later it was identified to
maintain a CHECK constraint in the table , this can be achieved with the help of ALTER
statement.
Syntax:
ALTER TABLE table2 MODIFY (col1 DATATYPE(size) NOT NULL);
Ex:CREATE TABLE student (sid NUMBER(4),sname VARCHAR2(30),dob DATE, gender
CHAR(1),doa DATE);
ALTER TABLE student MODIFY(doa DATE DEFAULT '10-MAR-13');
The above example specifies by default if the date of admission is not specified the specified
value need to be inserted.
1.2.10 Primary and Unique key differences
2.1. SubQueries
1.1 Objective
• Introduction
• Sub query Types
• Single row sub query
• Multi row sub query
• Multi column sub query
• Co-related sub query
1.2 Course Content
1.2.1 Introduction
• A sub query is a query within a query. The outer query is the main query and the inner query
is called sub query. The inner query is a SELECT statement.
• The sub queries can reside in the WHERE,FROM or SELECT clause.
• A sub query in the WHERE clause of a SELECT statement is called NESTED sub query.
• A sub query in the FROM clause of a SELECT statement is called INLINE VIEW.
• When a sub query is written in WHERE clause , up to 255 levels of sub queries only can be
written.
The purpose of sub queries is :
• To specify the number of records to be inserted into the target table when using CREATE or
INSERT statements.
• To specify the number of records to be assigned to the existing column in an UPDATE
statement.
• To specify the values for conditions in a WHERE and HAVING clauses of the SELECT ,
UPDATE and DELETE statements.
1.2.2 Guidelines
While defining sub queries , certain guidelines need to be followed.
• A sub query must be enclosed within parenthesis.
• A sub query must appear on the right hand side of the operator.
• A sub query must not contain an ORDER BY clause.
1.2.3 Sub query types
Sub queries can be classified into below types based upon the logic used.
• Single row sub query
• Multi row sub query
• Multi column sub query
• Co-related sub query
General Syntax:
SELECT select_list FROM table_name
WHERE col1 WHERE operator
(SELECT select_list FROM table_name);
Consider the below tables
1.2.4 Single row sub query
Single row sub queries returns only one row from the Inner SELECT statement.
The operators that can be used :
= != < <= > >=
Ex:
SELECT * FROM employee WHERE did =
(SELECT did FROM employee WHERE name='RAJU');

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 maximum salaried employee details.


1.2.4.2 Sub query with HAVING clause
Sub query can also be applied in HAVING clause. The inner query is executed first and the
results are returned into the HAVING clause of the outer query. When performing this logic, the
outer queries HAVING clause contains GROUP functions.
Ex:
SELECT did,MIN(salary) FROM employee
GROUP BY did HAVING MIN(salary) >
(SELECT MIN(salary) FROM employee WHERE did=103);

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:

CREATE VIEW v_clerk AS


SELECT empno, ename, deptno, job
FROM emp
WHERE job = 'CLERK'
WITH READ ONLY;
READ ONLY clause on a complex view:
CREATE VIEW v_emp_details AS
SELECT emp.empno, emp.ename, emp.job, emp.deptno, dept.dname, dept.loc FROM emp,
dept WITH READ ONLY;
WITH CHECK OPTION
• The WITH CHECK OPTION clause specifies the level of checking to be done when doing
DML against the view.
• If specified, every row that is inserted, updated or deleted through the view must conform to
the definition of the view.
Ex:
CREATE VIEW v_d20 AS
SELECT ename, sal, deptno FROM emp2 WHERE deptno = 20;
View created.
UPDATE v_d20 SET deptno = 10;
3 rows updated.
The above scenario is, we created a view with dept no 20 details. But we are able to update
the department number in view as 10 contradicting view definition.
To avoid above scenario , we can add with check option to view as shown as follows.
CREATE VIEW d20 AS
SELECT ename, sal, deptno FROM emp2 WHERE deptno = 20
WITH CHECK OPTION;
View created.
UPDATE d20 SET deptno = 10;
ORA-01402: view WITH CHECK OPTION where-clause violation
Force view:
• We can create a view, even if the base object not exists using FORCE keyword.
• The following view will be created even employee table not exists in our schema
Ex:
CREATE FORCE VIEW v_force_view AS
SELECT name ll', 'll job "Employee & Position",
department_id "Department" FROM employee
GROUP BY department_id;
In the above case, the view v_force_view will be created even employee table not existing in
schema.
3.2. Other DBObjects
1. SEQUENCE
1.1 Objective
• Introduction
• Syntax
• Creating Sequence
• Using Sequence
• Altering Sequence
• Dropping sequence
1.2 Course Content
1.2.1 Introduction
• In Oracle, You can populate the number column automatically by using sequences.
• A sequence is an object in Oracle that is used to generate a numeric sequence.
• This can be useful when you need to create a unique number to act as a primary key.
• We also can use sequence to populate unique values in the tables even though tables are
getting used by concurrent users.
• Generates numbers in ascending or descending order
• Provides intervals between numbers
• Independent object, can be used with any table that requires its output.
1.2.2 Creating Sequence
Syntax

CREATE SEQUENCE <sequence_name>


[ INCREMENT BY <integer value>
START WITH <integer value>
MAXVALUE <integer value> / NOMAXVALUE
MINVALUE <integer value> / NOMINVALUE
CYCLE / NOCYCLE
CACHE <integer value> / NOCACHE
ORDER / NOORDER ];
INCREMENT BY -- Interval between sequence numbers. Can be positive or negative but not
zero. If omitted default is 1
MINVALUE --Specifies Sequence minimum value
NOMINVALUE -- Specifies a minimum value of 1 for an ascending sequence or (-10)^26 for a
descending sequence
MAXVALUE -- Specifies maximum value that a sequence can generate
NOMAXVALUE -- Specifies a maximum of (10^27) for an ascending sequence or -1 for a
descending sequence
START WITH -- Specifies first sequence number to be generated.
Sequence minimum value(1) is the default value for ascending sequence where for a descending
sequence is the maximum sequence value.
CYCLE – Sequence continues to generate repeated values after reaching its maximum value
NOCYCLE --Cannot generate more values after reaching the maximum value.
CACHE -- Specifies how many values of a sequence Oracle pre-allocates and keeps in memory
for faster access.
The minimum value for this parameter is 2.
Specifying CACHE will help us in avoids hitting the database every time and improve the
performance.
But we will loose the values from cache memory when server restarts. So there is a chance of
gaps in the sequence values.
NOCACHE -- Values of a sequence are not pre-allocated and hit the database for every next
value of sequence
ORDER -- Guarantees that sequence numbers are generate in the order of request
NOORDER --Does not guarantee the order
Examples

CREATE SEQUENCE test_seq


START WITH 1
INCREMENT BY 1

CREATE SEQUENCE products_seq


MINVALUE 1
MAXVALUE 999999999999999999999999999
START WITH 1
INCREMENT BY 1
CYCLE
CACHE 20;
1.2.3 Using Sequence
Referencing a Sequence in Select statement
SELECT <sequence_name>.NextVal from dual;
SELECT <sequence_name>.CurrVal from dual;
Always in a session, sequence_name.nextval needs to be executed first to initialize the
sequence for that session.
Using a Sequence in INSERT statement to insert unique values
INSERT into
table_name(column1,column2,column3) values(<sequence_name>.NextVal,val2,val3);
1.2.4 Altering Sequence
• With alter statement we can change the sequence parameters.
• The modifications will be applied only new generation numbers.
• The old series of numbers will remain same.

If we want to start the sequence with new value, then old sequence needs to be dropped and
recreated with new start value.

ALTER SEQUENCE customers_seq Maxvalue 1500;


ALTER SEQUENCE customers_seq INCREMENT BY 10;
ALTER SEQUENCE customers_seq CACHE 5;
1.2.5 Dropping Sequence
The syntax to a drop a sequence in Oracle is:

DROP SEQUENCE sequence_name;


Example:
DROP SEQUENCE products_seq;
2. DB LINK
2.1 Objective
• Introduction
• Types of Database Links
• Database Link Restrictions
2.2 Course Content
2.2.1 Introduction
• A database link is a pointer that defines a one-way communication path from an Oracle
Database server to another database server.
• The link pointer is actually defined as an entry in a data dictionary table.
• To access the link, you must be connected to the local database that contains the data
dictionary entry.
• A database link connection is one-way in the sense that a client connected to local database
A can use a link stored in database A to access information in remote database B, but users
connected to database B cannot use the same link to access data in database A.
• If local users on database B want to access data on database A, then they must define a link
that is stored in the data dictionary of database B.

2.2.2 Types of Database Links


Oracle Database lets you create private, public, and global database links. These basic link types
differ according to which users are allowed access to the remote database:
Private database link
This link is more secure than a public or global link, because only the owner of the private link, or
sub programs within the same schema, can use the link to access the remote database.
Public database link
When many users require an access path to a remote Oracle Database, you can create a single
public database link for all users in a database.
Global database link
When an Oracle network uses a directory server, an administrator can conveniently manage
global database links for all databases in the system. Database link management is centralized
and simple.
Syntax:
CREATE PUBLIC DATABASE LINK <name>
CONNECT TO <username> IDENTIFIED BY <password>
USING <Service name>
Examples:
Private DB Link for Private connected user .
CREATE DATABASE LINK sales.us.americas.acme_auto.com USING sales_us';
Private DB Link for fixed connected user .
CREATE DATABASE LINK sales.us.americas.acme_auto.com
CONNECT TO scott IDENTIFIED BY tiger USING 'sales_us';
Public DB Link for Private connected user .
CREATE PUBLIC DATABASE LINK sales.us.americas.acme_auto.com
USING 'sales_us';
Public DB Link for fixed connected user .
CREATE PUBLIC DATABASE LINK sales.us.americas.acme_auto.com CONNECT TO scott
IDENTIFIED BY tiger USING 'sales_us';
2.2.3 Database Link Restrictions
You cannot perform the following operations using database links:
•Grant privileges on remote objects
•Analyze remote objects
•Define or enforce referential integrity
•Grant roles to users in a remote database
3. INDEXES
3.1 Objective
• Introduction
• Creation Of Index
• Advantages Of Indexes
• Disadvantages Of Indexes
• Index Selection Strategy
• Bitmap Index
• Function Based Index
• Renaming And Dropping Index
3.2 Course Content
3.2.1 Introduction
An Index is a database object that will be created to optimize the query performance and to
get the sql results in lesser time.

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.

3.2.2 Creation Of Index


The syntax for creating a index is:
CREATE [UNIQUE] INDEX index_name
ON table_name (column1, column2, ... column_n);
UNIQUE keyword is optional and it indicates that the combination of values in the indexed
columns must be unique.
The index we are creating with above declaration is called BTREE index.
Example:
CREATE INDEX products_idx ON products (product_name);
In this example, we've created an index on the products table called products_idx. It consists of
only one field - the product_name field.
We could also create an index with more than one field as in the example below:
CREATE INDEX products_idx ON products (product_name, city);
3.2.3 Advantages Of Indexes
Indexes improve the query performance by avoiding the full table scans.
Indexes are very useful with the tables having large amounts of data.
3.2.4 Disadvantages Of Indexes
The cost of DML operations on the base table increases because of index.
As index is separate database object, on inserting new data or on updating of data the changes
needs to be reflected in the table as well as in the index object.
So if we issue one insert statement on base table, oracle fires another insert statement internally
to insert the data into index.
So always we should be judicious on creating an index on a table. The gain we are getting in the
retrieving data should be more compared to the loss of time we are incurring in DML operations.
3.2.5 Index Selection Strategy
The following check points needs to be considered before creating index on a column.
• The column is queried frequently.
• The table data is not getting modified so frequently.
• The column should contain more no of distinct values.
• The column should not part of primary key or unique key.
• One column can have only one index. So If a column is already having index then we will be
not able to create one more index on it.
3.2.6 Bitmap Index
If we need to create an index on a column having less number of distinct values, then we should
create bitmap index.
Consider gender column in employee table. Even though employee table contains 3,00,000
rows, if we select distinct gender values we only get 2 values. So on these type of columns we
can create bitmap indexes.
Bitmap indexes are more used in data warehousing environments.

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:

sqlldr username@oracledb / password control=/home/u495298/employee.ctl

1.2.3 SQL *LOADER Control file Examples

Loading Comma Separated File:


DATA:
100,Thomas,Sales,5000
200,Jason,Technology,5500
300,Mayla,Technology,7000
400,Nisha,Marketing,9500
500,Randy,Technology,6000
501,Ritu,Accounting,5400
Employee.ctl
load data
infile '/home/u495298/employee.txt'
into table employee
fields terminated by ","
( id, name, dept, salary )
Loading Fixed Length File:
DATA
200JasonTechnology5500
300MaylaTechnology7000
400NishaTechnology9500
500RandyTechnology6000
Employee-fixeed.ctl
load data
infile '/home/u495298/employee-fixed.txt'
into table employee
fields terminated by ","
( id position(1:3), name position(4:8), dept position(9:18), salary position(19:22) )
Manipulating Data While Loading:
load data
infile '/home/u495298/employee.txt'
into table employee
fields terminated by ","
( id ":id+99",
name "upper(:name)",
dept ,
salary
)

Loading From Multiple Files:


load data
infile '/home/u495298/employee.txt'
infile '/home/u495298/newemployee.txt'
into table employee
fields terminated by ","
( id, name, dept, salary )
Loading Multiple Tables:
load data
infile '/home/u495298/employee-bonus.txt'
into table employee
( id position(1:3),
name position(5:10),
dept position(12:21),
salary position(23:26))
into table bonus
( id position(1:3),
bonus position(28:31))
Loading Specific Data:
DATA
100,Thomas,Sales,5000
200,Jason,Technology,5500
300,Mayla,Technology,7000
400,Nisha,Marketing,9500
500,Randy,Technology,6000
501,Ritu,Accounting,5400
Control file
load data
infile '/home/u495298/employee.txt'
into table employee
when dept = 'Technology'
fields terminated by ","
( id, name, dept, salary )
Appending Data To Existing Table:
DATA:
600,Sandy,Technology,9000
701,Situ,Accounting,7400
Employee.ctl
load data
infile '/home/u495298/employee.txt'
append
into table employee
fields terminated by ","
( id, name, dept, salary )
4.1. Introduction
1.1 Objective
• Introduction to PL/SQL
• Purpose
• Advantages
• Data types
• Basic Syntax
• Pl/Sql Program Types
• Operators
• Conditional Statements
1.2 Course Content
1.2.1 Introduction to PL/SQL
• PL/SQL is a completely portable, high-performance transaction-processing language.
• PL/SQL provides a built-in interpreted and OS independent programming environment.
• PL/SQL can also directly be called from the command-line SQL*Plus interface.
• Direct call can also be made from external programming language calls to database.
• PL/SQL's general syntax is based on that of ADA and Pascal programming language.
1.2.2 Features of PL/SQL
• PL/SQL is tightly integrated with SQL.
• PL/SQL offers extensive error checking.
• PL/SQL offers numerous data types.
• PL/SQL offers a variety of programming structures.
• PL/SQL supports structured programming through functions and procedures.
• PL/SQL supports object-oriented programming.
1.2.3 Advantages of PL/SQL
• PL/SQL supports both static and dynamic SQL. Static SQL supports DML operations and
transaction control from PL/SQL block. Dynamic SQL is SQL allows embedding DDL statements
in PL/SQL blocks.
• PL/SQL allows sending an entire block of statements to the database at one time. This
reduces network traffic and provides high performance for the applications.
• PL/SQL gives high productivity to programmers as it can query, transform, and update data in
a database.
• PL/SQL saves time on design and debugging by strong features, such as exception handling,
encapsulation, data hiding, and object-oriented data types.
• Applications written in PL/SQL are fully portable.
• PL/SQL provides high security level.
• PL/SQL provides access to predefined SQL packages.
• PL/SQL provides support for Object-Oriented Programming.
• PL/SQL provides support for Developing Web Applications and Server Pages.
1.2.4 Data types & Variable Declaration
PL/SQL Data Types come under the following categories:
Date Type Description
Numeric Numeric values on which arithmetic operations are performed. Ex:
INTEGER,NUMBER(3,2),NUMBER
Character Alphanumeric values that represent single characters or strings of characters. Ex:
CHAR,VARCHAR,VARCHAR2(10)
Boolean Logical values on which logical operations are performed. Ex: BOOLEAN
Datetime Dates and times. Ex: DATE,YEAR,MONTH,HOUR,TIMEZONE_MINUTE
• A variable is nothing but a name given to a storage area that our programs can manipulate.
• The name of a PL/SQL variable consists of a letter optionally followed by more letters,
numerals, dollar signs, underscores, and number signs and should not exceed 30 characters.
• variable names are not case-sensitive and you cannot use a reserved PL/SQL keyword as a
variable name.
Syntax :
variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT initial_value]
EX:
sales number(10, 2);
name varchar2(25);
address varchar2(100);
Initializing Variables in PL/SQL
• Whenever you declare a variable, PL/SQL assigns it a default value of NULL.
• If you want to initialize a variable with a value other than the NULL value, you can do so
during the declaration using DEFAULT or Assignment Operator
Ex:
counter binary_integer := 0;
greetings varchar2(20) DEFAULT 'Have a Good Day';
• INTO Clause will be used to assign values from tables to PL/SQL variables.
• For each item in the SELECT list, there must be a corresponding, type- compatible variable
in the INTO list.
Ex:
SELECT ename,deptno INTO v_name,v_no FROM Employee.
1.2.5 Basic Syntax
• PL/SQL is a block-structured language, meaning that PL/SQL programs are divided and
written in logical blocks of code.
• Each block consists of three sub-parts as shown below:
DECLARE
<declarations section> (optional)
BEGIN
<executable command(s)>
EXCEPTION
<exception handling> (optional)
END;
Ex:
DECLARE
message varchar2(20):= 'Hello, World!';
BEGIN
dbms_output.put_line(message);
END;
/
1.2.6 PL/SQL Program Types
Basically we have two types of PL/SQL blocks
Unnamed Blocks: Anonymous block
Named Blocks: Function, Procedure,Package,Trigger
1.2.7 Operators
The following operators are supported in PL/SQL.
Arithmetic operators : +,,*,/,**
Relational operators : =,<>,>,<,<=,>=,
Comparison operators : LIKE,BETWEEN,NULL,IN
Logical operators : AND,OR,NOT
1.2.8 Conditional Statements
Pl/Sql supports IF-THEN,IF-ELSE-THEN,IF-THEN-ELIF statements as condition statements.
Ex:
DECLARE
a number(2) := 10;
BEGIN
a:= 10;
-- check the boolean condition using if statement
IF( a < 20 ) THEN
-- if condition is true then print the following
dbms_output.put_line('a is less than 20 ' );
END IF;
dbms_output.put_line('value of a is : ' || a);
END;
/
Ex:
DECLARE
a number(3) := 100;
BEGIN
-- check the boolean condition using if statement
IF( a < 20 ) THEN
-- if condition is true then print the following
dbms_output.put_line('a is less than 20 ' );
ELSE
dbms_output.put_line('a is not less than 20 ' );
END IF;
dbms_output.put_line('value of a is : ' || a);
END;
Ex:
DECLARE
a number(3) := 100;
BEGIN
IF ( a = 10 ) THEN
dbms_output.put_line('Value of a is 10' );
ELSIF ( a = 20 ) THEN
dbms_output.put_line('Value of a is 20' );
ELSIF ( a = 30 ) THEN
dbms_output.put_line('Value of a is 30' );
ELSE
dbms_output.put_line('None of the values is matching');
END IF;
dbms_output.put_line('Exact value of a is: '|| a );
EN D ;
4.2. Control Structures
1.1 Objective
• Introduction
• Composite data types
• Control structures types
• Conditional Control structures
1.2 Course Content
1.2.1 Introduction
There may be situation that , a block of code need to be executed number of times. In order to
meet the real time scenarios branching, selection and looping are required. Control structures
are the most important PL/SQL extensions of SQL.
Consider the below tables
Employee

1.2.2 Composite Data types


Each value in ORACLE is manipulated by a data type. The data type associates a fixed set of
properties with that values stored. The data type defines the domain of values that each column
can contain.
Normally , a PL/SQL variable is closely tied to a table column and uses the same data type. But
whenever the data type of the specified column is changed , then program need to make a
change for the data type specified in the variable declaration which is linked with this column. To
get this independence , composite data types are defined.
A) %TYPE :- Used to declare the scalar PL/SQL variables those inherit the specification of
specific columns of database table, on a view or even a synonym. Its notation is:
< Table_Name> . <Col_Name> % TYPE; Ex:
DECLARE
empno NUMBER(3);
emp_name employee.name%TYPE;
sal employee.salary%TYPE;
BEGIN
eno := &eno;
SELECT name, salary INTO emp_name, sal FROM employee WHERE
eno=empno;
DBMS_OUTPUT.PUT_LINE(emp_name);
DBMS_OUTPUT.PUT_LINE(salary); END;
B) %ROWTYPE :- Used to declare a structured variable in PL/SQL block, which is referring the
entire structure of a table or a view or synonym or cursor. Structured variable is a variable having
some internal components each of one scalar type. These internal variables of structured
variables are called as elementary variables. The structured variables in PL/SQL are called as
Record Type variables. Its notation is:
< Table_Name> % ROWTYPE; Ex:
DECLARE
rs employee%ROWTYPE;
BEGIN
SELECT * INTO rs FROM employee WHERE eno=&eno;
DBMS_OUTPUT.PUT_LINE(rs.name ||rs.salary); END;
1.2.3 Control structures types
PL/SQL helps us manipulate and process Oracle data using
• Conditional Statements
• Iterative Statements
• Sequential
1.2.4 Conditional control structures
Conditional control structures allows to control the flow of the execution of the program based on
a condition. In programming terms, it means that the statements in the program are not executed
sequentially. Rather, one group of statements, or another will be executed, depending on how
the condition is evaluated.

Conditional Control structures are of two types


IF
CASE
1.2.4.1 CASE statement
The CASE statement selects one sequence of statement to execute similar to IF. The expression
is evaluated once and its value is matched with several blocks whichever block matches first ,
that is evaluated.
Syntax:
CASE selector
WHEN expression1 THEN Statement 1;
WHEN expression2 THEN Statement 2;
ELSE
Statement n; END CASE;
The reserved word CASE marks the beginning of the CASE statement.
The 'selector' is a value that determines , which WHEN clause should be executed. It is
evaluated only once for the whole selection process.
Each WHEN clause contains an expression and one or more executable statements associated
with it.
The ELSE clause is an optional statement.
Ex:
DECLARE
grade CHAR(1):=UPPER('&p_grade'); appraisal VARCHAR2(20);
BEGIN appraisal:= CASE v_grade
WHEN 'A' THEN
DBMS_OUTPUT.PUT_LINE ('Excellent');
WHEN 'B' THEN
DBMS_OUTPUT.PUT_LINE ('Very Good');
WHEN 'C' THEN
DBMS_OUTPUT.PUT_LINE ('Good');
WHEN 'D' THEN
DBMS_OUTPUT.PUT_LINE ('Fair');
WHEN 'E' THEN
DBMS_OUTPUT.PUT_LINE ('Poor');
ELSE
DBMS_OUTPUT.PUT_LINE ('No such grade'); END CASE;
DBMS_OUTPUT.PUT_LINE('Grade:'||grade||'appraisal:'||appraisal); END;
1.2.5 Iterative control statements
There may be a situation a block of code need to be executed several number of times. In
general, statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on.

Iterative Control structures are of three types


a.Simple LOOP
b.WHILE Loop
b.FOR Loop
1.2.5.1 The Loop control statements
Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed. PL/SQL supports the
following control statements. Labelling loops also helps in taking the control outside a loop.
A) EXIT statement :- The Exit statement completes the loop and control passes to the statement
immediately after END LOOP. When the EXIT statement is encountered inside a loop, the loop is
immediately terminated and program control moves to the next statement following the loop. If
nested loops are used the EXIT statement will stop the execution of the inner loop and starts
executing the next line of program after the block.
Syntax:
EXIT;
The EXIT-WHEN statement allows the condition in the WHEN clause to be evaluated. If the
condition is true, the loop completes and the control moves to the statement immediately after
END LOOP. Until the condition is true, the EXITWHEN statement acts like a NULL statement,
except for evaluating the condition, and does not terminate the loop.
Syntax:
EXIT WHEN condition;
B) CONTINUE statement :- Causes the loop to skip the remainder of its body and immediately
retests its condition prior to reiterating.
1.2.5.2 Simple LOOP- END LOOP
The simplest form of LOOP statement is the basic (or infinite) loop, which encloses a sequence
of statements between the keywords LOOP and END LOOP.
Syntax:
LOOP
Statements;
EXIT [WHEN <condition>];
END LOOP;
EXIT statement is used to terminate a LOOP. Once the LOOP is terminated , the control passes
to the next statement after the END LOOP.
EXIT can be issued either as an 'action' within an IF statement or as a stand alone statement
within the LOOP.
Ex:
DECLARE
a number:=100;
BEGIN
LOOP a:=a+25; EXIT when a=250;
END LOOP;
DBMS_OUTPUT.PUT_LINE(a); END;
Ex:
DECLARE
num NUMBER(1) := 1;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE('The Line ' || num || ' Output is '|| num);
num := num + 1;
IF num>5 THEN EXIT;
END IF;
END LOOP;
DBMS_OUTPUT.PUT_LINE('Total lines of output are ' || (num-1));
END;
1.2.5.2.1 Nested loops and labels
Loops can be nested to multiple levels.
All the loops can be nested into one another.
Loops can be labelled as per the requirement.
A label is placed before the statements either on the same line or on a before line.
When the loop is labelled , the label name can be optionally included after the END LOOP
statement for clarity.
Ex:
DECLARE
num NUMBER(3):=1; BEGIN
<< OuterLoop >> LOOP
<< InnerLoop >>
LOOP
EXIT WHEN num>5;
DBMS_OUTPUT.PUT_LINE(' Inner loop : ' || num); num := num + 1;
END LOOP InnerLoop;
DBMS_OUTPUT.PUT_LINE(' Outer loop : ' || num); num := num + 1; EXIT WHEN num > 10;
END LOOP OuterLoop;
END;
1.2.5.3 WHILE Loop
The WHILE-LOOP statement executes the statements in the loop body as long as condition is
true.
Syntax:
WHILE <condition>
LOOP
Statements; END LOOP;
Before each iteration of the LOOP, the condition is evaluated.
If it is TRUE , statements are executed , then control resumes at the top of the loop.
If it is FALSE , the loop is skipped and control passes to the next statement.
Ex:
DECLARE
num1 NUMBER(4):=&num1;
num2 NUMBER(4):=1;
BEGIN
WHILE (num2<=num1)
LOOP
DBMS_OUTPUT.PUT_LINE(num2); num2:=num2+1;
END LOOP; END;
1.2.5.4 FOR Loop
The FOR Loop executes for a specified number of times, defined in the loop definition. Simple
FOR loops iterate over a specified range of integers. The number of iterations is known before
the loop is entered.
Syntax:
FOR counter IN lower_bound .. upper_bound
LOOP
Statements;
END LOOP;
A double dot (..) serves as the range operator. The range is evaluated when the FOR loop is first
entered and is never re-evaluated. After each iteration, the loop counter is incremented.
The initial step is executed first, and only once. This step allows you to declare and initialize any
loop control variables.
Next, the condition, i.e., lower_bound .. upper_bound is evaluated. If it is TRUE, the body of the
loop is executed. If it is FALSE, the body of the loop does not execute and flow of control jumps
to the next statement just after the FOR loop.
After the body of the FOR loop executes, the value of the counter variable is increased or
decreased.
The condition is now evaluated again. If it is TRUE, the loop executes and the process repeats
itself . After the condition becomes FALSE, the FORLOOP terminates.
Ex:
BEGIN
FOR i IN 1..10
LOOP
DBMS_OUTPUT.PUT_LINE(i);
END LOOP;
END;
1.2.5.5 Reverse FOR loop
By default, iteration proceeds from the lower_bound to the upper_bound. This order can be
reversed by using the REVERSE keyword. In such case, iteration proceeds the other way. After
each iteration, the loop counter is decremented.
Syntax:
FOR counter REVERSE IN lower_bound .. upper_bound
LOOP
Statements; END LOOP;
Ex:
DECLARE
str VARCHAR2(200);
BEGIN
FOR i IN REVERSE 1..50
LOOP
str:=str||' '||i;
END LOOP;
DBMS_OUTPUT.PUT_LINE(str); END;
1.2.6 Sequential control structures
The sequence control structure simply executes a sequence of statements in the order in which
they occur.

Sequential control structures are of three types:


GOTO
NULL
1.2.6.1 GOTO statement
GOTO provides the ability to jump through a program from one place to another.
It is better to have a limited usage of GOTO in program code.
When a jump is proposed using GOTO , it is associated with an appropriate label.
The GOTO statement branches to a label unconditionally.
The label must be unique within its scope and must precede an executable statement.
When executed, the GOTO statement transfers the control to the labelled statements or block.
The labelled statement or block can be down or up in the sequence of statements.
The labels are enclosed between angular brackets << and >>
Syntax: GOTO label_name;
Ex:
DECLARE
num NUMBER(2) := 1;
BEGIN LOOP num := num+1; IF num > 5 THEN
GOTO 1_ENDOFLOOP; -- print num 5 times
END IF;
DBMS_OUTPUT.PUT_LINE('value = ' || );
END LOOP;
<<1 _ENDOFLOOP >> END;
PL/SQL enforces some restrictions while using GOTO.
It is illegal to use GOTO to branch into:
an inner block
a loop
an IF statement
an exception
1.2.6.2 NULL statement
Sometime PL/SQL requires a code statement when we do not have anything to execute. This is
the place where we can use NULL statement. The NULL statement does nothing, and passes
control to the next statement.
Syntax:
NULL;
Ex:
DECLARE
num NUMBER(3) := 5;
BEGIN
GOTO then_clause; num := 3; << then_clause >>
NULL; END;
4.3. Cursors
1.1 Objective
• Introduction
• Types Of Cursors
• Implicit Cursors
• Explicit Cursors
• Explicit Cursor Functions
• Controlling Explicit Cursors
• Cursor For Loops
• Parametrized Cursor
1.2 Course Content
1.2.1 Introduction
Oracle creates a memory area, known as context area, for processing an SQL statement, which
contains all information needed for processing the statement, for example, number of rows
processed, etc.
A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor.
Cursor contains information on a select statement and the rows accessed by it. This temporary
work area is used to store the data retrieved from the database and manipulate this data.
The set of rows the cursor holds is referred to as the active set.
1.2.2 Types Of Cursors
There are two types of cursors:
Implicit Cursors –
These are declared by PL/SQL implicitly for all DML and PL/SQL Select statements.
Explicit Cursors –
For Queries that return more than one row,explicit cursors are declared and managed by the
programmer and manipulated through specific statements in the blocks executable actions.

1.2.3 Implicit Cursors


Implicit cursors are automatically created by Oracle whenever an SQL statement is executed,
when there is no explicit cursor for the statement.
Programmers cannot control the implicit cursors and the information in it.
Whenever a DML statement (INSERT, UPDATE and DELETE) or SELECT INTO statement is
issued an implicit cursor is associated with this statement.
For INSERT operations, the cursor holds the data that needs to be inserted.
For UPDATE and DELETE operations, the cursor identifies the rows that would be affected.
In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which always has
the attributes like %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT.

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] ;

• Function-name specifies the name of the function.


• CREATE OR REPLACE option allows create a new function or modifying an existing
function.
• The optional parameter list contains name, mode and types of the parameters.
• The function must contain a return statement.
• RETURN clause specifies that data type you are going to return from the function.
• The AS keyword is used instead of the IS keyword for creating a standalone function.
• Function-body contains the executable part and at the end it contains return statement
returning the value.
Return Type:
The header section defines the return type of the function.
The return data type can be any of the oracle data type like VARCHAR, NUMBER etc.
The execution and exception section both should return a value which is of the data type defined
in the header section.
We can use cursors, conditional statements and loops in functions also.
We also can use exception techniques that we learnt in anonymous blocks in functions.
Example1:
CREATE or REPLACE FUNCTION func1(a number)
RETURN number
AS
b number;
c number;
BEGIN
b:=&num;
c:=a+b;
RETURN c;
END;
Example2:
CREATE OR REPLACE FUNCTION employer_details_func(p_id number)
RETURN VARCHAR IS
emp_name VARCHAR(20);
BEGIN
SELECT first_name INTO emp_name
FROM employee WHERE empid = p_id;
RETURN emp_name;
10> END;
/
1.2.7 Execution
A function can be executed in the following ways.
1) we can invoke the function using blocks , by defining a variable to catch the return value.
DECLARE
employee_name varchr2(30);
v_dept_id number
BEGIN
v_dept_id := 20;
employee_name := employer_details_func(v_dept_id);
dbms_output.put_line('employee name is -->'||employee_name)
END;
/
2) As a part of a SELECT statement
SELECT dept_id,employer_details_func(dept_id) FROM employee where dept_id = 20 ;
3) In a PL/SQL Statements.
dbms_output.put_line(employer_details_func(20));
This line displays the value returned by the function.

S-ar putea să vă placă și