Sie sind auf Seite 1von 81

SQL

SQL is an ANSI (American National Standards Institute) standard computer


language for accessing and manipulating database systems.

SQL works with database programs like MS Access, DB2, Informix, MS SQL
Server, Oracle, Sybase, etc.
What is SQL?

SQL stands for Structured Query Language

SQL allows you to access a database

SQL is an ANSI standard computer language

SQL can execute queries against a database

SQL can retrieve data from a database

SQL can insert new records in a database

SQL can delete records from a database

SQL can update records in a database

SQL is easy to learn

What is SQL?

SQL is based on Dr. E. F. Codds relational model

Originally developed by IBM

Pronounced as SEQUEL
Oracle SQL
Oracle has enhancements to the basic SQL engine. These
enhancement include the following:
PL/SQL is the procedural portion. It combines SQL and a procedural language. It
is incorporated into SQL engine

*Plus is report formatting commands, environment commands, etc. It is also


incorporated into SQL engine.

The first commercially available SQL relational DBMS was


introduced in 1979 by Oracle Corporation.

SQL command Groups

Data Retrieval

DDL -data definition language

DML-data manipulation language

DCL- data control language

TCL- transaction control language

Data Retrieval
SELECT:
used to retrieve the data present in the database tables

Data Definition Language (DDL)

CREATE

: to create a new data structure.

ALTER

: to change an existing data structure.

DROP

TRUNCATE : to remove all rows from table

RENAME

: to remove an entire data structure.

: to rename existing table

Data Manipulation Language (DML)

INSERT: to add records into the table

UPDATE: to change column value in the table

DELETE: to remove rows from the table

MERGE: to update & insert contents of one


Data Control Language (DCL)

GRANT :Allow access privileges to users (e.g. select, insert, update, alter, delete,
etc to nominated tables or attribute in tables)

REVOKE: Revoke or cancel access privileges

Transaction Control Language (TCL)

COMMIT :Save or enable DML changes to the database.

ROLLBACK: To undo DML changes till in a transaction

SAVEPOINT: To divide a transaction


Data Types

Data Types

Data Types
The Basic Select Statement
Writing SQL Statements

SQL statements are not case sensitive

SQL statements can be on one or more lines

Keywords cannot be abbreviated or split across lines

Clauses are usually placed on separate lines

Indents are used to enhance readability


SELECT Statement

The SELECT statement is used to select data from a table. The tabular result is
stored in a result table (called the result-set).
Syntax
SELECT <column_name(s)>
FROM <table_name>
Selecting Columns
All Columns
SELECT *
FROM departments;
Specific Columns
SELECT department_id,location_id
FROM departments;
Example
Changing the column order
SELECT FirstName, LastName
FROM Persons
Selecting all coloumns
The SELECT DISTINCT Statement
SELECT DISTINCT Company FROM Orders
Orders
Restricting and Sorting Data
The WHERE Clause
Character Strings and Dates

Are enclosed in single quotation marks


Character values are case sensitive
Date values are format sensitive
The default date format is DD-MON-RR
Example :

SELECT last_name, job_id, department_id


FROM employees
WHERE last_name = Whalen ;
Where
SQL Arithmetic Operators:
SQL Range Operators
Examples
SELECT ename, sal FROM emp
WHERE sal < 2500 ;
SELECT ename, sal FROM emp
WHERE sal > 2500 ;
SELECT ename, sal FROM emp
WHERE sal <= 2500 ;
SELECT ename, sal FROM emp
WHERE sal >= 2500 ;
SQL Equality Operators
Examples

SELECT ename, sal


FROM emp
WHERE dept = admin ;

SELECT ename, sal


FROM emp
WHERE dept <> admin ;

Comparison Operators

Use the LIKE condition to perform wildcard searches of valid search string values
% denotes zero or many characters
_ denotes one character (underscore)
Examples

BETWEEN..AND operator
SELECT ename, sal FROM emp
WHERE sal BETWEEN 2500 AND 3500;

IN operator
SELECT empno, ename, sal FROM emp
WHERE mgr IN (100, 101, 201);

LIKE operator
SELECT ename FROM
emp
WHERE ename LIKE S% ;

IS NULL operator

SELECT ename, mgr FROM emp


WHERE comm IS NULL;
SQL Logical Operators
Examples
SELECT *
FROM emp
WHERE dept = admin AND sal > 5000;
SELECT *
FROM emp
WHERE dept = admin or dept = CS;
Using the AND Operators
AND requires both conditions to be true
SELECT employee_id, last_name, job_id, salary
FROM employees
WHERE salary >=10000 AND job_id LIKE %MAN% ;
Using the OR operator
OR requires either condition to be true
SELECT employee_id, last_name, job_id, salary
FROM employees
WHERE salary > 10000 OR job_id LIKE %MAN% ;
Using the NOT Operator
To negate the result we use the NOT Operator
SELECT last_name, job_id
FROM employees
WHERE job_id NOT IN ( IT_PROG, ST_CLERK );
Rules of Precedence
ORDER BY Clause

Sort rows with the ORDER BY clause


- ASC : Ascending order, default
- DESC : Descending order
Syntax :
SELECT expr,column(s)
FROM table
[WHERE condition(s)]
[ORDER BY {column, expr} [ASC|DESC] ] ;
Sorting (Examples)

SELECT last_name, job_id, department_id, hire_date

FROM
employees
ORDER BY hire_date ;
SELECT last_name, job_id, department_id, hire_date
FROM employees
ORDER BY hire_date DESC ;
Sort order can be specified by position value also

SELECT last_name, job_id, department_id, hire_date


FROM employees
ORDER BY 3 DESC ;

Sorting (Examples)

Sorting by Column Alias


SELECT employee_id, last_name, salary*12 annsal
FROM employees
ORDER BY annsal ;

Sorting by Multiple Columns


- we can use multiple columns in the ORDER BY clause
- The order of ORDER BY list is the order of sort
SELECT last_name, department_id, salary
FROM employees
ORDER BY department_id, salary DESC;

Summary
In this lesson, you learned about :

SQL

SQL Data Types

The Basic Select Statement

Use the WHERE clause to restrict rows of output


- use the comparison conditions
- use the BETWEEN..AND.. , IN , LIKE , and NULL
conditions
- Apply the logical AND, OR, and NOT operators

Use the ORDER BY clause to sort rows of output

What is Data?

Data (plural of the word Datum) - Data is a factual information used as a basis
for reasoning, discussion, or calculation
Data may be numerical data which may be integers or floating point numbers, and
non-numerical data such as characters, date and etc. Data by itself normally doesnt have
a meaning associated with it.
e.g:Krishnan
01-Jan-71
15-Jun-05
50000
Information
Related data is often called as information. Information will always have a meaning
and context attached to the data element. Let us consider the same example that we
gave for data. When we add meaning and context to the data it becomes information:

Employee Name: Krishnan


Date of Birth: 01-Jan-71
Data of Joining: 15-Jun-05
Salary: 50000
Department Number: 10
Database

A logically coherent collection of related data (information) with inherent meaning,


built for a certain application, and representing a subset of the "real-world".
For e.g. a customer database in your bank, details of the insurance policies that we
hold etc.
Evolution of Databases
File Systems (1950s)

Basic Constructs
Sequential records
A record contains sequential fields

Relies on indexes for random access


ISAM (Index Sequential Access Method)
VSAM (Virtual Storage Access Method)

Basic operation
Open, close, or reset a file
Read, write or delete a record
Disadvantages of File processing system

Data redundancy and inconsistency

Difficulty in accessing data

Data isolation

Integrity problems

Atomicity problem
Concurrent access anomalies
Security problems

Hierarchical Model (1960s)

Data are represented by collection of records and the relationship among data are
represented by links, which can be viewed as pointers.

A record is a collection of fields (attributes), each of which contains only one data

value.

A link is an association between precisely two records.

Records are organized as collection of rooted trees.


Hierarchical Model

Again consider the database representing a customer-account relationship in a


banking system. There are two record types, customer and account.

type customer = record


customer name: string;
customer street: string;
customer city: string;
end

The account record type can be defined as


type account = record
account number: string;
balance: integer;
end

Hierarchical Model
Network Model (1960s)

Data are represented by collection of records and the relationship among data are
represented by links, which can be viewed as pointers.

Record is a collection of fields (attributes), each of which contains only one data

Link is an association between precisely two records.

Records are organized as arbitrary graphs.


Network Model

consider a database representing a customer-account relationship in a banking


system. There are two record types, customer and account.

type customer = record


customer name: string;
customer street: string;
customer city: string;
end

The account record type can be defined as


type account = record
account number: string;
balance: integer;
end

Network Model
Relational Model (1980s)

Data is presented as a collection of relations

Each relation is depicted as a table

Columns are attributes

Rows ("Tuples") represent entities

Every table has one or more set of attributes that taken together as a "key"
uniquely identifies each entity
Customer
Account
Relational Model
Relationship is established with the help of keys
Database Management System
(DBMS)

A database management system (DBMS) is software that allows databases to be


defined, constructed, and manipulated.
A collection of programs that enables you to store, modify, and extract
information from a database.

The general purpose of a DBMS is to provide for the definition, storage, and
management of data in a centralized area that can be shared by many users.

Purpose of a DBMS
DBMS developed to handle the following difficulties:

Data redundancy and inconsistency


Difficulty in accessing data
Data isolation - multiple files and formats
Integrity problems
Atomicity of updates
Concurrent access by multiple users
Security problems

Functionality of a DBMS

Specifying the database structure


data definition language

Manipulation of the database


query processing and query optimization

Integrity enforcement
integrity constraints

Concurrent control
multiple user environment

Crash recovery

Security and authorization


DBMS Approach
Object-Based Logical
Models

Data Models
Record-Based Logical
Models

Physical Data
Models

The Entity-Relationship Model


Relational Model
Model
The Object-Oriented Model
Network Model
Model
The Semantic Data Model
Hierarchical Model
The Functional Data Model
Data independence

capability of changing a database scheme without having


to change the scheme at the next higher level

two level of data independence

Unifying
Frame-Memory

Data Abstraction

Physical Level describes how data are actually stored

Logical Level describes what data are stored

View Level
describes only a part of the database useful for a particular user
Database Languages

data definition language (DDL) :


specify the conceptual database scheme

data manipulation language (DML): query language


used to retrieve and update information in a database

host language:

a conventional high level language used to write application programs

DBMS Structure
Relations
Relations
Relations
Codds Rule for RDBMS
Rule 1: The Information Rule
All data should be presented to the user in table form
Rule 2: Guaranteed Access Rule
All data should be accessible without ambiguity.
This can be accomplished through a combination
of the table name, primary key, and column name.
Rule 3: Systematic Treatment of Null Values
A field should be allowed to remain empty. This
involves the support of a null value, which is distinct
from an empty string or a number with a value of
zero. Of course, this can't apply to primary keys. In
addition, most database implementations support the
concept of a not null field constraint that prevents null
values in a specific table column.
Rule 4: Dynamic On-Line Catalog Based on the Relational Model
A relational database must provide access to its structure
through the same tools that are used to access the data.
This is usually accomplished by storing the structure
definition within special system tables.

Rule 5: Comprehensive Data Sub-language Rule


The database must support at least one clearly defined
language that includes functionality for data definition, data
manipulation, data integrity, and database transaction
control. All commercial relational databases use forms of
the standard SQL (Structured Query Language) as their
supported comprehensive language.
Rule 6: View Updating Rule
Data can be presented to the user in different logical
combinations, called views. Each view should support the
same full range of data manipulation that direct-access to a
table has available. In practice, providing update and delete
access to logical views is difficult and is not fully supported
by any current database.
Rule 7: High-level Insert, Update, and Delete
Data can be retrieved from a relational database in sets
constructed of data from multiple rows and/or multiple
tables. This rule states that insert, update, and delete
operations should be supported for any retrievable set
rather than just for a single row in a single table.
Rule 8: Physical Data Independence
The user is isolated from the physical method of storing and
retrieving information from the database. Changes can be
made to the underlying architecture ( hardware, disk
storage methods ) without affecting how the user accesses
it.
Rule 9: Logical Data Independence
How a user views data should not change when the logical
structure (tables structure) of the database changes. This
rule is particularly difficult to satisfy. Most databases rely on
strong ties between the user view of the data and the actual
structure of the underlying tables.
Rule 10: Integrity Independence
The database language (like SQL) should support
constraints on user input that maintain database integrity.
This rule is not fully implemented by most major vendors.
At a minimum, all databases do preserve two constraints
through SQL.
-- No component of a primary key can have a null value
-- If a foreign key is defined in one table, any value in it must exist as

a primary key in another table


Rule 11: Distribution Independence
A user should be totally unaware of whether or not the
database is distributed (whether parts of the database exist
in multiple locations). A variety of reasons make this rule
difficult to implement; I will spend time addressing these
reasons when we discuss distributed databases.
Rule 12: Non-subversion Rule
There should be no way to modify the database structure
other than through the multiple row database language (like
SQL). Most databases today support administrative tools
that allow some direct manipulation of the data Structure.
Functional dependency
Given a relation R, a set of attributes X in R is said to
functionally determine another attribute Y, also in R, (written
X Y) if and only if each X value is associated with at most
one Y value. Customarily we call X the determinant set and Y
the dependent attribute.
Properties of functional dependencies
Given that X, Y, and Z are sets of attributes in a relation R, one can derive several
properties of functional dependencies. Among the most important are Armstrong's
axioms

Reflexivity: If Y is a subset of X, then X Y


Augmentation: If X Y, then XZ YZ
Transitivity: If X Y and Y Z, then X Z

Closure of a set of Functional Dependencies


Given a set F of functional dependencies, there are certain other functional
dependencies that are logically implied by F.

The set of all functional dependencies logically implied by F is the closure of F


denoted by F+.

F+ can be found by applying Armstrongs Axioms:

Closure of a set of Functional Dependencies

We can further simplify the computation of F+ by using additional


rules:

Closure of a set of Functional Dependencies(example)


R=(A, B, C, G, H, I)
F= { A ---- > B
A ---- > C
CG ---- > H
CG ---- > I
B ---- > H }
Some members of F+:
A ---- > H (transitivity A ---- > B, B ---- > H)
AG ---- > I (pseudotransitivity A ---- > C, CG ---- > I)
CG ---- > HI (union CG ---- > H, CG ---- > I)
NORMALIZATION
Normalization
First Normal Form (1 NF)
1 NF Anomalies
contains redundant data. For example, information about the
supplier's location and the location's status have to be
repeated for every part supplied.
Redundancy causes what are called update anomalies.
INSERT. The fact that a certain supplier (s5) is located in a particular city
(Athens) cannot be added until they supplied a part.

DELETE. If a row is deleted, then not only is the information about quantity and
part lost but also information about the supplier.

UPDATE. If supplier s1 moved from London to New York, then six rows would
have to be updated with this new information.

Second Normal Form (2 NF)


2 NF

functional dependencies in the First table:


s# > city, status
city > status
(s#,p#) >qty
2 NF
The process for transforming a 1NF table to 2NF is:

Identify any determinants other than the composite key, and the columns they
determine.
Create and name a new table for each determinant and the unique columns it
determines.
Move the determined columns from the original table to the new table. The
determinate becomes the primary key of the new table.

Delete the columns you just moved from the original table except for the determinate
which will serve as a foreign key.
The original table may be renamed to maintain semantic meaning.
2 NF
To transform FIRST into 2NF we move the columns s#,
status, and city to a new table called SECOND. The column
s# becomes the primary key of this new table
2 NF Anomalies
Tables in 2NF but not in 3NF still contain modification
anomalies. In the example of SECOND, they are:

INSERT. The fact that a particular city has a certain status (Rome has a status of
50) cannot be inserted until there is a supplier in the city.

DELETE. Deleting any row in SUPPLIER destroys the status information about
the city as well as the association between supplier and city.
Third Normal Form (3 NF)
3 NF

Table PARTS is already in 3NF. The non-key column, qty, is fully dependent upon
the primary key (s#, p#).

SUPPLIER is in 2NF but not in 3NF because it contains the following transitive
dependency.

s# > status
s# > city
city > status
3 NF
The process of transforming a table into 3NF is:
Identify any determinants, other the primary key, and the columns they determine.
Create and name a new table for each determinant and the unique columns it
determines.

Move the determined columns from the original table to the new table. The
determinate becomes the primary key of the new table.

Delete the columns you just moved from the original table except for the
determinate which will serve as a foreign key.

The original table may be renamed to maintain semantic meaning.


3 NF
create a new table called CITY_STATUS and move the columns city
and status into it. Status is deleted from the original table, city is left
behind to serve as a foreign key to CITY_STATUS, and the original
table is renamed to SUPPLIER_CITY to reflect its semantic meaning
3 NF
The results of putting the original table into 3NF has
created three tables. These can be represented in

"psuedo-SQL" as:
PARTS (#s, p#, qty)
Primary Key (s#,#p)
Foreign Key (s#) references SUPPLIER_CITY.s#
SUPPLIER_CITY(s#, city)
Primary Key (s#)
Foreign Key (city) references CITY_STATUS.city
CITY_STATUS (city, status)
Primary Key (city)
Advantages of Third Normal Form
The advantage of having relational tables in 3NF is that it
eliminates redundant data which in turn saves space and
reduces manipulation anomalies. For example, the
improvements to our sample database are:
INSERT. Facts about the status of a city, Rome has a status of 50, can be added
even though there is not supplier in that city. Likewise, facts about new suppliers can be
added even though they have not yet supplied parts.

DELETE. Information about parts supplied can be deleted without destroying


information about a supplier or a city. UPDATE. Changing the location of a supplier or
the status of a city requires modifying only one row.
Boyce/Codd Normal Form

Determinant: an attribute or a group of attributes on which


some other attribute is fully functionally dependent.

Boyce/Codd Normal Form: a relation is in BCNF if and only if every


determinant is a candidate key.

Single-Row Functions
Objectives
After completing this lesson, you should be able to do the following :
Describe various types of functions available in SQL
Use character, number and date functions in SELECT statements
Describe the use of conversion functions.
Two types of SQL Functions
Single row functions : Operate on single rows only and return
one result per row .
Different Types of Single row functions :
Character Number Date Conversion General
Multiple row functions: Manipulates groups of rows to give one result per group
of rows. Also called as group functions
Single row functions :
Manipulate data items
Accept arguments and return one value
Act on each row returned
Return one result per row
May modify the data type
Can be nested
Accept arguments which can be a column or an
expression
function_name [ (arg1, arg2, ) ]
Can be used in SELECT, WHERE, and ORDER BY
clauses
Character Functions
Case-manipulation functions
LOWER UPPER INITCAP
Character-manipulation functions
CONCAT SUBSTR LENGTH
INSTR
LPAD | RPAD TRIM
REPLACE
These functions convert case for character strings.
- LOWER : converts character strings to lowercase
- UPPER : converts character strings to uppercase
- INITCAP: converts the first letter of each word to uppercase and remaining
letters to lowercase
Example :
SELECT LOWER(SQL Course) , INITCAP(SQL Course)
FROM dual;
These functions are useful for String comparisons in WHERE clause
Example
SELECT * FROM emp WHERE ename = UPPER(scott);
These functions manipulate character strings :
CONCAT
SUBSTR
LENGTH

: Joins values together


: Extracts a string of determined length
: Shows the length of a string as a numeric value

INSTR : Finds numeric position of a named character


LPAD : Pads the character value right-justified
RPAD : Pads the character value left-justified
TRIM : Trims heading or trailing characters( or both)
from a character string
CONCAT(Hello, World),
HelloWorld
SUBSTR(HelloWorld,1,5),
Hello
LENGTH(HelloWorld),
10
INSTR(HelloWorld,W),
6
LPAD(Hello,10,*),
*****Hello
RPAD(Hello,10,*),
Hello*****
TRIM(H FROM HelloWorld)
elloWorld
Number Functions
Round : Rounds value to specified decimal
ROUND(column|expression , [n]) : If n is omitted, no
places. If negative then integer part is rounded.
Trunc : Truncates value to specified decimal
TRUNC(column|expression, [n]) : If n is omitted, then n
zero
Mod : Returns remainder of division
MOD(m,n) : returns the remainder of m divided by n
> SELECT ROUND(45.92,1),ROUND(45.92,0),ROUND(45.92,-1),
TRUNC(45.92,1), TRUNC(45.92,0), TRUNC(45.92,-1),
MOD(45 , 7 ), MOD(45,9)
FROM DUAL;
> O/p : 45.9 46 50 45.9 45 40 3 0
Working with Dates
Oracle database stores dates in an internal numeric format :
century, year, month, day, hours, minutes, seconds
The default date display format is DD-MON-RR.
- Allows you to store 21st century dates in the 20th century by
specifying only the last two digits of the year
- Allows you to store 20th century dates in the 21st century in the
same way
SYSDATE is a function that returns :
- Date
- Time
Example :
SELECT SYSDATE FROM DUAL;
Arithmetic with Dates

decimal
defaults to

Use + operator to Add or Subtract number of days to/from a date for a resultant
date value
Use operator to find the number of days between those dates.
Add hours to a date by dividing the number of hours by 24
- date + number/24 will add a number of hours to a date
Example :
SELECT ename, (SYSDATE hiredate)/7 AS WEEKS
FROM emp
WHERE deptno = 90 ;
Date Functions
Function
Description
MONTHS_BETWEEN(date1,
date2)
ADD_MONTHS(date, n)

Number of months between two


dates
Add calendar months to date

NEXT_DAY(date, char)

Next day of the date specified

LAST_DAY(date)

Last day of the month

ROUND(date [, fmt] )

Round date

TRUNC(date [,fmt])

Truncate date

Using Date Functions


MONTHS_BETWEEN(01-sep-95,11-jan-94), --- 19.67741941
ADD_MONTHS(11-JAN-94 , 6), -------------- 1-JUL-94
NEXT_DAY(01-SEP-95 , FRIDAY), --------- 08-SEP-95
LAST_DAY(01-FEB-95), ------------------- 28-FEB-95
ROUND(SYSDATE , MONTH), ------------------ 01-AUG-95
ROUND(SYSDATE , YEAR), ----------------- 01-JAN-96
TRUNC(SYSDATE, MONTH), ----------------- 01-JUL-95
TRUNC(SYSDATE, YEAR), ------------------ 01-JAN-95
SYSDATE ----------------------------------- 25-JUL-95
Implicit Data Type Conversion
If a different data type value comes for an expected data type value then Oracle
server automatically converts the former to the later data type and uses it
This can happen in assignments or expression evaluations
The implicit conversion of string to number data type happens only when it is
compatible
Example :
SELECT
ename, job, sal
FROM
emp
WHERE
deptno=10 ;

Although implicit data type conversion is available, it is recommended to do


explicit data type conversion to ensure reliability.
Explicit Data Type Conversion
Date or Number
to
Varchar2 string
TO_CHAR(number/date , [fmt] )
Character
to
number
TO_NUMBER(char , [fmt] )
Character
to
Date
TO_DATE( char, [fmt] )
The fmt specifies the format in which the values are present facilitating the
conversion exactly
Elements of the Date Format Model
Format Model
Description
YYYY

Full year in numbers

YEAR

Year spelled out

MM

Two-digit value for month

MONTH

Full name of the month

MON

Three-letter abbreviation of the month

DY
DAY

Three-letter abbreviation of day of the


week
Full name of the day of the week

DD

Numeric day of the month

Elements of the Date Format Model


Format Model
Description
HH or HH12 or HH24 Hour of day, or hour(1-12), or hour(0-23)
MI

Minute (0-59)

SS

Second (0-59)

SSSSS

Seconds past midnight ( 0-86399 )

AM or PM

Meridian indicator

A.M. or P.M.

Meridian indicator with periods

Examples
SELECT TO_CHAR(sysdate,mm) ,sysdate
FROM DUAL;
O/p : 07 28-JUL-03
SELECT TO_NUMBER(12.238)
FROM DUAL;
O/p : 12.238

SELECT TO_DATE(18-07-2003,DD-MM-YYYY)
FROM DUAL;
O/p : 18-JUL-03
RR Date Format
If the specified two-digit year is
0-49
If two
0-49 The return date is in
digits of the
current century
current year
are :
50-99 The return date is in the
century after current one

50-99
The return date is in
century before current one
The return date is in
current century

Example :
SELECT ename, hiredate FROM emp
WHERE hiredate < TO_DATE(01-JAN-60 ,DD-MON-RR);
Nesting Functions
Single row functions can be nested to any level
Nested Functions are evaluated from deepest level to the least deep level
Example :
SELECT
TO_NUMBER(TO_CHAR(SYSDATE,YYYY))+1
AS Next year
FROM dual;
O/p : 2007
General Functions
These functions work with any data type and pertain to using nulls.
NVL( expr1, expr2)
NVL2(expr1, expr2, expr3)
NULLIF(expr1, expr2)
COALESCE(expr1, expr2,..,exprn)
Note : The NVL2, NULLIF, COALESCE functions are introduced in Oracle 9i
NVL Function
Converts a null to an actual value
Data types must match
Useful for expressions having null values as with this,
null values converts to a meaningful value
Syntax :
NVL (expr1, expr2 )
If expr1 is null then expr2 is returned else expr1 is returned
Example :

SELECT NVL(10,20) FROM DUAL;


SELECT NVL(null,20) FROM DUAL;
SELECT ENAME,NVL(TO_CHAR(COMMISSION),NOT APPLICABLE)
FROM EMP;
Using NVL2 function
NVL2 Function
NVL2(expr1, expr2, expr3)
If expr1 is not null then expr2 is returned else expr3 is
returned
Example :
Output
-

SELECT NVL2(10,20,30) FROM DUAL ;


20
SELECT NVL2(NULL,20,30) FROM DUAL ;
30
SELECT ENAME,SALARY,
NVL2(COMMISSION,(SALARY+COMMISION),SALARY) INCOME
FROM EMP;
Using NULLIF function
NULLIF function
NULLIF(expr1, expr2)
If expr1 and expr2 are equal then null else expr1 is returned
Example :
SELECT NULLIF(4*3 , 3*2), NULLIF( 2*3, 3*2)
FROM DUAL;
O/p : 12

Null is there but it will not appear


Using the COALESCE Function
The advantage of the COALESCE function over the NVL function is that this
function can take multiple alternate values.
COALESCE(expr1, expr2, expr3.,exprn)
This checks sequentially from expr1 to exprn and returns first non-null value
Example :
SELECT COALESCE(NULL,NULL,NULL,2,NULL,10,20)
FROM DUAL;
Conditional Expressions
To Provide the use of IF-THEN-ELSE logic within a SQL statement, use :
- CASE expression
- DECODE function

CASE expression
CASE expr WHEN comparison_expr1 THEN return_expr1
[WHEN comparison_expr2 THEN return_expr2
ELSE else_expr ]
END
DECODE function
DECODE(col/expr, search1, result1
[, search2, result2,] [, default] )
Examples
SELECT CASE a WHEN b THEN hello b
WHEN a THEN hello a
ELSE hello somebody
END
FROM DUAL;
SELECT ENAME, CASE SAL WHEN 100 THEN LOW
WHEN 5000 THEN HIGH ELSE MEDIUM END FROM EMP;
SELECT DECODE(A,B,HELLO B,A,HELLO A,
HELLO X) HELLO
FROM DUAL;
SELECT JOB, SAL, DECODE(JOB,ANALYST,SAL*1.1,
CLEARK, SAL*1.15, MANAGER, SAL*1.20,SAL) Updated Sal
From Emp;
In this lesson, you should have learned how to :
Perform calculations on data using functions
Modify individual data items using functions
Manipulate output for groups of rows using functions
Alter date formats for display using functions
Convert column data types using functions
User NVL functions
Use IF-THEN-ELSE logic

Displaying Data from


Multiple Tables
Objectives
After completing this lesson, you should be able to do the
following:
Extracting data from multiple tables
Types of Joins
Oracle proprietary Joins SQL:1999 Compliant Joins

Cartesian product
Equijoin
Non-equijoin
Outer join
Self join

Cross joins
Natural joins
Using Clause
Full or two sided outer joins
Arbitrary join conditions for
outer joins

Cartesian Products

A Cartesian product is formed when :


- A join condition is omitted or invalid
- All rows in the first table are joined to all rows in the second
table

To avoid a Cartesian product always include a valid join condition in a WHERE


clause.

Cartesian products are useful for some tests when we need to generate a large
number of rows to simulate a reasonable amount of data
Example :
SELECT last_name, department_name dept_name
FROM employees, departments;
Joining Tables

Use a join to query data from more than one table


SELECT table1.column, table2.column
FROM table1,table2
WHERE table1.column1 = table2.column2 ;

Write the join condition in the WHERE clause

Prefix the column name with the table name when the same column name appears
in more than one table

Joining n tables need a minimum of n-1 join conditions


Equijoin

Equijoin is based on equalto condition

Also called inner join or


simple join
Example :
SELECT employees.employee_id, employees.department_id,
departments.department_id, departments.location_id
FROM employees, departments

WHERE employees.department_id =departments.department_id ;


Use AND for additional search conditions
Using Table Aliases

simplify queries

Improve performance

Example :
SELECT e.employee_id, e.last_name, e.department_id,
d.department_id,d.location_id
FROM employees e, departments d
WHERE e.department_id = d.department_id
AND e.salary > 10000;
Non-Equi join

A non-equi join is based on condition other than an equality operator

Example :
SELECT last_name, salary, grade_level
FROM employees, job_grades
WHERE salary BETWEEN 5000 AND 15000 ;
Outer Joins

Use outer join to return records with no direct match

Outer join operator is the plus sign (+).


SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column(+) = table2.column ;
The (+) sign must be kept on the side of the join that is deficient in information.
Example :
SELECT e.last_name,
e.department_id,d.department_name
FROM employees e,departments d
WHERE e.department_id(+) = d.department_id ;
Self Joins

Joining a table to itself

Example :
SELECT worker.last_name|| works for || manager.last_name
FROM employees worker, employees manager
WHERE worker.manager_id = manager.employee_id ;
Oracle 9i feature

Oracle 9i introduced new features in compliance with SQL:1999 ANSI standard


Syntax :
SELECT table1.column, table2.column
FROM table1
[CROSS JOIN table2] |
[NATURAL JOIN table2] |
[JOIN table2 USING (column_name) ] |
[JOIN table2
ON (table1.column_name = table2.column_name) ] |
[LEFT | RIGHT | FULL OUTER JOIN table2
ON (table1.column_name = table2.column_name) ] ;
Cross Join

Forms a Cartesian Product whenever Join condition is not specified


SELECT ename,dname
FROM
emp
CROSS JOIN dept ;
Natural Joins

Equivalent to Equi Join

Joins with all the common columns present in the tables

The column names as well as the data types should match


Eg:
SELECT empno,ename,mgr,dname
FROM emp
NATURAL JOIN
dept;
USING clause

No matter how many common columns are available in the tables, NATURAL
JOIN will join with all the common columns

Use USING clause to join with specified columns

Example :
SELECT empno,ename,mgr,deptno,dname
FROM
emp
JOIN dept
USING (deptno,mgr);
ON clause

Explicit join condition can be specified by using ON clause

Additional conditions as well as sub-queries can be used along with ON clause


Example :
SELECT e.empno,e.name,d.deptno,d.dname
FROM emp e

JOIN
dept d
ON (e.deptno = d.deptno)
AND d.dname =SALES ;
Left Outer Join
SELECT e.ename,e.sal,d.deptno,d.dname
FROM
emp e
LEFT OUTER JOIN
dept d
ON (e.deptno = d.deptno) ;
Right Outer Join
SELECT e.ename,e.sal,d.deptno,d.dname
FROM emp e
RIGHT OUTER JOIN
dept d
ON (e.deptno = d.deptno) ;
FULL Outer Join
SELECT e.ename, e.sal,d.deptno,d.dname
FROM emp e
FULL OUTER JOIN
dept d
ON (e.deptno = d.deptno ) ;
Summary
In this lesson, you have learned :

Extracting data from multiple tables using joins


Oracle 8i proprietary joins
SQL:1999 ANSI standard joins ( oracle 9i feature)

Group Functions
After completing this lesson, you should be able to do the following :
Identify the available group functions
Describe the use of group functions
Group data using the GROUP BY clause
Include or exclude grouped rows by using the HAVING clause
Group Functions
Group Functions operate on sets of rows to give one result per group
Syntax :
SELECT [column, ] group_function(column), .
FROM table
[WHERE
condition]
[GROUP BY column]
[HAVING
group_condition]
[ORDER BY column] ;
All group functions ignore null values. To substitute a value for null values use
NVL functions
The Oracle server implicitly sorts the result set in ascending order when using a
GROUP BY clause.
Types of Group Functions
Function
Description
AVG( [DISTINCT | ALL] n)

Average value of n

COUNT( { *| [DISTINCT|ALL] expr } ) Number of rows where expr evaluates


to not null.
For *, including duplicates and rows
with nulls also
MAX( [DISTINCT|ALL] expr )

Maximum value of expr

MIN( [DISTINCT|ALL] expr)

Minimum value of expr

STDDEV( [DISTINCT|ALL] x)

Standard deviation of n

SUM ( [DISTINCT|ALL] n)

Sum values of n

VARIANCE( [DISTINCT|ALL]x)

Variance of n

Using the Group Functions


The AVG and SUM are used with numerica data.
The MIN and MAX functions used with any data type
The COUNT returns the number of rows with non null values.
Use DISTINCT clause not to consider duplicate values
Group functions do not consider null values. To consider user NVL functions.
Example :

Select sum(sal), avg(comm),avg(nvl(comm,0)), min(hiredate), max(hiredate),


count(*) strength
FROM emp;
Creating Groups of Data
Use GROUP BY clause to divide the table information into small groups
Use group functions to get summary information for each group
All individual columns other than group functions must be specified in the
GROUP BY clause list, when using GROUP BY
Any column other than selected column can also be placed in
GROUP BY clause
By default rows are sorted by ascending order of the column included in the
GROUP BY list.
Example :
SELECT deptno, AVG(sal)
FROM emp
GROUP BY deptno;
Excluding Group Results
To restrict groups we have to use HAVING clause
- Rows are grouped
- The group function is applied
- Groups matching the HAVING Clause are displayed.
Example :
SELECT department_id, MAX(salary)
FROM departments
GROUP BY department_id
HAVING MAX(salary) > 10000;
Nesting of Group Functions
Group functions can be nested to a depth of two.
Example :
SELECT MAX(AVG(salary))
FROM
employees
GROUP BY department_id ;
In this lesson, you should have learned how to :
Use the group functions COUNT, MAX, MIN, AVG
Write queries that use the GROUP BY clause
Write queries that use the HAVING clause

SET Operators
The SET Operators combine the results of two or more component queries into one
result. Queries containing SET operators are called compound queries.
Operator
UNION
UNION ALL
INTERSECT
MINUS

Returns
All distinct rows selected by either query
All rows selected by either query,including
duplicates
All distinct rows selected by both queries
All distinct rows that are selected by the first
SELECT statement and not selected in the second
SELECT statement.

The UNION Operator


The UNION operator returns all rows selected by either query from multiple
tables after eliminating duplications
Guidelines
- UNION operates over all of the columns being selected
- NULL values are not ignored during duplicate checking
- The IN operator has a higher precedence than the UNION
operator
- By default, the output is sorted in ascending order of the first
column of the SELECT clause
Using the UNION Operator
Example :
SELECT empno, job
FROM emp
UNION
SELECT employee_id, job_id
FROM job_history ;
The UNION operator eliminates any duplicate records. If there are records that
occur both in the EMPLOYEES and the JOB_HISTORY tables and are identical,
the records will be displayed only once.
To overcome this we have to use UNION ALL Operator
The UNION ALL Operator
The UNION ALL Operator returns all rows from multiple queries
Guidelines :
- Unlike UNION,duplicate rows are not eliminated
- The output is not sorted by default.
- The DISTINCT keyword cannot be used
- apart from these, all the guidelines of UNION ALL and
UNION are the same.

Example :
SELECT empno, job, deptno FROM emp
UNION ALL
SELECT employee_id, job_id, dept_id FROM
ORDER BY employee_id;

job_history

The INTERSECT Operator


The INTERSECT Operator returns all rows common to multiple queries from
multiple tables
Guidelines :
- INTERSECT result is same on reversing the order
- INTERSECT does not ignore NULL values
Example :
SELECT empno, job FROM emp
INTERSECT
SELECT employee_id, job_id FROM job_history;
The MINUS Operator
The MINUS Operator returns rows returned by first query that are not present in
the second query
- The result is not same by reversing the order
Example :
SELECT empno, job FROM emp
MINUS
SELECT employee_id, job_id FROM job_history ;
SET Operator Guidelines
The expressions in the SELECT lists must match in number and data type
Parentheses can be used to alter the sequence of execution
The ORDER BY clause :
- can appear only at the very end of the statement
- will accept the column name, aliases from the first
SELECT statement, or the positional notation
SET operators can be used in subqueries
The Oracle Server and SET Operators
Duplicate rows are automatically eliminated except in UNION ALL Operator.
Column names from the first query appear in the result
The output is sorted in ascending order by default except in UNION ALL
Operator.
If component queries select character data, the data type of the return values are
determined as follows :

- If both queries select values of data type CHAR, the


returned values have the data type CHAR.
- If either or both of the queries select values of data type
VARCHAR2 the returned values have data type
VARCHAR2.
Matching the SELECT Statements
Using the UNION Operator, display the department ID, location, hire_date for all
employees.
SELECT deptno,TO_NUMBER(null), hiredate
FROM emp
UNION
SELECT deptno, loc, TO_DATE(null)
FROM dept ;
TO_NUMBER() is used in first query to match NUMBER data type of location
TO_DATE() is used in second query to match the DATE data type of the
HIRE_DATE column of first query
If 0 is used for number type, then 0 will appear in output also.
Controlling the Order of Rows
Control the order of rows by taking a dummy column in the
Select clause and use NOPRINT option, and use it in the
ORDER BY clause
Example :
- COLUMN arrange NOPRINT
- SELECT I AS My dream, 3 FROM dual
UNION
SELECT Who,1
FROM dual
UNION
SELECT Am ,2 FROM dual
ORDER BY 2;
- O/p : Who Am I
In this lesson, you should have learned how to :
- Use UNION to return all distinct rows
- Use UNION ALL to return all rows, including duplicates
- Use INTERSECT to return all rows shared by both queries
- Use MINUS to return all distinct rows selected by the first
query but not by the second
- Use ORDER BY only at the very end of the statement

Subqueries
Objectives
After completing this lesson, you should be able to do the following :

Describe the types of problem that subqueries can solve

Define subqueries

List the types of subqueries

Write single-row and multiple-row subqueries

Multiple column subqueries

Scalar subqueries

Correlated subqueries

Use of EXISTS and NOT EXISTS operator


Subquery Syntax

Rather than having two or more queries to produce a result ,


we can solve
this by combining the two queries, placing one query inside the other query called inner
query or subquery.
Syntax :
SELECT select_list FROM table
WHERE expr_operator
( SELECT select_list FROM table );
The subquery executes once before the main query and its result is used by the
main query
Guidelines for Using Subqueries

Enclose subqueries in parentheses

Place subqueries on the right side of the comparison condition

The ORDER BY clause in the subquery is not needed unless we are performing
Top-N analysis ( later discussed)

Use single-row operators with single-row subqueries and use


multiple-row operators with multiple-row subqueries.

For single-row subqueries, use single-row comparison operators like


=, < , <= , > , >=, <> Or !=

For multiple-row subqueries use multiple-row operators like


IN , ANY , ALL
Examples

SELECT ename , job, sal


FROM emp
WHERE sal = (SELECT MIN(sal) FROM emp) ;

SELECT empno, ename, sal


FROM emp
WHERE sal < ANY ( SELECT sal
FROM emp
WHERE job = SALESMAN) ;

<ANY means < maximum value in the list


> ANY means >minimum value in the list
Examples
SELECT empno, ename, sal
FROM emp
WHERE sal < ALL ( SELECT sal
FROM emp
WHERE job = SALESMAN) ;

<ALL means less than minimum value in the list


> ALL means greater than maximum value in the list
NULL values in Subquery
SELECT e.ename FROM emp e
WHERE e.empno NOT IN (SELECT m.mgr FROM emp m );

Syntactically this is correct , but one value in the subquery is


null value and hence the whole subquery returns null . Hence
this query outputs nothing. To work correctly , we have to
write the query as
SELECT e.ename FROM emp e
WHERE e.empno NOT IN (SELECT NVL(m.mgr,0)
FROM emp m );
Multiple-Column Subqueries

Syntax :
SELECT column, column, FROM table
WHERE (column, column,) IN
(SELECT column,column FROM table
WHERE condition) ;
The column comparisons can be :
- Pair wise comparisons
- Non pair wise comparisons
Multiple-Column Subqueries
Pair wise comparisons

SELECT empno, mgr, deptno FROM emp


WHERE (mgr,deptno) IN (SELECT mgr,deptno FROM emp
WHERE empno = 7521 ) ;

Non pair wise comparisons


SELECT empno, mgr, deptno FROM emp
WHERE mgr IN (SELECT mgr FROM emp where empno=7521) AND deptno IN
(SELECT deptno FROM emp WHERE
empno=7521) ;

Scalar Subquery Expressions

A subquery that returns exactly one column value from one row.

Can be used in :
- condition and expression part of DECODE and CASE
- All clauses of SELECT except GROUP BY

Example :
SELECT empno, ename, (CASE WHEN deptno =
(SELECT deptno FROM dept where loc=HYDERABAD )
THEN Hyderabad ELSE Foreign END) location
FROM emp ;
Correlated Subqueries

A query is a Correlated Subquery when it references a column from a table


referred to in the parent statement

They are executed once for every row of the outer query

They are used for row-by-row processing


Example :
SELECT ename, sal, deptno FROM emp e
WHERE sal > (SELECT avg(sal) FROM emp d
WHERE e.deptno = d.deptno ) ;
EXISTS Operator

Tests for existence of rows in the results set of the subquery

Returns TRUE if subquery returns at least one row else FALSE is returned

IN operator can replace EXISTS operator

NOT EXISTS operator is opposite of EXISTS operator


Example :
SELECT empno, ename FROM emp e WHERE empno IN
(SELECT mgr FROM emp ) ;
SELECT empno, ename FROM emp e WHERE EXISTS
( SELECT 1 FROM emp WHERE mgr = e.empno );
Correlated UPDATE

To update rows in one table based on rows from another table

Syntax :
UPDATE table1 alias1
SET column = ( SELECT expression FROM table2 alias2
WHERE alias1.column = alias2.column ) ;
Example :
UPDATE emp e SET deptname = (select dname
FROM dept d WHERE e.deptno = d.deptno);
Similarly Correlated Delete can be used
The WITH Clause

Introduced in Oracle 9i
Using the WITH clause, the same query block in SELECT statement can be used
more than once within a complex query

It retrieves the results of a query block and stores it in the users temporary table
space and thus improves performance

It makes the query easy to read

Example

Averts the usage of re-writing the same subquery multiple times in complex sub
queries
Example :
SELECT dname, SUM(sal) AS dept_total
FROM emp, dept
WHERE emp.deptno = dept.deptno GROUP BY dname
HAVING SUM(sal) > (SELECT SUM(sal) * 1/3
FROM emp, dept WHERE emp.deptno = dept.deptno)
ORDER BY SUM(sal) DESC;
Example
WITH summary
AS( SELECT dname, SUM(sal) AS dept_total
FROM emp, dept WHERE emp.deptno = dept.deptno
GROUP BY dname)
SELECT dname, dept_total
FROM summary WHERE dept_total >
( SELECT SUM(dept_total) * 1/3 FROM summary)
ORDER BY dept_total DESC;
Summary
In this lesson, you should have learned :

Identifying when a subquery can help to solve a question


Single row subqueries
Multiple row subqueries
Multiple-column subqueries
Scalar subqueries
Correlated subqueries
Using WITH clause

Manipulating Data
Objectives
After completing this lesson, you should be able to do :

Describe each DML statement

Insert rows into a table

Update rows in a table

Delete rows from a table

Merge rows in a table

Control transactions
Data Manipulation Language

It is core part of SQL.

A DML statement is executed when you :


- Add new rows to a table
- Modify existing rows in a table
- Remove existing rows from a table

A transaction consists of a collection of DML statements that form a logical unit


of work.

They are useful for the maintenance of Integrity of database


The INSERT Statement Syntax

Add new rows to a table by using the INSERT statement


INSERT INTO
table [ (column [, column]) ]
VALUES
(value [, value ] ) ;
Example :

INSERT INTO dept


VALUES ( 10, Sales,vizag);

Substitution variables can also be used


INSERT INTO departments
VALUES ( 10, Sales, &location );
Copying Row from Another Table

Write INSERT statement with a subquery


INSERT INTO copy_emp(id, name, salary,comm)
SELECT empno, ename, sal, comm
FROM emp WHERE job_id LIKE %MAN% ;

Do not use the VALUES clause


Match the number of columns and their data types in the INSERT clause to those
in the subquery
Changing Data using UPDATE statement

Modify existing rows with the UPDATE statement


UPDATE
table
SET
column = value [, column = value, ]
[WHERE
condition ] ;

Update more than one row at a time, if required

If WHERE clause is omitted, then all rows are modified


Subqueries can also be used for values
Example :
UPDATE
employees
SET
department_id = 70
WHERE
employee_id = 113 ;
Removing rows using DELETE statement

use the DELETE statement


DELETE [FROM] table
[WHERE
condition] ;

If WHERE clause is omitted then all rows in table are deleted


Example :
DELETE FROM dept
WHERE dname = Finance ;

Using a Subquery in an INSERT Statement

Use a subquery in place of the table name in the INTO clause of the INSERT
statement.

The select list must have the same number of columns as the column list of the
VALUES clause.
Ex :
INSERT INTO ( SELECT dname, deptno FROM dept)
VALUES (ODS,100) ;
Using a Subquery in an INSERT Statement

Use WITH CHECK OPTION to prohibit insertion of rows that are not in the
subquery.
INSERT INTO ( SELECT dname, deptno, loc
FROM dept
WHERE loc = NEW YORK WITH CHECK OPTION)
VALUES ( SAP, 200, NEW YORK ) ;

If other than NEW YORK is given for loc, it will result an error

INSERT INTO ( SELECT dname, deptno, loc FROM dept


WHERE loc = NEW YORK WITH CHECK OPTION)
VALUES ( SAP, 200, NEW JERSY ) ;
Database Transactions

A database transaction consists of one of the following :


- DML statements which constitutes one consistent change to the data
- One DDL statement
- One DCL statement

Begin when the first DML SQL statement is executed

End with one of the following events :

- A COMMIT or ROLLBACK statement is issued


- A DDL or DCL statement executes ( automatic commit)
- The user exits iSQL*Plus or SQL*Plus
- The system crashes
Explicit Default Feature

Oracle9i allows to use Default Keyword not only in DDL statements but also in
DML statements too.

DEFAULT can be used as a column value where its default value is desired
Example :

INSERT INTO emp(empno,ename,sal,deptno)


VALUES (416,Srikanth,5000,DEFAULT);

UPDATE emp
SET sal=DEFAULT
where deptno=10;
Merge Statement

Facilitates the user to conditionally update or insert values into database table

Does an Update if the row exists; else inserts a new row into database table
Syntax:
MERGE INTO table_name table_alias
USING (table|view|sub_query) alias ON (join condition)
WHEN MATCHED THEN
UPDATE SET
col1=col_val1, col2=col_val2
WHEN NOT MATCHED THEN
INSERT(column_list)
VALUES(column_values);
Merge Statement
Example :
MERGE INTO dest_tab d
USING source_tab s ON (s.no=d.no)
WHEN MATCHED THEN
UPDATE SET
d.name=s.name,
d.address=s.address
d.salary=s.salary
WHEN NOT MATCHED THEN
INSERT (d.name,d.address,d.salary)
VALUES(s.name,s.address,s.salary) ;
Transaction Control Statements
Implicit Transaction Processing

An automatic commit occurs under the following circumstances :


- DDL or DCL statement is issued
- Normal exit from iSQL*Plus

An automatic rollback occurs under


- An abnormal termination of iSQL*Plus
- a system failure.
State of the Data

Before COMMIT or ROLLBACK


- The previous state of the data can be recovered
- The current user can review the results of the DML operations
- Other users cannot view the results of the DML statements
- The affected rows are locked

After COMMIT
- Data changes are made permanent in the database
- The previous state of the data is permanently lost
- All users can view the result
- Locks are released
-All savepoints are erased
State of the Data

After ROLLBACK
- Data changes are undone
- Previous state of the data is restored
- Locks on the affected rows are released

Statement-Level Rollback
- If a single DML statement fails during execution, only that
statement is rolled back.
- The Oracle server implements an implicit savepoint
- All other changes are retained
- The user should terminate transactions explicitly by executing
COMMIT or ROLLBACK statement
Read Consistency

Guarantees a consistent view of the data at all times

Changes made by one user do not conflict with changes made by other user

Read consistency ensures that on the same data :


- Readers do not wait for writers
- Writers do not wait for readers

The purpose of read consistency is to ensure that each user sees data as it existed
at last commit, before DML operation started.

Read consistency is an automatic implementation. It keeps a partial copy of the


database in undo segments.

Except the user who is doing DML operation, all others see the consistent view of
data only. They will see the changes only when the DML operations are committed .
Locking
In an Oracle database, locks :

Prevent destructive interaction between concurrent transactions


Require no user action
Automatically use the lowest level of restrictiveness
Are held for the duration of the transaction

Are of two types :


- Explicit Locking
- Implicit Locking
Implicit Locking

Tow lock modes :


- Exclusive :
locks out other users
- Share : Allows other users to access

High level of data concurrency


- DML :
Table share, row exclusive
- Queries : No locks required
- DDL :
Protects object definitions

Locks held until commit or rollback


Summary
In this lesson, you should have learned
DML statements
control transactions.

Creating and Managing Tables


Objectives
After completing this lesson, you should be able to :

Describe the main database objects

Create tables

Describe the data types that can be used when specifying column definition

Alter table definitions

Drop, rename, and truncate tables


Database Objects
Naming Rules
Table names and column names :

Must begin with a letter

Must be 1-30 characters long

Must contain only A-Z, a-z, 0-9, _ , $ , and #

Must not duplicate the name of another object owned by the same user

Must not be an Oracle server reserved word

Use descriptive names for tables and other database objects

Table names are case insensitive (not case sensitive)


The CREATE TABLE Statement

A user must have :


CREATE TABLE privilege
A storage area

Syntax :
CREATE TABLE [schema . ]table

(column datatype [DEFAULT expr] [,.]) ;

Specify
Table name
Column name, column data type, and column size
Specify a default value for a column during an insert.

Data Types
Examples

Create the table


CREATE TABLE dept
( dept_id NUMBER(2), deptname varchar2(14),
location varchar2(13) );
Referencing Tables
- If the table is in your schema only then
SELECT * FROM employees
- If you want to use other users tables then You should use the
owners name as a prefix
SELECT * FROM user_b.employees;
Tables in the Oracle Database

User Tables :
- Are a collection of tables created and maintained by the user
- Contain user information

Data Dictionary
- Is a collection of tables created and maintained by Oracle Server
- Contain database information

Querying the Data Dictionary Views


- USER_TABLES : gives tables owned by the user
- USER_OBJECTS : gives distinct object types owned by user
- USER_CATALOG : gives tables,views,synonyms and
sequences owned by the user
Creating a Table by Using a Subquery Syntax

Create a table and insert rows by combining the CREATE TABLE statement and
the select query with AS keyword
CREATE TABLE table [ ( column, column, ) ]
AS subquery ;

Match the number of specified columns to the number of subquery columns

Define columns with column names and default values


Example :
CREATE TABLE dept80
AS
SELECT empno, ename, sal*12 annsal,hiredate
FROM emp WHERE deptno = 80 ;
The ALTER TABLE Statement

Use the ALTER TABLE statement to :

Add a new column

Modify an existing column and define a default value for the new column
ALTER TABLE table
ADD | MODIFY (column datatype [DEFAULT expr]
[,column datatype]) ;

Drop a column
ALTER TABLE table
DROP (column) ;
Examples

Adding a column
ALTER TABLE dept80
ADD (job_id varcahr2(9) );

Modifying a column
- we can change data type, size and default value
ALTER TABLE dept80
MODIFY (last_name varchar2(30) );

Dropping a column
ALTER TABLE dept80
DROP COLUMN job_id ;
The SET UNUSED Option

Use the SET UNUSED option to mark one or more columns as unused. They are
logically removed and cant be viewed or used .

They can be dropped when the demand on system resources is lower

This is a fast process than using DROP clause


ALTER TABLE table SET UNUSED (column ) ;

Example :
- ALTER TABLE dept SET UNUSED (loc) ;
The SET UNUSED Option

View the unused columns in


USER_UNUSED_COL_TABS
Use DROP UNUSED COLUMNS option to remove the columns that are marked
as unused

ALTER TABLE table DROP UNUSED COLUMNS ;

Example :
- ALTER TABLE dept DROP UNUSED COLUMNS;
Dropping, Renaming, Truncating a Table

Dropping
- All data , structure in the table and indexes are dropped

- Syntax : DROP TABLE table ;

Renaming
- We can change the name of a table, view, sequence
- Syntax : RENAME oldname TO newname ;

Truncating
- Removes all rows from a table
- Releases storage space used by that table
- Syntax : TRUNCATE TABLE table ;

Note : You cant rollback these operations


Adding Comments

Add comments to a table or column by using the COMMENT statement. The


comment can be up to 2000 bytes
COMMENT ON TABLE table | COLUMN table.column
IS comment ;

Comments can be viewed through the data dictionary views :


- ALL_COL_COMMENTS, USER_COL_COMMENTS,
ALL_TAB_COMMENTS, USER_TAB_COMMENTS
Example :
COMMENT ON TABLE departments IS Depts info ;
COMMENT ON COLUMN department.deptid
IS department identification unique id ;
Summary
In this lesson, you should have learned how to use DDL
statements to create, alter, drop and rename tables
CREATE TABLE - Creates a table
ALTER TABLE - Modifies table structures
DROP TABLE
- Removes the rows and table structure
RENAME
- Changes the name of the table, view,
sequence, or synonym
TRUNCATE
- Removes all rows from table and
releases storage space
COMMENT
- Adds comments to a table or column or
view

Including Constraints
Objective
After completing this lesson, you should be able to do :

Describe constraints

Create and maintain constraints


What are constraints ?

Constraints enforce rules at the table level. They prevent the deletion of a table if
there are dependencies

The following constraint types are valid :

NOT NULL : The column cant contain a null value


UNIQUE
: Specifies column(s) whose values must be
unique for all rows in the table. Null values
are allowed
PRIMARY KEY : Uniquely identifies each row of the table
FOREIGN KEY :
Establishes and enforces a foreign key
relationshipbetween the column and a
column
of referenced table
CHECK
: Specifies a condition that must be true
Constraint Guidelines

Name a constraint or the Oracle server generates a name by using the SYS_Cn
format.

Create a constraint either :


- At the same time as the table is created
- After the table has been created

Define a constraint at the column or table level

View a constraint in the data dictionary view


USER_CONSTRAINTS

Defining Constraints
CREATE TABLE [schema .] table
(column datatype [DEFAULT expr] [column_constraint] ,
[table_constraint ] [, ] ) ;
Defining Constraints

Column constraint level


column [ CONSTRAINT constraint_name ] constraint_type
- References a single column and is defined within a specification for the owning
column; can be any type of integrity constraint

Table constraint level


column,
[CONSTRAINT constraint_name] constraint_type (column,)
- References one or more columns and is defined separately from the definitions of the
columns in the table; can define any constraints except NOT NULL
Examples

NOT NULL
CREATE TABLE employees (
employee_id NUMBER(6) NOT NULL,
name VARCHAR2(20) CONSTRAINT emp_name_nn
NOT
NULL ) ;

UNIQUE
CREATE TABLE employees (
employee_id NUMBER(6) , name VARCAHR2(20)
CONSTRAINT emp_id_uk UNIQUE(employee_id) ) ;

PRIMARY
CREATE TABLE employees (
employee_id NUMBER(6) , name VARCAHR2(20)

CONSTRAINT emp_id_pk PRIMARY KEY (employee_id)) ;


FOREIGN KEY Constraint

FOREIGN KEY : Defines the column in the child table at the table constraint
level

REFERENCES : Identifies the table and column in the parent table

ON DELETE CASCADE : Deletes the dependent rows in the child table when a
row in the parent table is deleted

ON DELETE SET NULL : Converts dependent foreign key values to null

Without the ON DELETE CASCADE, ON DELETE SET NULL options, the row
in the parent table cannot be deleted if it is referenced in the child table.
Examples

FOREIGN KEY
- column level
CREATE TABLE employees
( employee_id number(6) ,
department_id number(4) CONSTRAINT emp_dept_fk
references departments(dept_id),
name varchar2(20) );
- Table level
CREATE TABLE employees
( employee_id number(6), department_id number(4),
name varchar2(20), CONSTRAINT emp_dept_fk
FOREIGN
KEY(department_id)
REFERENCES departments(dept_id) );
The CHECK Constraint

Defines a condition that each row must satisfy

The following expressions are not allowed :


- References to CURRVAL, NEXTVAL, LEVEL and ROWNUM
- calls to SYSDATE, UID, USER and USERENV functions
- Queries that refer to other values in other rows
Example
CREATE TABLE departments
( deptno number(2) CONSTRAINT dept_no_min
CHECK (deptno >0),deptname varchar2(20) ) ;
Adding a constraint
Use the ALTER TABLE statement to :

Add or drop a constraint, but not modify its structure


Enable or disable constraints
Add a NOT NULL constraint by using the MODIFY clause
Syntax :
ALTER TABLE table
ADD [CONSTRAINT constraint] type (column) ;
Example :

ALTER TABLE dept


MODIFY (dname varchar2(20) not null dept_name_nn );
Dropping a constraint

Syntax :
ALTER TABLE table
DROP PRIMARY KEY | UNIQUE (column) |
CONSTRAINT constraint
[CASCADE] ;

The cascade option causes any dependent constraints also to be dropped.


Example :
ALTER TABLE employees
DROP CONSTRAINT emp_dept_fk ;
Disabling Constraints

Disabling :
- Execute the DISABLE clause of the ALTER TABLE
statement to deactivate an integrity constraint
- Apply the CASCADE option to disable dependent integrity
constraints
- Syntax :
ALTER TABLE table
DISABLE CONSTRAINT constraint [CASCADE] ;

Example :
ALTER TABLE employees
DISABLE CONSTRAINT emp_id_pk CASCADE;
Enabling Constraints
Enabling :
- Activate an integrity constraint currently disabled in the table definition by using the
ENABLE clause.
ALTER TABLE table
ENABLE CONSTRAINT constraint ;
Example :
ALTER TABLE employees
ENABLE CONSTRAINT emp_id_pk ;
Cascading Constraints

The CASCADE CONSTRAINTS clause is used along with the DROP COLUMN
clause

The CASCADE CONSTRAINTS clause drops all referential integrity constraints


that refer to the primary and unique keys defined on the dropped columns.

The CASCADE CONSTRAINTS clause also drops all multicolumn constraints


defined on the dropped columns
ALTER TABLE test1
DROP (pk) CASCADE CONSTRAINTS ;
Viewing Constraints

Query the USER_CONSTRAINTS table to view all constraint definitions and

names
View the columns associated with the constraint names in the
USER_CONS_COLUMNS view.
Example :
SELECT constraint_name, constraint_type,
search_condition
FROM USER_CONSTRAINTS
WHERE table_name = EMP ;
Summary
In this lesson, you should have learned :

Types of constraints
- NOT NULL
- UNIQUE
- PRIMARY KEY
- FOREIGN KEY
- CHECK

You can query the USER_CONSTRAINTS table to view all constraint definitions
and names

Creating VIEWS
Objectives
What is a view ?

A view is a logical table based on a table or another view.

It contains no data of its own but is like window through which data can be
viewed or changed.

The tables from which data retrieved are called base tables.
Why use views?

To restrict data access

To make complex queries easy

To provide data independence

To prevent different views of the same data


Simple views and Complex views
Creating View
Creating View
Creating View
Some points on view

Use a view just as a table

The views are stored in the database as a select query

The views and its definition can be seen by querying data

Dictionary view called USER_VIEWS

Modify a view using OR REPLACE option in the syntax

Remove views using DROP VIEW clause

DROP VIEW <view name> ;

Creating a complex view


Rules for performing DML operations
Rules for performing DML operations
Rules for performing DML operations
Using the WITH CHECK OPTION clause
Using the WITH READ ONLY clause
Inline Views
Top-N Analysis
Top-N Analysis Example
Summary
Other Data Base Objects
Objectives
After completing this lesson, you should be able to :

Create, maintain, and use sequences

Create and maintain indexes

Create private and public synonyms


What is a Sequence?
A sequence

Automatically generates unique numbers

Is a sharable object

Is typically used to create a primary key value

Replaces application code

Speeds up the efficiency of accessing sequence values when cached in memory


Syntax
Define a sequence to generate sequential numbers automatically
CREATE SEQUENCE sequence
[ INCREMENT BY n ]
[ START WITH n ]
[ { MAXVALUE n | NOMAXVALUE } ]
[ { MINVALUE n | NOMINVALUE } ]
[ { CYCLE | NOCYCLE } ]
[ { CACHE | NOCACHE }] ;
sequence
is the name of the sequence generator
INCREMENT BY n specifies the interval between sequence numbers where n is an integer
( default 1)
START WITH n
specifies the first sequence number to be generated ( default is 1)
MAXVALUE n
specifies the maximum value the sequence can generate
NOMAXVALUE
specifies a max value of 10^27 for an ascending sequence and 1 for a
descending sequence (default)
MINVALUE n
specifies the minimum sequence value
NOMINVALUE
specifies a min value of 1 for an ascending sequence and 10^26 for a
descending sequence
CYCLE | NOCYCLE specifies whether the sequence continues to generate values after
reaching its max or min value
CACHE n|NOCACHE
specifies how many values the Oracle server preallocates and
keep in memory

Note : underlined are default values


Conforming Sequences

Verify sequence generation in USER_OBJECTS data dictionary table

Verify your sequence values in the USER_SEQUENCES data dictionary table


SELECT sequence_name,min_value,max_value,
FROM user_sequences;
The LAST_NUMBER column displays the next available sequence number if
NOCACHE is specified
NEXTVAL and CURRVAL Pseudocolumns

NEXTVAL returns the next available sequence value.

CURRVAL obtains the current sequence value

Example
CREATE SEQUENCE dept_deptid_seq
INCREMENT BY 10
START WITH 120
MAXVALUE 9999 ;

INSERT INTO dept (deptno,dname,loc)


VALUES(dept_deptid_seq.NEXTVAL,Support,ABC);

SELECT dept_deptid_seq.CURRVAL FROM dual;


Rules for Using NEXTVAL AND CURRVAL
You can use NEXTVAL and CURRVAL in the following contexts :
The SELECT list of a SELECT statement that is not part of a
subquery
The SELECT list of a subquery in an INSERT statement
The VALUES clause of an INSERT statement
The SET clause of an UPDATE statement
You cannot use the NEXTVAL and CURRVAL in the following contexts :
The SELECT list of a view
A SELECT statement with the DISTINCT keyword
A SELECT statement with GROUP BY,HAVING, OR ORDER
BY
clauses
A subquery in a SELECT,DELETE,OR UPDATE statement
The DEFAULT expression in a CREATE TABLE or
ALTER TABLE statement
Note :NEXTVAL must be issued for that sequence before CURRVAL contains a value
Using a Sequence

Caching sequence values in memory gives faster access to those values

Gaps in sequence values can occur when :


- A rollback occurs

- The system crashes


- A sequence is used in another table
If the sequence was created with NOCACHE, view the next available value, by
querying USER_SEQUENCES
Modifying a Sequence

We can modify a sequence using ALTER SEQUENCE

Example :
ALTER SEQUENCE dept_deptid_seq
INCREMENT BY 20
MAXVALUE 999999
NOCACHE
NOCYCLE ;
Dropping a Sequence

We can remove a sequence using DROP SEQUECE clause


DROP SEQUENCE dept_deptid_seq ;
What is an Index ?
An index

is a schema object

is used by the Oracle server to speed up the retrieval of rows by using a pointer

can reduce disk I/O by using a rapid path access method to locate data quickly

is independent of the table it indexes

is used and maintained automatically by the Oracle Server


How indexes are created?

Automatically : A unique index is created automatically when you define a


PRIMARY KEY or UNIQUE KEY constraint in a table definition. The name of index is
name given to constraint.

Manually : Users can create non unique indexes on columns to speed up


access to the rows.
Creating an Index

Create an index on one or more columns


CREATE INDEX index_name
ON table (column[, column]);
Example :
CREATE INDEX emp_last-name_idx
ON employees(lart_name);
This will speed up query access to the LAST_NAME
column in the EMPLOYEES table.

When to create an Index


Create an index if

A column contains a wide range of values

A column contains a large number of null values

One or more columns are frequently used together in a WHERE clause or a join
condition

The table is large and most queries are expected to retrieve less than 2 to 4
percent of the rows
When not to create an Index
It is usually not worth creating an Index if :

The table is small

The columns are not often used as a condition in the query

Most queries are expected to retrieve more than 2 to 4 percent of rows in the
table

The table is updated frequently

The indexed columns are referenced as part of an expression


Confirming Indexes
Check the Index creation and its fields in

The USER_INDEXES data dictionary view contains the name of the index and
its uniqueness

The USER_IND_COLUMNS view contains the index name, the table name, and
the column name.
Example:
SELECT ic.index_name,ic.column_name,ix.uniqueness
FROM user_indexes ix, user_ind_columns ic
WHERE ic.index_name=ix.index_name
AND ic.table_name=EMPLOYEES;
Function-Based Indexes

A function based index is an index based on expressions

The index expression is built from table columns, constants, SQL functions, and
user-defined functions.
CREATE INDEX upper_dept_name_idx
ON departments(UPPER(department_name));
Removing an Index
Synonyms
Summary

Controlling User Access


Objectives
After completing this lesson, you should be able to :

Create users
Create roles to ease setup and maintenance of the security model
Use the GRANT and REVOKE statements to grant and revoke object privileges
Create and access database links
Privileges

Database Security
- System Security
- Data Security

System privileges : Gaining access to the database

Object privileges : Manipulating the content of the database objects

Schemas : Collections of objects,such as tables,views and sequences

The Data Base Administrator (DBA) has high-level system privileges for tasks
such as :

Creating and Removing new users

Removing Tables

Backing up tables
Creating Users and User System Privileges

The DBA creates users by using the CREATE USER statement


CREATE USER user
IDENTIFIED BY password;

Once a user is created, the DBA can grant specific system privileges to a user
using GRANT clause
GRANT privileges [, privileges..]
TO user [,user/role, PUBLIC] ;

Example :

CREATE USER scott IDENTIFIED BY tiger ;

GRANT create session,create table, create view TO scott;


What is a Role ?

A named group of related privileges that can be granted to user.

This makes it easier to revoke and maintain privileges

A user can have access to several roles, and several users can be assigned the
same role

Roles are typically created for a database application.


Syntax :
CREATE ROLE role;
Grant privileges to a role
Grant a role to users
Example :
CREATE ROLE manager
GRANT create table,create view TO manager;
GRANT manager TO scott;
Changing Your Password

The DBA creates your user account and initializes your password

You can change your password by using the ALTER USER statement

The Syntax is :
ALTER USER user

IDENTIFIED BY password;
Example :
ALTER USER scott
IDENTIFIED BY lion ;
To perform this you must have the ALTER USER privilege.
Object privileges
Object Privileges

Object privileges vary from object to object

An owner has all the privileges on the object

An owner can give specific privileges on that owners object


Syntax :
GRANT object_priv [ (columns) ]
ON object
TO {user|role|PUBLIC} [ WITH GRANT OPTION ] ;

Example :
GRANT select ON employees TO sue,rich;
GRANT update(department_name,location_id) ON departments TO scott,
manager;
Using Other GRANT options

WITH GRANT OPTION


- Give a user authority to pass along privileges
- Alice gives select, insert privileges to scott with grant option

GRANT select,insert
ON departments
TO scott
WITH GRANT OPTION;
- Allow all users on the system to query data from Alices DEPARTMENTS table

GRANT select
ON alice.departments
TO PUBLIC;
Confirming Privileges Granted
Revoking of Object Privileges

Use REVOKE statement to revoke privileges granted to users


Syntax :
REVOKE { privilege [ , privilege] | ALL }
ON object
FROM { user [ , user] | role | PUBLIC }
[ CASCADE CONSTRAINTS ] ;

Note : The CASCADE CONSTRAINTS clause is required to remove any referential


integrity constraints made to the object by means of the REFERENCES privilege

Example : REVOKE select,insert ON departments FROM scott;


Database Links

A Database Link connection allows local users to access data on a remote


database
It 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.

The great advantage of database links is that they allow users to access another
users objects in a remote database so that they are bounded by the privilege set of the
objects owner.
Database Links

Create the Database Link


CREATE PUBLIC DATABASE LINK hq.acme.com
USING sales;
The USING clause identifies the service name of a remote database.
Write SQL statements that use the database link
SELECT *
FROM emp@hq.acme.com;

The dictionary view USER_DB_LINKS contains information on links to which a


user has access.
Summary
In this lesson you should have learned about DCL statements
that control access to the database and database objects

Objective

At the end of the session participants will be able to

Write simple PL / SQL blocks

handling errors,

usage of cursors
Agenda

Introduction to PL/SQL
PL/SQL Data Types
Control Structures
Cursors
Exception handling

PL/SQL extends SQL by adding constructs such as

Variables and constants

Control structures such as IF-THEN-ELSE statements and loops

Procedures and functions

It bridges the gap between the database technology and procedural programming
language

The Basic unit of PL/SQL is a block.

All PL/SQL programs are made up of blocks, which can be nested within each
other.

Each block performs a logical unit of work in the program

A standard PL/SQL block consists of the following sections

Declaration Section
Variables and constants are declared here

Executable Section
Consists of SQL and PL/SQL statements and is meant for manipulating
objects during execution

Exception Section
Errors or exceptions raised during execution are handled here

PL/SQL Block Structure


DELCARE (Optional)
< Declarations>
BEGIN (Mandatory)
< Statements>

EXCEPTION (Optional)
< Error handlers >
END ; (Mandatory)
Variables

Can contain up to 30 characters

Must begin with an alphabetic character

Should not be reserved word

Should not be the same name as database column name Or database table name

Cannot contain characters such as hyphens, slashes, spaces

Declaring PL/SQL Variables


Syntax :
identifier [CONSTANT] data type [NOT NULL]
[ := | DEFAULT expr] ;

Initialize variables designated as NOT NULL and CONSTANT

Example :
v_age CONSTANT number(2) := 20 ;
v_name

employees.last_name % TYPE ;

DBMS_OUTPUT.PUT_LINE

An Oracle supplied packaged procedure

An alternative for displaying data from a PL/SQL block

Must be enabled with SET SERVEROUTPUT ON

Example:
SET SERVEROUTPUT ON
DECLARE
BEGIN
DBMS_OUTPUT.PUT_LINE (hello world );
END ;

Compilation of PL / SQL Blocks

Checking for the correct syntax

Binding ( Assigning Storage Address to variables )

P-code Generation

Two types of PL/SQL blocks are

Anonymous Blocks

Named Blocks
Operators in PL/SQL

Logical

Arithmetic

Concatenation

Parenthesis to control order of operations

Exponential operator ( ** )

Note :
comparisons involving nulls always yield NULL

SQL Statements in PL/SQL

Extract a row of data from the database by using SELECT statement

Make changes to rows in the database by using DML commands

Control a transaction with the COMMIT, ROLLBACK, or SAVEPOINT


command

Use DML, TCL statements as in SQL only.


SELECT statements in PL/SQL
Syntax :
SELECT select_list
INTO
{ variable_name [, variable_name] |
record_name }
FROM
table
[WHERE condition ] ;

Note :

The queries must return one and only one row


Example
Example :
DELCARE
v_dept
BEGIN
SELECT
INTO
FROM
WHERE
END ;

dept.deptno% TYPE ;
deptno
v_dept
dept
dept_name = Sales ;

Manipulating Data Using PL/SQL

Manipulation can be done using DML commands :


- INSERT
- UPDATE
- DELETE
- MERGE

Use DML statements same as in SQL in the executable and exception blocks.

Example :
BEGIN
DELETE FROM employees ;
END ;
VARIABLE name VARCHAR2(30)
DECLARE
v_no employees.employee_id % TYPE := 176;
BEGIN
SELECT last_name
INTO
: name
WHERE employee_id = v_employee_id ;
DBMS_OUTPUT.PUT_LINE(hello || : name ) ;
END ;
/
PRINT name
IF Statements

Syntax :
IF condition THEN
statements ;
[ ELSIF condition THEN
statements ; ]
[ ELSE
statements ; ]

END IF;
Set SERVEROUTPUT ON
DECLARE
sal NUMBER(9,2) := 20000 ;
BEGIN
IF( sal > 25000)
DBMS_OUTPUT.PUT_LINE(BEST);
ELSIF ( sal > 15000)
DBMS_OUTPUT.PUT_LINE( BETTER );
ELSE
DBMS_OUTPUT.PUT_LINE(Good);
END IF
END ;
CASE Expression

A CASE Expression selects a result and returns it .


DECLARE
salary NUMBER(9,2) := 25000 ;
grade CHAR(1) ;
BEGIN
grade := CASE salary
WHEN 25000 THEN A
WHEN 15000 THEN B
ELSE C
END ;
DBMS_OUTPUT.PUT_LINE( GRADE : || grade ) ;
END ;
Iterative control :LOOP Statements

Loops repeat a statement or sequence of statements multiple times.

There are three loop types :


- Basic loop
- FOR loop
- WHILE loop

Basic Loops

Syntax :
LOOP
statement1 ;

EXIT [ WHEN condition ] ;


END LOOP ;

Condition is a boolean variable or expression

DECLARE
v_counter number(2) :=1 ;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE( Number : || v_counter );
v_counter := v_counter + 1 ;
EXIT WHEN v_counter > 5 ;
END ;
WHILE Loops

Syntax :
WHILE condition LOOP
statement 1 ;
statement 2 ;

END LOOP ;
DECLARE
v_counter number(2) :=1 ;
BEGIN
WHILE v_counter < 6 LOOP
DBMS_OUTPUT.PUT_LINE( Number : || v_counter );
v_counter := v_counter + 1 ;
END LOOP ;
END ;
FOR Loops

Syntax :
FOR counter IN [REVERSE] lower_bound..upper_bound
LOOP
statement 1 ;
statement 2 ;

END LOOP ;

The counter is declared implicitly. No necessary to declare explicitly

BEGIN
FOR v_counter IN 1..5
LOOP
DBMS_OUTPUT.PUT_LINE( Number : || v_counter );
INSERT INTO numbers VALUES (v_counter) ;
END LOOP

END ;
cursor

A cursor is a private SQL work area


The oracle server uses implicit cursors to parse and execute SQL statements.

There are two types of cursors

Implicit cursors :
- Declared for all DML and PL/SQL SELECT statements.
- User has no control over it
- PL/SQL refers most recent implicit cursor as the
SQL
cursor

Explicit cursors :
- Declared and named by the programmer
- User has control over it and names it
- Useful when more than one row is returned by the query
Explicit Cursors

Used when each row returned by a multiple-row SELECT statement needs


processed

Controlling Explicit Cursors :


- Declare the cursor
- Open the cursor
- Fetch data from the cursor
- Close the cursor
Declaring Cursors

Syntax :
CURSOR cursor_name IS
select_statement ;

Note : Declaration of cursor do not execute the query


Example :
CURSOR dept_cursor IS
SELECT deptno, dname, location
FROM dept;

Opening Cursors

Syntax :
OPEN cursor_name ;

Open the cursor to execute the query


Use cursor attributes to test the outcome after a fetch
Example :

OPEN dept_cursor ;
Fetching Data from the cursor

Syntax :
FETCH cursor_name INTO [variable1, variable2,] |
record_name ;

Retrieve the current row values into variables.

Include the same number of variables .

Make sure that the data types are compatible.

Example :
FETCH dept_cursor INTO v_no, v_name, v_location ;
Closing the cursor

Syntax :
CLOSE cursor_name ;

Close the cursor after completing the processing of the rows .

Reopen the cursor, if required


Do not attempt to fetch data from a cursor after it has been closed.

Explicit Cursor Attributes


Controlling Multiple Fetches

Process several rows from an explicit cursor using a loop

Fetch a row with each iteration

Use explicit cursor attributes to test the success of each fetch

Use %ROWCOUNT, to retrieve an exact number of rows

Use %NOTFOUND, to determine when to exit the loop

We can use RECORD structures to fetch the rows of the cursor

Note :
Before the first fetch %NOTFOUND returns NULL
DECLARE
CURSOR dept_cursor IS
SELECT * FROM dept ;
dept_record dept_cursor % ROWTYPE ;
BEGIN
OPEN dept_cursor ;
LOOP
FETCH dept_cursor INTO dept_record ;
EXIT WHEN dept_cursor % NOTFOUND ;
DBMS_OUTPUT.PUT_LINE(dept_record .dname || location : ||
dept_record.loc) ;
END LOOP ;
CLOSE dept_cursor ;

END ;
Cursor FOR Loops

Syntax :
FOR record_name IN cursor_name LOOP
statement 1 ;
statement 2 ;

END LOOP ;

All processes Opening, Fetching, Closing are implicitly done

The record is implicitly declared

For fields refer to them as record_name . Field_name


DECLARE
CURSOR dept_cursor IS
SELECT * FROM dept ;
BEGIN
FOR dept_record IN student_cursor LOOP -- implicit open
DBMS_OUTPUT.PUT_LINE(dept_record.dname ||
location is ||
dept_record.loc) ;
END LOOP ;
-- implicit close
END ;

Syntax :
TYPE type_name is RECORD
( field_declaration [, field_declaration] ) ;
identifier type_name ;

Where field_declaration is :
field_name { field_type | variable % TYPE |
table.column%TYPE | table %ROWTYPE}
[ [NOT NULL] { := | DEFAULT } expr ]
DECLARE
TYPE student IS RECORD
( name varchar2(25),
htnumber varchar2(25),
status varchar2(10) ) ;
candidate student ;
BEGIN

SELECT stu_name,status INTO candidate.name, candidate.status FROM


students
WHERE RegdNo = 1116097 ;
DBMS_OUTPUT.PUT_LINE(candidate.name||is||candidate.status) ;
END ;

Declare a variable according to a collection of columns in a database table or


view.

Prefix %ROWTYPE with the database table.

Fields in the record take their names and data types from the columns of the table
or view

Syntax :
identifier
reference % ROWTYPE ;

Advantages :
- The number of columns and data types of underlying database columns need not be
known
- The number of columns and data type may change at run time.
DECLARE
candidate students % ROWTYPE ;
BEGIN
SELECT * INTO candidate
FROM students
WHERE RegdNo = 1116097 ;
DBMS_OUTPUT.PUT_LINE(candidate.name||is||
candidate.status) ;
END ;
Handling Exceptions with PL/SQL

An exception is an identifier in PL/SQL that is raised during execution

It is raised when
- An Oracle error occurs
- You raise it explicitly

It can be handled by
- Trapping it with a handler
- Propagating it to the calling environment
Exception Types
Trapping Exceptions

Syntax :
EXCEPTION
WHEN exception1 [ OR exception2] THEN
statement(s) ;
[WHEN exception3 [OR exception4] THEN
statement(s) ;

]
[WHEN OTHERS THEN
statement(s) ;
]
Trapping Predefined Oracle Server Errors

Reference the standard name in the exception handling routine

Sample predefined exceptions :


- NO_DATA_FOUND
- TOO_MANY_ROWS
- INVALID_CURSOR
- ZERO_DIVIDE
- DUP_VAL_ON_INDEX

PL/SQL declares predefined exceptions in the STANDARD package.


DECLARE
emp_record emp%ROWTYPE ;
BEGIN
SELECT * INTO emp_record
FROM emp WHERE deptno IS NULL;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE(Every body is in some department ) ;
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE(More people with no department ) ;
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE( SOME ERROR OCCURED) ;
END ;
Nonpredefined Error

Trapping Nonpredefined Oracle Server Errors

Steps :
Declare
Declarative section
Associate
Declarative section
Reference
Exception-handling section

To associate an exception name with an oracle error number, use PRAGMA


EXCEPTION_INIT.
DECLARE
x varchar2(5);
num_val exception;
PRAGMA EXCEPTION_INIT(num_val , -6502);
BEGIN

x:='welcome';
dbms_output.put_line('x='||x);
EXCEPTION
when num_val then
dbms_output.put_line('my exception');
END ;
Functions for Trapping Exceptions

When an exception occurs, identify the associated error code and message by
using two functions :
- SQLCODE : Returns the numeric value for the error code
- SQLERRM : Returns character data containing the message associated with the error
number
- Useful to know the error code and message in OTHERS exception block

All Oracle server errors return negative numbers except NO_DATA_FOUND,


which returns +100
Example
DECLARE
x varchar2(5) ;
BEGIN
x := hello world ;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(SQLERRM || OCCURRED );
END ;
Trapping User-Defined Exceptions

To define our own exceptions


Declare
IN
Declarative Section
Raise
IN
Executable section
Reference
IN
Exception-handling section

The exception must be raised explicitly

To raise the exception use


RAISE exception_name ;

DECLARE
e_invalid_deptno
EXCEPTION ;
BEGIN
DELETE FROM emp
WHERE deptno = (SELECT MAX(deptno)+1 FROM dept );
IF SQL%NOTFOUND THEN
RAISE e_invalid_deptno ;
EXCEPTION

WHEN e_invalid_deptno THEN


DBMS_OUPT.PUT_LINE(no candidate with that
department no);
END ;
DECLARE
name varchar2(15) ;
BEGIN
name := hello world ;
DECLARE
name varchar2(5) ;
BEGIN
name := hello India ;
DBMS_OUTPUT.PUT_LINE(name) ;
END ;
DBMS_OUTPUT.PUT_LINE(name) ;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(SQLERRM) ;
END ;
The RAISE_APPLICATION_ERROR Procedure

Use this procedure to issue user-defined error messages from stored subprograms

Report errors to your application and avoid returning unhandled exceptions

Syntax :
raise_application_error( error_number, message [,
{TRUE|FALSE} ] ) ;

Used in two different places :


- Executable section
- Exception section

Returns error condition to user in a manner consistent with other Oracle server
errors
DECLARE
e_invalid_deptno
EXCEPTION ;
BEGIN
DELETE FROM emp
WHERE deptno = (SELECT MAX(deptno)+1 FROM dept );
IF SQL%NOTFOUND THEN
RAISE_APPLICATION_ERROR(-20345,No candidate
with such department number);
END ;

Objective

At the end of the session participants will be able to appreciate the use of

Functions

Procedures

Packages

Triggers
Agenda

Functions

Stored Procedures

Packages

Triggers

Sub Programs
A subprogram :
Is a named PL/SQL block that can accept parameters and be invoked from a
calling environment

Is of two types :
- A procedure that performs an action
- A function that computes a value

Provides modularity, reusability, extensibility, and maintainability

Provides easy maintenance, improved data security and integrity, improved


performance, and improved code clarity
Structure of a Sub Program
< header >
IS | AS
Declaration section

BEGIN
Executable section
EXCEPTION
Exception section
END ;
Functions

(optional)

A function

Is a named PL/SQL block that returns a value

Can be stored in the database as a schema object for repeated execution

Can be called as part of an expression

Can accept parameters


Functions

Syntax :
CREATE [OR REPLACE] FUNCTION function_name
[ parameter1 [mode] datatype1, parameter2 [mode] datatype2,... ]
RETURN data type
IS | AS
PL/SQL Block ;

The PL/SQL Block must have at least on RETURN statement.

Creating a Function

Write the code of the function

Compile the code


- This will create the Pcode

Invoke the function from a PL/SQL Block.

Example :

CREATE or REPLACE function square(no number)


RETURN number is
begin
RETURN no * no ;
end square;

SELECT square(20) FROM DUAL ;

Advantages

Can Invoke them as part of PL/SQL expression

SQL

Extend SQL where activities are too complex, too awkward, or unavailable with

They can be called by:


- select list of a SELECT command
- condition of the WHERE and HAVING clauses
- CONNECT BY, START WITH, ORDER BY and GROUP BY clauses
- VALUES clause of the INSERT command
- SET clause of the UPDATE command
Restrictions on Calling Functions

To be callable from SQL expressions, a user-defined function :

- must be a stored function


- should Accept and return only valid SQL data types, not PL/SQL specific types
- can not contain DML statements
- can not contain statements that end transactions
Functions called from UPDATE/DELETE statements on a table T cannot contain
DML or query on same table T

They should not contain calls to subprograms that break the previous restrictions

Removing Functions

To drop a function
DROP FUNCTION function_name ;

Example :
DROP FUNCTION square ;

All the privileges granted on a function are revoked when the function is dropped.

Required Privileges

In order to create and operate subprograms one should have


these system privileges
- CREATE (ANY) PROCEDURE
- ALTER ANY

PROCEDURE

- DROP

PROCEDURE

ANY

- EXECUTE ANY PROCEDURE


Procedure

A procedure is a type of subprogram that performs an action

Can be stored in the database, as a schema object, for repeated execution.

Syntax :
CREATE [OR REPLACE] PROCEDURE procedure_name
[ (parameter1 [mode1] datatype1, parameter2 [mode2]
datatype2, ) ]
IS | AS
PL/SQL Block ;

The REPLACE option specifies the recreation of procedure if exists

Developing Procedures

Write the code to create a procedure

Compile the code


- This generates P code

Execute the procedure


- When the procedure is successfully created, it can be executed any number of times
using EXECUTE command.

Parameter Modes
Declaring Procedures

CREATE or REPLACE procedure

ins_emp( empno number,empname varchar2,deptno number)


IS
BEGIN
insert into emp values(empno,ename,deptno);
END ins_emp ;

It can be invoked as
Execute ins_emp(123, sunil , 20);

Exceptions

CREATE PROCEDURE sel_emp ( p_empno emp.empno%type ) IS


emprecord emp%ROWTYPE ;

BEGIN
SELECT * INTO emprecord
FROM emp
WHERE empno = p_empno ;
DBMS_OUTPUT.PUT_LINE( 'hello || emprecord.ename ) ;
END ;

CREATE PROCEDURE print_details( p_empnumber emp.empno%TYPE ) IS


emprecord

emp%ROWTYPE ;

BEGIN
sel_emp(p_empnumber);
DBMS_OUTPUT.PUT_LINE( 'Bye.. ' || p_empnumber );
EXCEPTION

WHEN OTHERS THEN

DBMS_OUTPUT.PUT_LINE('exception occurred');
END ;
Removing Procedures

Use Drop statement

Syntax :
DROP PROCEDURE procedure_name ;

Example :
DROP PROCEDURE ins_emp ;

Procedures Vs Functions
Packages

Group logically related PL/SQL types, items, and subprograms

Consist of two parts :


- Specification
:
interface to application
- Body
:
implementation of specification
Cannot be invoked, parameterized, or nested

Components of a Package
Public package constructs :
- Those that are declared in package specification and defined in the package body
- These can be referenced from any Oracle server environment

- The visibility is global


Private package constructs :
- Those that are declared and defined within the package body
- These can be referenced only by other constructs which are
part of the same package.
- The visibility is local
Developing a Package

Write the text of the CREATE PACKAGE statement

Compile the script file which generates P code and


stores it

Write the text of the CREATE PACKAGE BODY statement

Compile the source code which generates P code and stores it

Invoke any public construct within the package from an Oracle server environment

Creating the Package Specification

Syntax :
CREATE [OR REPLACE] PACKAGE package_name
IS | AS
public type and item declarations
subprogram specifications
END package_name ;

The REPALCE option drops and recreates the specification

Variables declared in the specification are initialized to NULL by default

All constructs declared in specification are visible to users who are granted
privileges on the package.

Example

CREATE OR REPLACE PACKAGE operations


IS
temp number ;
function raise_to (p_no1 number, p_no2 number)
return number ;
end ;

temp is a global variable initialized to NULL by default

raise_to is a public function that is implemented in the package body


Creating the Package Body

Syntax :

CREATE [OR REPLACE] PACKAGE BODY packagename


IS | AS
private type and item declarations
subprogram bodies
END packagename ;
Example
CREATE OR REPLACE PACKAGE BODY operations IS
local number ;
function raise_to (p_no1 number,p_no2 number)
return number
IS
BEGIN
local := (p_no1) ** (p_no2) ;
RETURN local ;
END ;
END operations;
Invoking Package Constructs

Can be invoked directly from a procedure / function within the same package

To access the procedure/function outside of package


prefix the package name before it separated by a period
Syntax : package_name . Procedure_name [(parameters)]

Example :
SELECT operations.raise_to(12,10) FROM DUAL ;
Removing Packages

To remove the package specification and the body use

DROP PACKAGE package_name ;

To remove only package body use


DROP PACKAGE BODY package_name;

Example :
DROP PACKAGE operations ;

Guidelines for Developing Packages

Construct packages for general use

Define the package specification before the body

The package specification should contain only those constructs that you want to
be public

Place items in the declaration part of the package body when you must maintain
them throughout a session or across transactions.

Changes to the package specification require recompilation of each referencing


subprogram

Advantages of Packages

Modularity : Encapsulate related constructs.

Easier application design : code and compile specification and body separately.

Hiding information : all coding is hidden in the package body.

Added functionality : persistency of variables and cursors

Better performance :
- The entire package is loaded in memory when the package is first referenced.
- There is only one copy in memory for all users.

Overloading : multiple subprograms with same name.


Triggers
A trigger :

Is a PL/SQL block or PL/SQL procedure associated with a table, view, schema,


or the database

Executes implicitly whenever a particular event takes place


Can be either :
- Application Trigger : Fires whenever an event occurs with a particular application

- Database Trigger : Fires whenever a data event or system event occurs on a schema
or database

A triggering statement contains :

Trigger timing
- for table : before , after
- for view : instead of

Triggering event : INSERT, UPDATE, or DELETE

Table Name : On table, view

Trigger Type : Row or statement

WHEN clause : Restricting condition

Trigger body : PL/SQL block


Trigger timing
Specifies the timing of the trigger firing..

BEFORE
Execute the trigger body before the triggering DML event on a table.

AFTER
Execute the trigger body after the triggering DML event on a table

INSTEAD OF
Execute the trigger body instead of the triggering statement. This is used for
views that are not otherwise modifiable.
Trigger user event
Specifies the DML statement causing the trigger to execute.

It can be

INSERT

UPDATE

DELETE
Trigger type
Specifies the execution type of trigger.
It can be :

Statement Trigger:
-executes once for the triggering event.

- It fires once, even if no rows are affected at all.


- useful when action does not depend on data from rows
Row Trigger :
- executes once for each row affected by triggering event.

- It is not executed if the triggering event affects no rows


- useful if action depends on data of rows that affected
Trigger body :

- The action performed by triggers


- It is a PL/SQL block or call to a procedure
Syntax :
CREATE [OR REPLACE] TRIGGER trigger_name
timing
event1 [or event 2 or event3]
ON table_name
trigger_body

CREATE OR REPLACE TRIGGER check_sal


BEFORE INSERT ON emp
BEGIN
if(USER <> SCOTT) then
raise_application_error(-20003, not a valid user);
end if;
END;

CREATE OR REPLACE dept_trig


BEFORE INSERT or UPDATE on dept
BEGIN
IF INSERTING THEN
IF (TO_CHAR(SYSDATE,DY) IN(SAT, SUN) )

THEN RAISE_APPLICATION_ERROR( -20345,You


business days only);
END IF;

can insert data in

ELSIF UPDATING THEN


IF (TO_CHAR(SYSDATE,DY) IN(SAT, SUN) )
THEN RAISE_APPLICATION_ERROR( -20355, You can change data in
business days only);
END IF;
END IF;
END ;
INSTEAD OF Triggers

A view can not be modified by normal DML statements if the view query contains
set operators, group functions or joins

In such cases we need INSTEAD OF triggers

They are used to perform INSERT, UPDATE,or DELETE operations directly in


the underlying tables.

Syntax :
CREATE [OR REPLACE] TRIGGER trigger_name
INSTEAD OF event1 [ OR event2 OR event3]
ON view_name
[REFERENCING OLD AS old/NEW AS new]
[FOR EACH ROW]
trigger_body

CREATE VIEW emp_dept_vu


IS
SELECT empno,ename,e.deptno, dname, loc

FROM emp e,dept e


WHERE e.deptno=d.deptno ;
TRIGGERS Vs Stored Procedures
Managing Triggers

Disabling or re enabling a database trigger


ALTER TRIGGER trigger_name DISABLE | ENABLE

Disable or re enable all triggers for a table


ALTER TABLE table_name DISABLE|ENABLE ALL
Recompile a trigger for a table

TRIGGERS

ALTER TRIGGER trigger_name COMPILE

Remove a trigger
DROP TRIGGER trigger_name

Note : If table is dropped all relevant triggers are also dropped


Trigger Execution Model

Execute all BEFORE STATEMENT triggers

Loop for each row affected :


- execute all BEFORE ROW triggers
- execute all AFTER ROW triggers

Execute the DML statement and perform integrity constraint checking

Execute all AFTER STATEMENT triggers

Update emp set deptno = 99 where empno = 7891 ;

CREATE OR REPLACE TRIGGER emp_dept_trigger


AFTER UPDATE ON emp
FOR EACH ROW
BEGIN
INSERT INTO dept(deptno,dname)
VALUES(99, ERP);
END ;

Update emp set deptno = 99 where empno = 7891 ;

Viewing Trigger Information


USER_OBJECTS
for object information

USER_TRIGGER

for the text of the tiger

USER_ERRORS

for compilation errors

Example :
SELECT trigger_body from USER_TRIGGERS
WHERE trigger_name = WISH_TRIG ;
Guidelines for Designing Triggers

Design triggers to :

- perform related actions


- centralize global operations

Do not design triggers :


- where functionality is already built into the Oracle server
- that duplicate other triggers

Create, store procedures and invoke them in a trigger, if the PL/SQL code is very
lengthy.

Das könnte Ihnen auch gefallen