0% found this document useful (0 votes)
87 views

SQL Queries

The document discusses various SQL queries including: (1) The SELECT statement to retrieve data from tables. (2) The DISTINCT keyword to eliminate duplicate rows. (3) Aliases and subqueries to select data from multiple tables. (4) Aggregate functions like SUM, AVG, MAX, MIN and COUNT to summarize query results.

Uploaded by

rel786
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
87 views

SQL Queries

The document discusses various SQL queries including: (1) The SELECT statement to retrieve data from tables. (2) The DISTINCT keyword to eliminate duplicate rows. (3) Aliases and subqueries to select data from multiple tables. (4) Aggregate functions like SUM, AVG, MAX, MIN and COUNT to summarize query results.

Uploaded by

rel786
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 26

1

SQL Queries

(1) Basics of the SELECT Statement


In a relational database, data is stored in tables. An example table would relate
Social Security Number, Name, and Address:
EmployeeAddressTable
SSN FirstName LastName Address City State
51268745 83 First
Joe Smith Howard Ohio
8 Street
75842001 Losantivill
Mary Scott 842 Vine Ave. Ohio
2 e
10225489
Sam Jones 33 Elm St. Paris New York
6
87651256
Sarah Ackerman 440 U.S. 110 Upton Michigan
3

Now, let's say you want to see the address of each employee. Use the SELECT
statement, like so:

SELECT FirstName, LastName, Address, City, State FROM EmployeeAddressTable;

The following is the results of your query of the database:


Last
First Name Address City State
Name
83 First
Joe Smith Howard Ohio
Street
Losantivill
Mary Scott 842 Vine Ave. Ohio
e
Sam Jones 33 Elm St. Paris New York
Sarah Ackerman 440 U.S. 110 Upton Michigan

To get all columns of a table without typing all column names, use:

SELECT * FROM TableName;

(2) DISTINCT and Eliminating Duplicates


2

Let's say that you want to list the ID and names of only those people who have sold
an antique. Obviously, you want a list where each seller is only listed once--you
don't want to know how many antiques a person sold, just the fact that this person
sold one. This means that you will need to tell SQL to eliminate duplicate sales
rows, and just list each person only once. To do this, use the DISTINCT keyword.
To throw in one more twist, we will also want the list alphabetized by LastName,
then by FirstName (on a LastName tie). Thus, we will use the ORDER BY clause:

SELECT DISTINCT SELLERID, OWNERLASTNAME, OWNERFIRSTNAME


FROM ANTIQUES, ANTIQUEOWNERS WHERE SELLERID = OWNERID
ORDER BY OWNERLASTNAME, OWNERFIRSTNAME;

(3) Aliases & In Subqueries

In this section, we will talk about Aliases, In and the use of subqueries, and how
these can be used in a 3-table example. First, look at this query which prints the
last name of those owners who have placed an order and what the order is, only
listing those orders which can be filled (that is, there is a buyer who owns that
ordered item):

SELECT OWN.OWNERLASTNAME Last Name,


ORD.ITEMDESIRED Item Ordered
FROM ORDERS ORD, ANTIQUEOWNERS OWN
WHERE ORD.OWNERID = OWN.OWNERID
AND ORD.ITEMDESIRED IN (SELECT ITEM FROM ANTIQUES);

This gives:
Last Name Item Ordered
--------- ------------
Smith Table
Smith Desk
Akins Chair
Lawson Mirror

(4) Aggregate Functions

I will discuss five important aggregate functions: SUM, AVG, MAX, MIN, and COUNT.
They are called aggregate functions because they summarize the results of a
3

query, rather than listing all of the rows.


SUM () gives the total of all the rows, satisfying any conditions, of the given
column, where the given column is numeric.
AVG () gives the average of the given column.
MAX () gives the largest figure in the given column.
MIN () gives the smallest figure in the given column.
COUNT(*) gives the number of rows satisfying the conditions.
Looking at the tables at the top of the document, let's look at three examples:

SELECT SUM(SALARY), AVG(SALARY) FROM EMPLOYEE;

This query shows the total of all salaries in the table, and the average salary of all
of the entries in the table.

SELECT MIN(BENEFITS) FROM EMPLOYEE WHERE POSITION = 'Manager';

This query gives the smallest figure of the Benefits column, of the employees who
are Managers, which is 12500.

SELECT COUNT(*) FROM EMPLOYEE WHERE POSITION = 'Staff';

This query tells you how many employees have Staff status (3).

(5) Views

In SQL, you might (check your DBA) have access to create views for yourself. What
a view does is to allow you to assign the results of a query to a new, personal
table, that you can use in other queries, where this new table is given the view
name in your FROM clause. When you access a view, the query that is defined in
your view creation statement is performed (generally), and the results of that
query look just like another table in the query that you wrote invoking the view.

For example, to create a view:

CREATE VIEW ANTVIEW AS SELECT ITEMDESIRED FROM ORDERS;

Now, write a query using this view as a table, where the table is just a listing of all
Items Desired from the Orders table:

SELECT SELLERID FROM ANTIQUES, ANTVIEW WHERE ITEMDESIRED = ITEM;


4

This query shows all SellerID's from the Antiques table where the Item in that table
happens to appear in the Antview view, which is just all of the Items Desired in the
Orders table. The listing is generated by going through the Antique Items one-by-
one until there's a match with the Antview view. Views can be used to restrict
database access, as well as, in this case, simplify a complex query.

(6) Creating New Tables

All tables within a database must be created at some point in time...let's see how
we would create the Orders table:

CREATE TABLE ORDERS (OWNERID INTEGER NOT NULL, TEMDESIRED CHAR(40)


NOT NULL);

(7) Altering Tables

Let's add a column to the Antiques table to allow the entry of the price of a given
Item:

ALTER TABLE ANTIQUES ADD (PRICE DECIMAL(8,2) NULL);

The data for this new column can be updated or inserted as shown later.

(8) Adding Data

To insert rows into a table, do the following:

INSERT INTO ANTIQUES VALUES (21, 01, 'Ottoman', 200.00);

This inserts the data into the table, as a new row, column-by-column, in the pre-
defined order. Instead, let's change the order and leave Price blank:

INSERT INTO ANTIQUES (BUYERID, SELLERID, ITEM) VALUES (01, 21, 'Ottoman');

(9) Deleting Data

Let's delete this new row back out of the database:

DELETE FROM ANTIQUES WHERE ITEM = 'Ottoman';


5

But if there is another row that contains 'Ottoman', that row will be deleted also.
Let's delete all rows (one, in this case) that contain the specific data we added
before:

DELETE FROM ANTIQUES WHERE ITEM = 'Ottoman' AND BUYERID = 01 AND


SELLERID = 21;

(10) Updating Data

Let's update a Price into a row that doesn't have a price listed yet:

UPDATE ANTIQUES SET PRICE = 500.00 WHERE ITEM = 'Chair';

This sets all Chair's Prices to 500.00. As shown above, more WHERE conditionals,
using AND, must be used to limit the updating to more specific rows. Also,
additional columns may be set by separating equal statements with commas.

Joins

A join is a query that combines rows from two or more tables, views, or
materialized views. Oracle performs a join whenever multiple tables
appear in the queries FROM clause. The query's select list can select any
columns from any of these tables. If any two of these tables have a column
name in common, you must qualify all references to these columns
throughout the query with table names to avoid ambiguity.

Join Conditions
Most join queries contain WHERE clause conditions that compare two
columns, each from a different table. Such a condition is called a join
condition. To execute a join, Oracle combines pairs of rows, each
containing one row from each table, for which the join condition evaluates
to TRUE. The columns in the join conditions need not also appear in the
select list.

Equijoins

An equijoin is a join with a join condition containing an equality operator (


= ). An equijoin combines rows that have equivalent values for the
specified columns.
6

For example the following query returns empno,name,sal,deptno and


department name and city from department table.

select emp.empno,emp.ename,emp.sal,emp.deptno,dept.dname,dept.city
from emp,dept where emp.deptno=dept.deptno;

The above query can also be written like, using aliases, given below.

select e.empno, e.ename, e.sal, e.deptno, d.dname, d.city from emp e,


dept d where emp.deptno=dept.deptno;

The above query can also be written like given below without using table
qualifiers.

select empno, ename, sal, dname, city from emp, dept where
emp.deptno=dept.deptno;

And if you want to see all the columns of both tables then the query can
be written like this.

select * from emp,dept where emp.deptno=dept.deptno;

Non Equi Joins.

Non equi joins is used to return result from two or more tables where exact
join is not possible.

For example we have emp table and salgrade table. The salgrade table
contains grade and their low salary and high salary. Suppose you want to
find the grade of employees based on their salaries then you can use NON
EQUI join.

select e.empno, e.ename, e.sal, s.grade from emp e, salgrade s where


e.sal between s.lowsal and s.hisal

Self Joins

A self join is a join of a table to itself. This table appears twice in the
FROM clause and is followed by table aliases that qualify column names in
the join condition. To perform a self join, Oracle combines and returns rows
of the table that satisfy the join condition.
For example the following query returns employee names and their
manager names for whom they are working.
7

Select e.empno, e.ename, m.ename Manager from emp e,


emp m where e.mgrid=m.empno

Inner Join

An inner join (sometimes called a "simple join") is a join of two or more


tables that returns only those rows that satisfy the join condition.

Outer Joins

An outer join extends the result of a simple join. An outer join returns all
rows that satisfy the join condition and also returns some or all of those
rows from one table for which no rows from the other satisfy the join
condition.

To write a query that performs an outer join of tables A and B and returns
all rows from A (a left outer join), use the ANSI LEFT [OUTER] JOIN
syntax, or apply the outer join operator (+) to all columns of B in the join
condition. For all rows in A that have no matching rows in B, Oracle returns
null for any select list expressions containing columns of B.

To write a query that performs an outer join of tables A and B and returns
all rows from B (a right outer join), use the ANSI RIGHT [OUTER] syntax,
or apply the outer join operator (+) to all columns of A in the join
condition. For all rows in B that have no matching rows in A, Oracle returns
null for any select list expressions containing columns of A.

To write a query that performs an outer join and and returns all rows from
A and B, extended with nulls if they do not satisfy the join condition (a full
outer join), use the ANSI FULL [OUTER] JOIN syntax.

For example the following query returns all the employees and department
names and even those department names where no employee is working
for Left Outer Join.

select e.empno,e.ename,e.sal,e.deptno,d.dname,d.city from emp e, dept


d where e.deptno(+)=d.deptno;

SQL Operators
SQL Operators Overview
8

An operator manipulates individual data items and returns a result. The


data items are called operands or arguments. Operators are represented
by special characters or by keywords. For example, the multiplication
operator is represented by an asterisk (*) and the operator that tests for
nulls is represented by the keywords IS NULL. There are two general
classes of operators: unary and binary. Oracle lite SQL also supports set
operators.
Table Levels of Precedence of the Oracle Lite SQL Operators
Precedence
Level SQL Operator
1 Unary + - arithmetic operators, PRIOR operator
2 * / arithmetic operators
3 Binary + - arithmetic operators, || character operators
4 All comparison operators
5 NOT logical operator
6 AND logical operator
7 OR logical operator

Arithmetic Operators

Arithmetic operators manipulate numeric operands. The - operator is also


used in date arithmetic.

Table Arithmetic Operators


Operato
r Description Example
+ Makes operand positive SELECT +3 FROM DUAL;
(unary)
- (unary) Negates operand SELECT -4 FROM DUAL;
/ Division (numbers and dates) SELECT SAL / 10 FROM EMP;
* Multiplication SELECT SAL * 5 FROM EMP;
+ Addition (numbers and dates) SELECT SAL + 200 FROM EMP;
- Subtraction (numbers and SELECT SAL - 100 FROM EMP;
dates)
9

Character Operators

Character operators are used in expressions to manipulate character


strings.

Character Operators

Operat
or Description Example
|| Concatenates SELECT 'The Name of the employee is: ' ||
character strings ENAME FROM EMP;

Concatenating Character Strings

With Oracle Lite, you can concatenate character strings with the following
results:
Concatenating two character strings results in another character string.

Oracle Lite preserves trailing blanks in character strings by concatenation,


regardless of the strings' datatypes.

Oracle Lite provides the CONCAT character function as an alternative to


the vertical bar operator. For example:

SELECT CONCAT (CONCAT (ENAME, ' is a '),job) FROM EMP WHERE SAL >
2000;

This returns:
CONCAT(CONCAT(ENAME
-------------------------
KING is a PRESIDENT
BLAKE is a MANAGER
CLARK is a MANAGER
JONES is a MANAGER
FORD is a ANALYST
SCOTT is a ANALYST

6 rows selected.
Comparison Operators
10

Comparison operators are used in conditions that compare one expression


with another. The result of a comparison can be TRUE, FALSE, or
UNKNOWN.

Table Comparison Operators


Operator Description Example
= Equality test. SELECT ENAME
"Employee" FROM EMP
WHERE SAL = 1500;
!=, ^=, <> Inequality test. SELECT ENAME FROM
EMP WHERE SAL ^=
5000;
> Greater than test. SELECT ENAME
"Employee", JOB "Title"
FROM EMP WHERE SAL
> 3000;
< Less than test. SELECT * FROM PRICE
WHERE MINPRICE < 30;
>= Greater than or equal to test. SELECT * FROM PRICE
WHERE MINPRICE >=
20;
<= Less than or equal to test. SELECT ENAME FROM
EMP WHERE SAL <=
1500;
IN "Equivalent to any member of" test. SELECT * FROM EMP
Equivalent to "= ANY". WHERE ENAME IN
('SMITH', 'WARD');
ANY/ SOME Compares a value to each value in a SELECT * FROM DEPT
list or returned by a query. Must be WHERE LOC = SOME
preceded by =, !=, >, <, <=, or ('NEW YORK','DALLAS');
>=. Evaluates to FALSE if the query
returns no rows.
NOT IN Equivalent to "!= ANY". Evaluates to SELECT * FROM DEPT
FALSE if any member of the set is WHERE LOC NOT IN
NULL. ('NEW YORK', 'DALLAS');
ALL Compares a value with every value SELECT * FROM emp
in a list or returned by a query. Must WHERE sal >= ALL
be preceded by =, !=, >, <, <=, or (1400, 3000);
>=. Evaluates to TRUE if the query
11

Operator Description Example


returns no rows.
[NOT] [Not] greater than or equal to x and SELECT ENAME, JOB
BETWEEN x less than or equal to y. FROM EMP WHERE SAL
and y BETWEEN 3000 AND
5000;
EXISTS TRUE if a sub-query returns at least SELECT * FROM EMP
one row. WHERE EXISTS (SELECT
ENAME FROM EMP
WHERE MGR IS NULL);
x [NOT] TRUE if x does [not] match the SELECT * FROM EMP
LIKE y pattern y. Within y, the character WHERE ENAME LIKE '%E
[ESCAPE z] "%" matches any string of zero or %';
more characters except null. The
character "_" matches any single
character. Any character following
ESCAPE is interpretted litteraly,
useful when y contains a percent
(%) or underscore (_).
IS [NOT] Tests for nulls. This is the only SELECT * FROM EMP
NULL operator that should be used to test WHERE COMM IS NOT
for nulls. NULL AND SAL > 1500;

Logical Operators

Logical operators manipulate the results of conditions.

Table Logical Operators


Operat
or Description Example
NOT Returns TRUE if the following condition SELECT * FROM EMP
is FALSE. Returns FALSE if it is TRUE. If WHERE NOT (job IS NULL)
it is UNKNOWN, it remains UNKNOWN. SELECT * FROM EMP
WHERE NOT (sal
BETWEEN 1000 AND
2000)
AND Returns TRUE if both component SELECT * FROM EMP
conditions are TRUE. Returns FALSE if WHERE job='CLERK' AND
either is FALSE; otherwise returns deptno=10
UNKNOWN.
12

Operat
or Description Example
OR Returns TRUE if either component SELECT * FROM emp
condition is TRUE. Returns FALSE if WHERE job='CLERK' OR
both are FALSE. Otherwise, returns deptno=10
UNKNOWN.

Set Operators

Set operators combine the results of two queries into a single result.

Table Set Operators


Operator Description Example
UNION Returns all distinct rows SELECT * FROM
selected by either query. (SELECT ENAME FROM EMP
WHERE JOB = 'CLERK'
UNION
SELECT ENAME FROM EMP
WHERE JOB = 'ANALYST');
UNION ALL Returns all rows selected SELECT * FROM
by either query, including (SELECT SAL FROM EMP
all duplicates. WHERE JOB = 'CLERK'
UNION
SELECT SAL FROM EMP
WHERE JOB = 'ANALYST');
INTERSECT and Returns all distinct rows SELECT * FROM orders_list1
INTERSECT ALL selected by both queries. INTERSECT
SELECT * FROM orders_list2
MINUS Returns all distinct rows SELECT * FROM (SELECT SAL
selected by the first FROM EMP WHERE JOB =
query but not the second. 'PRESIDENT'
MINUS
SELECT SAL FROM EMP
WHERE JOB = 'MANAGER');

Note: :
The syntax for INTERSECT ALL is supported, but it returns
the same results as INTERSECT.
13

Other Operators

The following lists other operators:

Table Other Operators


Operat
or Description Example
(+) Indicates that the preceding column is SELECT ENAME, DNAME
the outer join column in a join. FROM EMP, DEPT
WHERE DEPT.DEPTNO =
EMP.DEPTNO (+);
PRIOR Evaluates the following expression for SELECT EMPNO, ENAME,
the parent row of the current row in a MGR FROM EMP
hierarchical, or tree-structured query. In CONNECT BY PRIOR
such a query, you must use this EMPNO = MGR;
operator in the CONNECT BY clause to
define the relationship between the
parent and child rows.

Database Triggers

A database triggers is stored PL/SQL program unit associated with a


specific database table or view. The code in the trigger defines the action
the database needs to perform whenever some database manipulation
(INSERT, UPDATE, and DELETE) takes place.
Unlike the stored procedure and functions, which have to be called
explicitly, the database triggers are fires (executed) or called implicitly
whenever the table is affected by any of the above said DML operations.
14

Till oracle 7.0 only 12 triggers could be associated with a given table, but
in higher versions of Oracle there is no such limitation. A database trigger
fires with the privileges of owner not that of user

A database trigger has three parts

A triggering event
A trigger constraint (Optional)
Trigger action
A triggering event can be an insert, update, or delete statement or an
instance shutdown or startup etc. The trigger fires automatically when any
of these events occur a trigger constraint specifies a Boolean expression
that must be true for the trigger to fire. This condition is specified using
the WHEN clause. The trigger action is a procedure that contains the code
to be executed when the trigger fires.

Types of Triggers

The following are the different types of triggers.

Row triggers and statement triggers

A Row trigger fires once for each row affected. It uses FOR EACH ROW
clause. They are useful if trigger action depends on number of rows
affected.

Statement Trigger fires once, irrespective of number of rows affected in


the table. Statement triggers are useful when triggers action does not
depend on

Before and afterTriggers

While defining the trigger we can specify whether to perform the trigger
action (i.e. execute trigger body) before or after the triggering statement.
BEFORE and AFTER triggers fired by DML statements can only be defined
on tables.

BEFORE triggers The trigger action here is run before the trigger
statement.

AFTER triggers The trigger action here is run after the trigger statement.
15

INSTEAD of Triggers provide a way of modifying views that can not be


modified directly using DML statements.

LOGON triggers fires after successful logon by the user and LOGOFF
trigger fires at the start of user logoff.

Points to ponder

A trigger cannot include COMMIT, SAVEPOINT and ROLLBACK.


We can use only one trigger of a particular type.
A table can have any number of triggers.
We use correlation names: new and: old can be used to refer to data in
command line and data in table respectively.

Triggers on DDL statements

DDL trigger are of the following types

BEFORE CREATE OR AFTER CREATE trigger is fired when a schema object is


created.
BEFORE OR AFTER ALTER trigger is fired when a schema object is altered.
BEFORE OR AFTER DROP trigger is fired when a schema object is dropped.

A trigger can be enabled means can be made to run or it can disable


means it cannot run. A trigger is automatically enabled when it is created.
We need re-enable trigger for using it if it is disabled. To enable or disable
a trigger using ALTER TRIGGER command, you must be owner of the
trigger or should have ALTER ANY TRIGGER privilege. To create a trigger
you must have CREATE TRIGGER privilege, which is given to as part of
RESOURCE privilege at the time of user creation.

Following figures give more understanding about triggers


16
17

PL/SQL subprograms

A subprogram is a named block of PL/SQL. There are two types of


subprograms in PL/SQL namely Procedures and Functions. Every
subprogram will have a declarative part, an executable part or body, and
an exception handling part, which is optional.
Declarative part contains variable declarations. Body of a subprogram
contains executable statements of SQL and PL/SQL. Statements to handle
exceptions are written in exception part.

When client executes a procedure are function, the processing is done in


the server. This reduces network traffic. The subprograms are compiled
and stored in the Oracle database as stored programs and can be invoked
whenever required. As they are stored in compiled form when called they
only need to be executed. Hence they save time needed for compilation.

Subprograms provide the following advantages

They allow you to write PL/SQL program that meet our need
They allow you to break the program into manageable modules.
They provide reusability and maintainability for the code.
18

Procedures

Procedure is a subprogram used to perform a specific action. A procedure


contains two parts specification and the body. Procedure specification
begins with CREATE and ends with procedure name or parameters list.
Procedures that do not take parameters are written without a parenthesis.
The body of the procedure starts after the keyword IS or AS and ends with
keyword END.

In the above given syntax things enclosed in between angular brackets


(< > ) are user defined and those enclosed in square brackets ([ ]) are
optional.

OR REPLACE is used to overwrite the procedure with the same name if


there is any.

AUTHID clause is used to decide whether the procedure should execute


with invoker (current-user or person who executes it) or with definer
(owner or person created) rights
19

Example

CREATE PROCEDURE MyProc (ENO NUMBER)


AUTHID DEFINER AS
BEGIN
DELETE FROM EMP
WHERE EMPNO= ENO;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE (No employee with this number);
END;

Let us assume that above procedure is created in SCOTT schema (SCOTT


user area) and say is executed by user SEENU. It will delete rows from the
table EMP owned by SCOTT, but not from the EMP owned by SEENU. It is
possible to use a procedure owned by one user on tables owned by other
users. It is possible by setting invoker-rights
Example

If a procedure is defined as GROSS (ESAL NUMBER, ECOM NUMBER)


If we call this procedure as GROSS (ESA, ECO) then parameters used are
called positional parameters. For Notational Parameters we use the
following syntax
GROSS (ECOM => ECO, ESAL => ESA)

A procedure can also be executed by invoking it as an executable


statement as shown below.
20

BEGIN
PROC1; --- PROC1 is name of the procedure.
END;
/

Oracle 9i: Exception Handling

An Exception is an error situation, which arises during program execution.


When an error occurs exception is raised, normal execution is stopped and
control transfers to exception-handling part. Exception handlers are
routines written to handle the exception. The exceptions can be internally
defined (system-defined or pre-defined) or User-defined exception.

Predefined exception is raised automatically whenever there is a


violation of Oracle coding rules. Predefined exceptions are those like
ZERO_DIVIDE, which is raised automatically when we try to divide a
number by zero. Other built-in exceptions are given below. You can handle
unexpected Oracle errors using OTHERS handler. It can handle all raised
exceptions that are not handled by any other handler. It must always be
written as the last handler in exception block.

CURSOR_ALREADY_OPEN Raised when we try to open an already open


cursor.
21

DUP_VAL_ON_INDEX When you try to insert a duplicate value into a


unique column

INVALID_CURSOR It occurs when we try accessing an invalid cursor


INVALID_NUMBER On usage of something other than number in place of
number value.

LOGIN_DENIED At the time when user login is denied

TOO_MANY_ROWS When a select query returns more than one row and
the destination variable can take only single value.

VALUE_ERROR When an arithmetic, value conversion, truncation, or


constraint error occurs.

Predefined exception handlers are declared globally in package


STANDARD. Hence we need not have to define them rather just use them.

The biggest advantage of exception handling is it improves readability and


reliability of the code. Errors from many statements of code can be
handles with a single handler. Instead of checking for an error at every
point we can just add an exception handler and if any exception is raised it
is handled by that. For checking errors at a specific spot it is always better
to have those statements in a separate begin end block.
22

Examples: Following example gives the usage of ZERO_DIVIDE exception

Exmpmple 2: I have explained the usage of NO_DATA_FOUND exception in


the following
23

The DUP_VAL_ON_INDEX is raised when a SQL statement tries to create


a duplicate value in a column on which a primary key or unique constraints
are defined.

Example to demonstrate the exception DUP_VAL_ON_INDEX.


24

More than one Exception can be written in a single handler as shown


below.

EXCEPTION

When NO_DATA_FOUND or TOO_MANY_ROWS then


Statements;
END;

User-defined Exceptions

A User-defined exception has to be defined by the programmer. User-


defined exceptions are declared in the declaration section with their type
as exception. They must be raised explicitly using RAISE statement, unlike
pre-defined exceptions that are raised implicitly. RAISE statement can also
be used to raise internal exceptions.

Declaring Exception:

DECLARE
myexception EXCEPTION;
BEGIN
------

Raising Exception:

BEGIN
RAISE myexception;
-------

Handling Exception:

BEGIN
------
----
EXCEPTION
WHEN myexception THEN
Statements;
END;
25

Points To Ponder:

An Exception cannot be declared twice in the same block.


Exceptions declared in a block are considered as local to that block and
global to its sub-blocks.
An enclosing block cannot access Exceptions declared in its sub-block.
Where as it possible for a sub-block to refer its enclosing Exceptions.

The following example explains the usage of User-defined Exception

RAISE_APPLICATION_ERROR

To display your own error messages one can use the built-in
RAISE_APPLICATION_ERROR. They display the error message in the same
way as Oracle errors. You should use a negative number between 20000
to 20999 for the error_number and the error message should not exceed
512 characters.
The syntax to call raise_application_error is
RAISE_APPLICATION_ERROR (error_number, error_message, { TRUE
| FALSE });
26

You might also like