DBMS Unit 3 Notes.docx 2
DBMS Unit 3 Notes.docx 2
Unit-3
Topics Covered: Basics of SQL-DDL,DML,DCL,TCL , Structure Creation, alternation , Defining
Constraints-Primary Key, Foreign Key, Unique, not null, check, IN operator ,
Functions-aggregation functions , Built-in Functions-numeric, date, string functions, string
functions, Set operations, Sub Queries, correlated sub queries , Nested Queries, View ,
Transaction Control Commands , Commit, Rollback, Save point , PL/SQL Concepts- Cursors ,
Stored Procedure, Functions Triggers and Exception Handling .
1
Neetu BanslaDBMS21CSC205P
Examples:
DROP TABLE table_name;
table_name: Name of the table to be deleted.
● ALTER: This is used to alter the structure of the database. ALTER TABLE – ADD
ADD is used to add columns into the existing table. Sometimes we may require to add
additional information, in that case we do not require to create the whole database
again, ADD comes to our rescue.
Syntax:
ALTER TABLE table_name
ADD (Columnname_1 datatype,
Columnname_2 datatype,
…
Columnname_n datatype);
● TRUNCATE: This is used to remove all records from a table, including all spaces
allocated for the records are removed. TRUNCATE statement is a Data Definition
Language (DDL) operation that is used to mark the extents of a table for deallocation
(empty for reuse). The result of this operation quickly removes all data from a table,
typically bypassing a number of integrity enforcing mechanisms. It was officially
introduced in the SQL:2008 standard.
The TRUNCATE TABLE mytable statement is logically (though not physically)
equivalent to the DELETE FROM mytable statement (without a WHERE clause).
Syntax:
TRUNCATE TABLE table_name;
table_name: Name of the table to be truncated.
DATABASE name - student_data
2
Neetu BanslaDBMS21CSC205P
● SELECT: It is used to retrieve data from the database. Select is the most commonly used
statement in SQL. The SELECT Statement in SQL is used to retrieve or fetch data from a
database. We can fetch either the entire table or according to some specified rules. The
data returned is stored in a result table. This result table is also called result-set.
Syntax:
SELECT column1, column2 FROM table_name
column1, column2: names of the fields of the table
table_name: from where we want to fetch
3
Neetu BanslaDBMS21CSC205P
4
Neetu BanslaDBMS21CSC205P
1. Granting SELECT Privilege to a User in a Table: To grant Select Privilege to a table
named “users” where User Name is Amit, the following GRANT statement should be
executed.
GRANT SELECT ON Users TO'Amit'@'localhost;
2. Granting more than one Privilege to a User in a Table: To grant multiple Privileges to
a user named “Amit” in a table “users”, the following GRANT statement should be
executed.
GRANT SELECT, INSERT, DELETE, UPDATE ON Users TO 'Amit'@'localhost
1. Granting All the Privilege to a User in a Table: To Grant all the privileges to a user
named “Amit” in a table “users”, the following Grant statement should be executed.
5
Neetu BanslaDBMS21CSC205P
● REVOKE: This command withdraws the user’s access privileges given by using the
GRANT command.
Revoke command withdraw user privileges on database objects if any granted. It does
operations opposite to the Grant command. When a privilege is revoked from a
particular user U, then the privileges granted to all other users by user U will be
revoked.
Syntax:
revoke privilege_name on object_name
from {user_name | public | role_name}
Example:
grant insert,
select on accounts to Ram
By the above command user ram has granted permissions on accounts database object like
he can query or insert into accounts.
revoke insert,
select on accounts from Ram
By the above command user ram’s permissions like query or insert on accounts database
object has been removed.
6
Neetu BanslaDBMS21CSC205P
Syntax:
COMMIT;
ROLLBACK;
● SAVEPOINT: Sets a save point within a transaction. It creates points within the
groups of transactions in which to ROLLBACK. A SAVEPOINT is a point in a
transaction in which you can roll the transaction back to a certain point without
rolling back the entire transaction.
SQL Constraints
SQL constraints are used to specify rules for the data in a table. Constraints are used to limit
the type of data that can go into a table. This ensures the accuracy and reliability of the data
7
Neetu BanslaDBMS21CSC205P
in the table. If there is any violation between the constraint and the data action, the action
is aborted.
Constraints can be column level or table level. Column level constraints apply to a column,
and table level constraints apply to the whole table.
Example
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar (255) NOT NULL,
FirstName varchar (255) NOT NULL,
Age int
);
Example
● PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each
row in a table
Example
8
Neetu BanslaDBMS21CSC205P
Age int
);
● FOREIGN KEY - Prevents actions that would destroy links between tables
Example
Example
Example
The DEFAULT constraint can also be used to insert system values, by using functions
like GETDATE ():
9
Neetu BanslaDBMS21CSC205P
● CREATE INDEX - Used to create and retrieve data from the database very quickly
Example
10
Neetu BanslaDBMS21CSC205P
6 F Null
Count ():
Count (*): Returns total number of records .i.e. 6.
Count (salary): Return number of Non Null values over the column salary. i.e.5.
Count (Distinct Salary): Return number of distinct Non Null values over the column salary
.i.e. 4
Sum ():
Sum (salary): Sum all Non Null values of Column salary i.e., 310
sum (Distinct salary): Sum of all distinct Non-Null values i.e., 250.
Avg ():
Avg (salary) = Sum (salary) / count (salary) = 310/5
Avg (Distinct salary) = Sum (Distinct salary) / Count (Distinct Salary) = 250/4
Min ():
Min (salary): Minimum value in the salary column except NULL i.e., 40.
Max (salary): Maximum value in the salary i.e., 80.
Function Description
11
Neetu BanslaDBMS21CSC205P
12
Neetu BanslaDBMS21CSC205P
QUOTENAME Returns a Unicode string with delimiters added to make the string
a valid SQL Server delimited identifier
13
Neetu BanslaDBMS21CSC205P
STUFF Deletes a part of a string and then inserts another part into the
string, starting at a specified position
TRANSLATE Returns the string from the first argument after the characters
specified in the second argument are translated into the
characters specified in the third argument.
UNICODE Returns the Unicode value for the first character of the input
expression
Function Description
14
Neetu BanslaDBMS21CSC205P
15
Neetu BanslaDBMS21CSC205P
POWER Returns the value of a number raised to the power of another number
16
Neetu BanslaDBMS21CSC205P
Function Description
17
Neetu BanslaDBMS21CSC205P
DATEADD Adds a time/date interval to a date and then returns the date
DATEFROMPARTS Returns a date from the specified parts (year, month, and day
values)
GETUTCDATE Returns the current database system UTC date and time
MONTH Returns the month part for a specified date (a number from 1 to
12)
18
Neetu BanslaDBMS21CSC205P
Function Description
CURRENT_USER Returns the name of the current user in the SQL Server database
ISNULL Return a specified value if the expression is NULL, otherwise return the
expression
19
Neetu BanslaDBMS21CSC205P
SESSION_USER Returns the name of the current user in the SQL Server database
The SQL Set operation is used to combine the two or more SQL SELECT statements.
1. Union
o The SQL Union operation is used to combine the result of two or more SQL SELECT
queries.
o In the union operation, all the number of datatype and columns must be same in
both the tables on which UNION operation is being applied.
20
Neetu BanslaDBMS21CSC205P
o The union operation eliminates the duplicate rows from its result set.
Syntax
2. Union All
Union All operation is equal to the Union operation. It returns the set without removing
duplication and sorting the data.
Syntax:
3. Intersect
o It is used to combine two SELECT statements. The Intersect operation returns the
common rows from both the SELECT statements.
o In the Intersect operation, the number of datatype and columns must be the same.
o It has no duplicates and it arranges the data in ascending order by default.
Syntax
4. Minus
o It combines the result of two SELECT statements. Minus operator is used to display
the rows which are present in the first query but absent in the second query.
o It has no duplicates and data arranged in ascending order by default.
Syntax:
21
Neetu BanslaDBMS21CSC205P
Sub Queries, correlated sub queries
Correlated subqueries are used for row-by-row processing. Each subquery is executed once
for every row of the outer query.
A correlated subquery is evaluated once for each row processed by the parent statement.
The parent statement can be a SELECT, UPDATE, or DELETE statement.
SELECT column1, column2….
FROM table1 outer
WHERE column1 operator
(SELECT column1, column2
FROM table2
WHERE expr1 =
outer.expr2);
A correlated subquery is one way of reading every row in a table and comparing values in
each row against related data. It is used whenever a subquery must return a different result
or set of results for each candidate row considered by the main query. In other words, you
can use a correlated subquery to answer a multipart question whose answer depends on
the value in each row processed by the parent statement.
Nested Subqueries versus Correlated Subqueries:
With a normal nested subquery, the inner SELECT query runs first and executes once,
returning values to be used by the main query. A correlated subquery, however, executes
once for each candidate row considered by the outer query. In other words, the inner query
is driven by the outer query.
22
Neetu BanslaDBMS21CSC205P
EXAMPLE of Correlated Subqueries: Find all the employees who earn more than the
average salary in their department.
CORRELATED UPDATE:
UPDATE table1 alias1
SET column = (SELECT expression
FROM table2 alias2
WHERE alias1.column =
alias2.column);
Use a correlated subquery to update rows in one table based on rows from another table.
CORRELATED DELETE:
DELETE FROM table1 alias1
WHERE column1 operator
(SELECT expression
FROM table2 alias2
WHERE alias1.column = alias2.column);
Use a correlated subquery to delete rows in one table based on the rows from another
table.
23
Neetu BanslaDBMS21CSC205P
QUERIES:
View
o Views in SQL are considered as a virtual table. A view also contains rows and
columns.
o To create the view, we can select the fields from one or more tables present in the
database.
o A view can either have specific rows based on certain condition or all the rows of a
table.
Sample table:
Student_Detail
1 Stephan Delhi
24
Neetu BanslaDBMS21CSC205P
2 Kathrin Noida
3 David Ghaziabad
4 Alina Gurugram
Student_Marks
1 Stephan 97 19
2 Kathrin 86 21
3 David 74 18
4 Alina 90 20
5 John 96 18
1. Creating view
A view can be created using the CREATE VIEW statement. We can create a view from a
single table or multiple tables.
Syntax:
In this example, we create a View named DetailsView from the table Student_Detail.
25
Neetu BanslaDBMS21CSC205P
Query:
Just like table query, we can query the view to view the data.
Output:
NAME ADDRESS
Stephan Delhi
Kathrin Noida
David Ghaziabad
View from multiple tables can be created by simply include multiple tables in the SELECT
statement. In the given example, a view is created named MarksView from two tables
Student_Detail and Student_Marks.
Query:
26
Neetu BanslaDBMS21CSC205P
Stephan Delhi 97
Kathrin Noida 86
David Ghaziabad 74
Alina Gurugram 90
4. Deleting View
Syntax
PL/SQL Concepts
● PL/SQL is a block structured language that can have multiple blocks in it.
● The programs of PL/SQL are logical blocks that can contain any number of
nested sub-blocks.
● Pl/SQL stands for "Procedural Language extension of SQL" that is used in
Oracle. PL/SQL is integrated with Oracle database (since version 7).
● The functionalities of PL/SQL usually extended after each release of Oracle
database. Although PL/SQL is closely integrated with SQL language, yet it
adds some programming constraints that are not available in SQL. With
PL/SQL, you can use SQL statements to manipulate Oracle data and flow of
control statements to process the data.
● The PL/SQL is known for its combination of data manipulating power of SQL
with data processing power of procedural languages. It inherits the
robustness, security, and portability of the Oracle Database.
● PL/SQL is not case sensitive so you are free to use lower case letters or upper
case letters except within string and character literals.
27
Neetu BanslaDBMS21CSC205P
The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs one
or more specific tasks. It is just like procedures in other programming languages.
o Header: The header contains the name of the procedure and the parameters or
variables passed to the procedure.
o Body: The body contains a declaration section, execution section and exception
section similar to a general PL/SQL block.
When you want to create a procedure or function, you have to define parameters .There is
three ways to pass parameters in procedure:
28
Neetu BanslaDBMS21CSC205P
[declaration_section]
BEGIN
executable_section
[EXCEPTION exception_section]
END [procedure_name];
In this example, we are going to insert record in user table. So you need to create user table
first.
Table creation:
Procedure Code:
Output:
Procedure Created
EXECUTE Insertuser(101,’Rahul’);
BEGIN
Insertuser (101,'Rahul');
dbms_output.put_line ('record inserted successfully');
29
Neetu BanslaDBMS21CSC205P
END;
/
Now, see the "USER" table, you will see one record is inserted.
ID Name
101 Rahul
Sample Procedures
30
Neetu BanslaDBMS21CSC205P
The PL/SQL Function is very similar to PL/SQL Procedure. The main difference between
procedure and a function is, a function must always return a value, and on the other hand a
procedure may or may not return a value. Except this, all the other things of PL/SQL
procedure are true for PL/SQL function too.
Here:
31
Neetu BanslaDBMS21CSC205P
DECLARE
n3 number(2);
BEGIN
n3:= adder (11, 22);
dbms_output.put_line ('Addition is: ' || n3);
END;
/
Output:
Addition is: 33
Statement processed.
0.05 seconds
Example
The following example demonstrates Declaring, Defining, and Invoking a Simple PL/SQL
Function that computes and returns the maximum of two values.
32
Neetu BanslaDBMS21CSC205P
RETURN number
IS
z number;
BEGIN
IF x > y THEN
z:= x;
ELSE
Z:= y;
END IF;
RETURN z;
END;
/
DECLARE
x number;
y number;
z number;
BEGIN
x:= 23;
y:= 45;
z := findMax(x, y);
dbms_output.put_line (' Maximum of (23,45): ' || z);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Maximum of (23, 45): 45
33
Neetu BanslaDBMS21CSC205P
n! = n*(n-1)!
= n*(n-1)*(n-2)!
...
= n*(n-1)*(n-2)*(n-3)... 1
The following program calculates the factorial of a given number by calling itself
recursively −
DECLARE
num number;
factorial number;
BEGIN
num:= 6;
factorial := fact (num);
dbms_output.put_line (' Factorial '|| num || ' is ' || factorial);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Factorial 6 is 720
34
Neetu BanslaDBMS21CSC205P
When an SQL statement is processed, Oracle creates a memory area known as context area.
A cursor is a pointer to this context area. It contains all information needed for processing
the statement. In PL/SQL, the context area is controlled by Cursor. A cursor contains
information on a select statement and the rows of data accessed by it.
A cursor is used to refer to a program to fetch and process the rows returned by the SQL
statement, one at a time. There are two types of cursors:
o Implicit Cursors
o Explicit Cursors
The implicit cursors are automatically generated by Oracle while an SQL statement is
executed, if you don't use an explicit cursor for the statement. These are created by default
to process the statements when DML statements like INSERT, UPDATE, and DELETE etc. are
executed.
35
Neetu BanslaDBMS21CSC205P
Let's execute the following program to update the table and increase salary of each
customer by 5000. Here, SQL%ROWCOUNT attribute is used to determine the number of
rows affected:
Create procedure:
DECLARE
Total_rows number (2);
BEGIN
UPDATE customers
SET salary = salary + 5000;
IF sql%notfound THEN
dbms_output.put_line ('no customers updated');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line (total_rows || ' customers updated ');
END IF;
END;
/
Output:
6 customers updated
PL/SQL procedure successfully completed.
Now, if you check the records in customer table, you will find that the rows are updated.
36
Neetu BanslaDBMS21CSC205P
The Explicit cursors are defined by the programmers to gain more control over the context
area. These cursors should be defined in the declaration section of the PL/SQL block. It is
created on a SELECT statement which returns more than one row.
Steps:
You must follow these steps while working with an explicit cursor.
It defines the cursor with a name and the associated SELECT statement.
37
Neetu BanslaDBMS21CSC205P
CURSOR name IS
SELECT statement;
It is used to allocate memory for the cursor and make it easy to fetch the rows returned by
the SQL statements into it.
OPEN cursor_name;
It is used to access one row at a time. You can fetch rows from the above-opened cursor as
follows:
It is used to release the allocated memory. The following syntax is used to close the
above-opened cursors.
Close cursor_name;
Explicit cursors are defined by programmers to gain more control over the context area. It
is defined in the declaration section of the PL/SQL block. It is created on a SELECT
statement which returns more than one row.
38
Neetu BanslaDBMS21CSC205P
Create procedure:
Execute the following program to retrieve the customer name and address.
1. DECLARE
2. c_id customers.id%type;
3. c_name customers.name%type;
4. c_addr customers.address%type;
5. CURSOR c_customers is
6. SELECT id, name, address FROM customers;
7. BEGIN
8. OPEN c_customers;
9. LOOP
10. FETCH c_customers into c_id, c_name, c_addr;
11. EXIT WHEN c_customers%notfound;
12. dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
13. END LOOP;
14. CLOSE c_customers;
15.END;
16./
39
Neetu BanslaDBMS21CSC205P
Output:
1 Ramesh Allahabad
2 Suresh Kanpur
3 Mahesh Ghaziabad
4 Chandan Noida
5 Alex Paris
6 Sunita Delhi
What is Exception
PL/SQL facilitates programmers to catch such conditions using exception block in the
program and an appropriate action is taken against the error condition.
o System-defined Exceptions
o User-defined Exceptions
1. DECLARE
2. <declarations section>
3. BEGIN
4. <executable command(s)>
5. EXCEPTION
6. <exception handling goes here >
7. WHEN exception1 THEN
8. exception1-handling-statements
40
Neetu BanslaDBMS21CSC205P
Let's take a simple example to demonstrate the concept of exception handling. Here we are
using the already created CUSTOMERS table.
1. DECLARE
2. c_id customers.id%type := 8;
3. c_name customers.name%type;
4. c_addr customers.address%type;
5. BEGIN
6. SELECT name, address INTO c_name, c_addr
41
Neetu BanslaDBMS21CSC205P
After the execution of above code at SQL Prompt, it produces the following result:
No such customer!
PL/SQL procedure successfully completed.
The above program should show the name and address of a customer as result whose ID is
given. But there is no customer with ID value 8 in our database, so the program raises the
run-time exception NO_DATA_FOUND, which is captured in EXCEPTION block.
Triggers could be defined on the table, view, schema, or database with which the event is
associated.
42
Neetu BanslaDBMS21CSC205P
Advantages of Triggers
Here,
43
Neetu BanslaDBMS21CSC205P
o {BEFORE | AFTER | INSTEAD OF}: This specifies when the trigger would be
executed. The INSTEAD OF clause is used for creating trigger on a view.
o {INSERT [OR] | UPDATE [OR] | DELETE}: This specifies the DML operation.
o [OF col_name]: This specifies the column name that would be updated.
o [ON table_name]: This specifies the name of the table associated with the trigger.
o [REFERENCING OLD AS o NEW AS n]: This allows you to refer new and old values
for various DML statements, like INSERT, UPDATE, and DELETE.
o [FOR EACH ROW]: This specifies a row level trigger, i.e., the trigger would be
executed for each row being affected. Otherwise the trigger will execute just once
when the SQL statement is executed, which is called a table level trigger.
o WHEN (condition): This provides a condition for rows for which the trigger would
fire. This clause is valid only for row level triggers.
Let's take a simple example to demonstrate the trigger. In this example, we are using the
following CUSTOMERS table:
44
Neetu BanslaDBMS21CSC205P
Create trigger:
Following trigger will display the salary difference between the old values and new values:
After the execution of the above code at SQL Prompt, it produces the following result.
Trigger created.
Use the following code to get the old salary, new salary and salary difference after the
trigger created.
DECLARE
Total_rows number (2);
BEGIN
UPDATE customers
SET salary = salary + 5000;
IF sql%notfound THEN
45
Neetu BanslaDBMS21CSC205P
NOTE: sql%notfound is an attribute has a Boolean value that returns TRUE if no rows were
affected by an INSERT, UPDATE, or DELETE statement, or if a SELECT INTO statement did not
retrieve a row.
Output:
Note: As many times you executed this code, the old and new salary is incremented by
5000 and hence the salary difference is always 5000.
46
Neetu BanslaDBMS21CSC205P
The following table specifies the status of the cursor with each of its attribute.
Attribute Description
%FOUND Its return value is TRUE if DML statements like INSERT, DELETE and UPDATE affect at
least one row or more rows or a SELECT INTO statement returned one or more rows.
Otherwise it returns FALSE.
%NOTFOUND Its return value is TRUE if DML statements like INSERT, DELETE and UPDATE affect no
row, or a SELECT INTO statement return no rows. Otherwise it returns FALSE. It is a just
opposite of %FOUND.
%ISOPEN It always returns FALSE for implicit cursors, because the SQL cursor is automatically
closed after executing its associated SQL statements.
%ROWCOUNT It returns the number of rows affected by DML statements like INSERT, DELETE, and
UPDATE or returned by a SELECT INTO statement.
PL/SQL facilitates programmers to catch such conditions using exception block in the
program and an appropriate action is taken against the error condition.
o System-defined Exceptions
o User-defined Exceptions
DECLARE
<declarations section>
BEGIN
<executable command(s)>
47
Neetu BanslaDBMS21CSC205P
EXCEPTION
<exception handling goes here >
WHEN exception1 THEN
exception1-handling-statements
WHEN exception2 THEN
exception2-handling-statements
WHEN exception3 THEN
exception3-handling-statements
........
WHEN others THEN
exception3-handling-statements
END;
Let's take a simple example to demonstrate the concept of exception handling. Here we are
using the already created CUSTOMERS table.
48
Neetu BanslaDBMS21CSC205P
DECLARE
c_id customers.id%type:= 8;
c_name customers.name%type;
c_addr customers.address%type;
BEGIN
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line ('No such customer!');
WHEN others THEN
dbms_output.put_line ('Error!');
END;
/
After the execution of above code at SQL Prompt, it produces the following result:
No such customer!
PL/SQL procedure successfully completed.
The above program should show the name and address of a customer as result whose ID is
given. But there is no customer with ID value 8 in our database, so the program raises the
run-time exception NO_DATA_FOUND, which is captured in EXCEPTION block.
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling goes here >
49
Neetu BanslaDBMS21CSC205P
Let's take a simple example to demonstrate the concept of exception handling. Here we are
using the already created CUSTOMERS table.
50
Neetu BanslaDBMS21CSC205P
DECLARE
c_id customers.id%type:= 8;
c_name customers.name%type;
c_addr customers.address%type;
BEGIN
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line ('No such customer!');
WHEN others THEN
dbms_output.put_line ('Error!');
END;
/
After the execution of above code at SQL Prompt, it produces the following result:
No such customer!
PL/SQL procedure successfully completed.
The above program should show the name and address of a customer as result whose ID is
given. But there is no customer with ID value 8 in our database, so the program raises the
run-time exception NO_DATA_FOUND, which is captured in EXCEPTION block.
If you use the id defined in the above table (i.e. 1 to 6), you will get a certain result. For a
demo example: here, we are using the id 5.
DECLARE
c_id customers.id%type := 5;
c_name customers.name%type;
c_addr customers.address%type;
51
Neetu BanslaDBMS21CSC205P
BEGIN
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
After the execution of above code at SQL prompt, you will get the following result:
Name: alex
Address: paris
PL/SQL procedure successfully completed.
Raising Exceptions
In the case of any internal database error, exceptions are raised by the database server
automatically. But it can also be raised explicitly by programmer by using command RAISE.
DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
WHEN exception_name THEN
statement;
END;
52
Neetu BanslaDBMS21CSC205P
PL/SQL facilitates their users to define their own exceptions according to the need of the
program. A user-defined exception can be raised explicitly, using either a RAISE statement
or the procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR.
1. DECLARE
2. my-exception EXCEPTION;
There are many pre-defined exception in PL/SQL which are executed when any database
rule is violated by the programs.
CASE_NOT_FOUND 06592 -6592 It is raised when none of the choices in the "WHEN"
clauses of a CASE statement is selected, and there is no else
clause.
53
Neetu BanslaDBMS21CSC205P
INVALID_CURSOR 01001 -1001 It is raised when attempts are made to make a cursor
operation that is not allowed, such as closing an unopened
cursor.
INVALID_NUMBER 01722 -1722 It is raised when the conversion of a character string into a
number fails because the string does not represent a valid
number.
NO_DATA_FOUND 01403 +100 It is raised when a select into statement returns no rows.
NOT_LOGGED_ON 01012 -1012 It is raised when a database call is issued without being
connected to the database.
ROWTYPE_MISMATCH 06504 -6504 It is raised when a cursor fetches value in a variable having
incompatible data type.
SELF_IS_NULL 30625 -30625 It is raised when a member method is invoked, but the
instance of the object type was not initialized.
STORAGE_ERROR 06500 -6500 It is raised when PL/SQL ran out of memory or memory
was corrupted.
TOO_MANY_ROWS 01422 -1422 It is raised when a SELECT INTO statement returns more
than one row.
54
Neetu BanslaDBMS21CSC205P
55