Unit V - RDBMS
Unit V - RDBMS
RDBMS
UNIT V
Prepared By
Mrs. S. Radhika
Department of Computer Applications,
Thiruthangal Nadar College,
Selavayal, Chennai – 51.
RDBMS – UNIT V
CONTENTS
1. PL/SQL: Structure
2. PL/SQL Language Elements
3. Operators Control Structure
4. Iterative Control
5. Cursors
6. Procedure
7. Function
8. Packages
9. Exceptional Handling
10. Triggers.
UNIT V – PL/SQL
PL/SQL Block Structure
PL/SQL stands for Procedural
Language/Structured Query
Language.
It is extension of SQL.
PL/SQL program units
[DECLARE] organize the code into blocks.
Syntax for PL/SQL Block
Declaration section; BEGIN
Structure
Execution section; [EXCEPTION]
Exception section;
END;
/
1. Declaration Section
It starts with DECLARE keyword.
It is used to declare the variables, constants, records and cursors etc.
It is an optional section.
2. Execution Section
Execution section starts with BEGIN keyword and ends with END
keyword.
This can contain both PL/SQL code and SQL code.
It is used to write the program logic.
It is a mandatory section.
3. Exception Section
This section starts with the EXCEPTION keyword.
It contains exception(s) that handle errors in the program.
This section allows the user to define his/her own error messages.
This section executes only when an error occurs. It is an optional
section.
It is an optional section.
4. End Section
This section indicates the end of PL/SQL block.
3
UNIT V - RDBMS
Example :
SQL> SET SERVEROUTPUT ON;
SQL> BEGIN
DBMS_OUTPUT.PUT_LINE(“Hello World”)
END;
/ Output:
Hello World
Character
sets Lexical
Units
Delimiters
Identifiers
Literals
Comments
Character Set
A PL/SQL program consists of text having specific set of characters.
Character set may include the following characters:
Alphabets, both in upper case [A–Z] and lower case [a–z]
Numeric digits [0–9]
Special characters ( ) + − * /< >= ! ∼ ˆ ; : . _ @ % , # $ & | { } ? [ ]
Blank spaces, tabs, new line, and carriage returns.
PL/SQL is not case sensitive, so lower case letters are equivalent to corresponding upper case
letters except within string and character literals.
Lexical Units
A line of PL/SQL program contains groups of characters known as lexical units, which can be
classified as
follows:
Delimiter
s
Identifiers
Literals
Commen
ts
4
UNIT V - RDBMS
1. Delimiters
A delimiter is a simple or compound symbol that has a special meaning to PL/SQL.
Simple symbol consists of one character, while compound symbol consists of more than
one character.
Simple
SymbolDelimiters Compound
Meaning Delimites Symbol Meaning
+ addition operator := assignment operator
- Subtraction operator => association operator
* Multiplication operator || concatenation operator
/ Division operator ** exponentiation operator
% attribute indicator << label delimiter (begin)
' character string delimiter >> label delimiter (end)
. component selector /* multi-line comment delimiter (begin)
( expression or list */ multi-line comment delimiter (end)
delimiter <> relational operator
) expression or list
delimiter != relational operator
: host variable indicator ~= relational operator
, item separator ^= relational operator
" quoted identifier delimiter <= relational operator
= relational operator >= relational operator
< relational operator -- single-line comment indicator
> relational operator
@ remote access indicator
; statement terminator
2. Identifiers
Identifiers are used in the PL/SQL programs to name the items as constants, variables,
cursors, cursor variables, subprograms, etc.
Identifiers can consists of alphabets, numerals, dollar signs, underscores, and number
signs only.
Any other characters like hyphens, slashes, blank spaces, etc. are illegal.
It must begin with an alphabetic letter optionally followed by one or more characters
(permissible in identifier).
It cannot contain more than 30 characters.
Example
o Some of the valid identifiers are as follows:
Name1 A1
Student_id
o Some of the Invalid identifiers:
mine&yours debit-amount on/off
5
UNIT V - RDBMS
3. Literals
A literal is an explicitly defined numeric, character, string, or Boolean value, which is not represented by an
identifier.
i. Numeric Literals
A numeric literal is an integer or a real value.
An integer literal may be a positive, negative, or unsigned whole number without a decimal point.
Examples:
030 6 -14 0 +32767
A real literal is a positive, negative, or unsigned whole or fractional number with a decimal point.
Examples:
6.6667 0.0 -12.0 3.14159 +8300.00 .5 25
Numeric literals can also contain exponential numbers (an optionally signed number suffix with an E
(or e) followed by an optionally signed integer).
Examples:
2E5 1.0E-7 3.14159e0 -1E38 -9.5e-3
• Character Literals
A character literal is an individual character enclosed by single quotes (‘).
Character literals include all the printable characters in the PL/SQL character set: letters, numerals,
spaces, and special symbols.
Examples:
'Z' '%' '7' ' ' 'z' '('
PL/SQL is case sensitive within character literals.
For example, PL/SQL considers the literals “A” and “a” to be different.
iv.String Literals
A character string can be represented by an identifier or explicitly written as a string literal.
A string literal is enclosed within single quotes and may consist of one or more characters. Some
examples of string literals are as follows:
“Good Morning!”
“TATA INFOTECH LTD” “04-MAY-00”
“$15,000,000”
All string literals are of character data type.
PL/SQL is case sensitive within string literals.
For example, PL/SQL considers the following literals to be different:
“HUMAN”
“Human”
• Boolean Literals
Boolean literals are the predefined values TRUE, FALSE, and NULL.
Boolean literals are values, not strings.
For example a condition:
If (x = 10) is TRUE only for the value of x equal to 10, for any other value of x it is FALSE and for no value of x
it is NULL.
6
UNIT V - RDBMS
4. Comments
Comments are used in the PL/SQL program to improve the readability and understandability of a
program.
A comment can appear anywhere in the program code.
The compiler ignores comments.
Generally, comments are used to describe the purpose and use of each code segment.
A PL/SQL comment may be a single-line or multiline.
Single-Line Comments
o Single-line comments begin with a double hyphen (–) anywhere on a line and extend to the end
of the line.
Example
– start calculations
Multiline Comments
o Multiline comments begin with a slash-asterisk (/*) and end with an asterisk slash(*/)
Example
/* Hello World! This is an example of multiline comments in PL/SQL */
----------------------------------------------------------------------------------------------------------------------------------
Declaring Constants 7
UNIT V - RDBMS
Declaration of constant is similar to declaration of variable, except the keyword CONSTANT precedes
the datatype
It must be initialized by some value.
The syntax for declaring a constant is as follows:
Identifier_Name CONSTANT datatype := value; Example
Age_limit CONSTANT NUMBER := 30;
A list of variables that have the same data type cannot be declared in the same row
Example
A, B, C NUMBER (4,2); – illegal
It should be declared in separate lines as follows: A NUMBER (4,2);
B NUMBER (4,2);
C NUMBER (4,2);
-------------------------------------------------------------------------------------------------------------------------------
Operators
PL/SQL language is rich in built-in operators and provides the following types of operators −
Arithmetic operators
Relational operators
Comparison operators
Logical operators
String operators
1. Arithmetic Operators
Let us assume variable A = 10 and variable B = 5
4. Logical
Operators
9
UNIT V - RDBMS
Let us assume variable A holds true and variable B holds false,
then
Example
Operator Description
an Called the logical AND operator. If both the operands are true then (A sand B) is
d condition becomes true. false.
or Called the logical OR Operator. If any of the two operands is true then (A or B) is true.
condition becomes true.
no Called the logical NOT Operator. Used to reverse the logical state of its not (A and B)
t operand. If a condition is true then Logical NOT operator will make it is true.
false.
PL/SQL Operator Precedence
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence
than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators will be evaluated first.
The precedence of operators goes as follows: =, <, >, <=, >=, <>, !=, ~=, ^=, IS NULL, LIKE, BETWEEN,
IN.
--------------------------------------------------------------------------------------------------------------------------------
CONTROL STRUCTURES
It can be categorized into
1.Decision Making Statements
2.Looping or Iterative Statement
i.IF Statement
The IF statement executes a sequence of statements depending on the value of
a condition.
There are three forms of IF statements:
IF-THEN
IF-THEN-ELSE
IF-THEN-ELSIF
IF-THEN statement
10
UNIT V - RDBMS
The simplest form of IF statement
It associates a condition with a sequence of statements enclosed by the keywords THEN
and END IF.
Syntax:
IF condition THEN
Statement body
END IF;
Flow
Chart:
Example code :
OUTPUT:
Result: 80 is greater than 10
PL/SQL procedure successfully completed.
IF-THEN-ELSE statement
IF statement adds the keyword ELSE followed by an alternative sequence of statement.
If the condition is false or NULL, then only the alternative sequence of statements get
executed.
It ensures that either of the sequence of statements is executed.
11
UNIT V - RDBMS
Syntax:
IF <test_condition> THEN
statement1
ELSE
statement2 END IF;
Flow Chart:
Example code:
SET SERVEROUTPUT ON; DECLARE
x INT;
BEGIN
x := &x;
IF MOD(x,2) = 0 THEN
DBMS_OUTPUT.PUT_LINE('Even Number');
ELSE
DBMS_OUTPUT.PUT_LINE('Odd Number'); END IF;
END;
OUTPUT:
Enter value for x : 6
Even Number
PL/SQL procedure successfully completed.
12
UNIT V - RDBMS
IF-THEN-ELSIF statement
IF...THEN...ELSIF...ELSE statement is suitable in which all the conditions are tested one by one and
whichever condition is found to be TRUE, that block of code is executed. And if all the conditions result in
FALSE then the ELSE part is executed.
Syntax:
DECLARE
A INT; B INT; C INT;
BEGIN
A := &A;
B := &B;
C := &C;
IF((A>B) AND (A>C)) THEN
DBMS_OUTPUT.PUT_LINE(‘A is greatest number’); ELSIF(B>C) THEN
DBMS_OUTPUT.PUT_LINE(‘B is greatest number’);
ELSE
DBMS_OUTPUT.PUT_LINE(‘C is greatest number’); END IF;
END;
/
OUTPUT:
Enter value for A : 12
Enter value for B : 4 Enter value for C : 32
13
UNIT V - RDBMS
C is greatest number
PL/SQL procedure successfully
completed.
It is a decision making statement that selects only one option out of the multiple
available options.
If all the cases fail then the else case is executed.
Syntax:
CASE selector
WHEN value1 THEN statement1;
WHEN value2 THEN statement2;
...
...
ELSE statement; END CASE;
Example code:
DECLARE
A INT; B INT;
BEGIN
A := &A;
B := MOD(A,2); CASE B
WHEN 0 THEN DBMS_OUTPUT.PUT_LINE('Even Number'); WHEN 1 THEN
DBMS_OUTPUT.PUT_LINE('Odd Number');
ELSE DBMS_OUTPUT.PUT_LINE('User entered wrong input'); END CASE;
END;
/
OUTPUT:
14
UNIT V - RDBMS
2. Looping or Iterative
Statements
LOOP chart
In iterative control, a group of statements are executed repeatedly till certain condition is true,
and control exits from loop to next statement when the condition becomes false.
There are mainly three types of loop statements:
i. LOOP
ii. WHILE-LOOP
iii. FOR-LOOP
i. LOOP statement
It is basic loop structure encloses sequence of statements between the keywords
LOOP and END LOOP.
With each iteration of the loop, the sequence of statements gets executed, then control
reaches at the top of the loop.
The syntax for LOOP control :
LOOP
sequence of statements
END LOOP;
15
UNIT V - RDBMS
DBMS_OUTPUT.PUT_LINE('After Exit, x is: ' || x); END;
/
OUTPUT: 10
20
30
After Exit, x is: 40
Example Code :
DECLARE
num int:=1; BEGIN
WHILE(num <= 10) LOOP
dbms_output.put_line(''|| num); num := num+2;
END LOOP;
END;
/ OUTPUT:
1
3
5
7
9
PL/SQL procedure successfully completed.
16
UNIT V - RDBMS
For Loop (Iterative control)
This loop is used when some statements in PL/SQL code block are to be repeated for a fixed
number of times.
The for loop automatically increments the value of the counter variable by 1 at the end of each
loop cycle.
Syntax: FOR counter_variable IN start_value..end_value
LOOP
Sequence of statements
END LOOP;
counter variable decides how many time the loop will be executed based on a start_value
and end_value provided at the beginning of the loop.
Example code:
DECLARE
i number(2); BEGIN
FOR i IN 1..5 LOOP
DBMS_OUTPUT.PUT_LINE(i); END LOOP;
END;
/
OUTPUT: 1
2
3
4
5
17
UNIT V - RDBMS
/
OUTPUT:
5
4
3
2
1
LOOP
Sequence of statements1 LOOP
Sequence of statements2 END
LOOP;
END LOOP;
18
UNIT V - RDBMS
Example Code for nested basic
loop:
DECLARE
i number(3); j number(3);
BEGIN
i := 2;
dbms_output.put_line(’ Prime Numbers'); LOOP
j:= 2; LOOP
exit WHEN ((mod(i, j) = 0) or (j = i)); j := j +1;
END LOOP;
IF (j = i ) THEN
dbms_output.put_line(i); END IF;
i := i + 1;
exit WHEN i = 20; END LOOP;
END;
/
OUTPUT:
Prime Numbers 2
3
5
7
11
13
17
19
PL/SQL procedure successfully completed.
-----------------------------------------------------------------------------------------------------------------------------------
CURSORS
Oracle creates a memory area, known as the context area, which contains all the information
needed for processing the statement.
A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor.
A cursor holds the rows (one or more) returned by a SQL statement.
The set of rows the cursor holds is referred to as the active set.
There are two types of cursors −
19
UNIT V - RDBMS
1. Implicit
cursors
2. Explicit
cursors
1. Implicit cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement is
executed, when there is no explicit cursor for the statement.
Programmers cannot control the implicit cursors and the information in it.
PL/SQL implicitly declares a cursor for every SQL DML statement, such as INSERT, DELETE,
UPDATE, and SELECT statement
Cursor Attributes
In PL/SQL every cursor, implicit or explicit, has four attributes:
Cursor attributes Description
These cursor attributes can be used in procedural statements (PL/SQL), but not in SQL
statements.
1 Ramesh 23 20000
2 Suresh 22 22000
3 Mahesh 24 24000
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:
20
UNIT V - RDBMS
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:
3 customers updated
PL/SQL procedure successfully completed.
1 Ramesh 23 25000
2 Suresh 22 27000
3 Mahesh 24 29000
2. Explicit cursors
An explicit cursor points to the current row in the active set (multiple
rows).
This allows the program to process one row at a time.
It is defined by the programmers to gain more control over the context
area.
It is created on a SELECT statement which returns more than one row.
Syntax of explicit cursor
CURSOR cursor_name IS select_statement;
For example :-
CURSOR c_customers IS
SELECT id, name, address FROM customers;
ii. Opening the cursor
Opening the cursor for allocating the memory
Make it easy to fetch the rows returned by the SQL statements
into it.
Syntax for cursor open:
OPEN cursor_name;
For example :-
OPEN c_customers;
iii. Fetching the cursor
Fetching the cursor for retrieving the data
It is used to access one row at a time.
Syntax for cursor fetch:
FETCH cursor_name INTO variable_list;
For example :-
FETCH c_customers INTO c_id, c_name, c_addr;
iv.Closing the cursor
Closing the cursor to release the allocated memory
Syntax for cursor close:
Close cursor_name; For example :-
CLOSE c_customers;
Following is a complete example program for
explicit cursor:
DECLARE
c_id customers.id%type; c_name customers.name%type;
c_salary customers.salary%type; CURSOR c_customers is
SELECT id, name, salary FROM customers;
BEGIN
OPEN c_customers; LOOP
FETCH c_customers INTO c_id, c_name, c_salary;
22
UNIT V - RDBMS
EXIT WHEN c_customers%NOTFOUND;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_salary); END LOOP;
CLOSE c_customers; END;
/
OUTPUT:
1 Ramesh 25000
2 Suresh 27000
3 Mahesh 29000
-----------------------------------------------------------------------------------
PL/SQL procedure
The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs one or
more specific tasks.
The procedure contains a header and a body.
o Header: The header contains the name of the procedure and the parameters or
variables passed to the procedure.
Body: The body contains a declaration section, execution section and exception section
similar to a general PL/SQL block.
Syntax of creating a procedure in PL/SQL:
CREATE [OR REPLACE ] PROCEDURE procedure_name (parameter_list)
IS
[declaration statements]
BEGIN
[execution statements]
EXCEPTION
[exception handler]
END [procedure_name ];
Where,
procedure-name specifies the name of the procedure.
[OR REPLACE] option allows the modification of an existing procedure.
The optional parameter list contains name, mode and the types of the parameters. Each
parameter can be in either IN, OUT, or INOUT mode.
IN parameters: This parameter is used for giving input to the subprograms. It is read-
only. Its value will be passed from outside.
23
UNIT V - RDBMS
OUT parameters: An OUT parameter will be used to return a value outside of the
procedure. It is write-only.
INOUT parameters: An INOUT parameter is both readable and writable. ie) The
procedure can read and modify it.
procedure-body contains the executable part.
The AS keyword is used instead of the IS keyword for creating a standalone
procedure.
Example code:
OR
2. BEGIN
display_msg('DAVID');
END;
/
OUTPUT:
Hello DAVID Welcome to BCA Dept PL/SQL procedure successfully completed.
--------------------------------------------------------------------------------------------------------------------------
FUNCTIONS
A function is same as a procedure except that it returns a value.
Creating a Function (Called function)
A standalone function is created using the CREATE FUNCTION statement.
The simplified syntax for the CREATE OR REPLACE PROCEDURE statement:-
Where,
function-name specifies the name of the
function. 24
UNIT V - RDBMS
[OR REPLACE] option allows the modification of an existing function.
The optional parameter list contains name, mode and the types of the parameters. Each
parameter can be in either IN, OUT, or INOUT mode.
IN parameters: This parameter is used for giving input to the subprograms. It is read-
only. Its value will be passed from outside.
OUT parameters: An OUT parameter will be used to return a value outside of the
function. It is write-only.
INOUT parameters: An INOUT parameter is both readable and writable. ie) The
function can read and modify it.
The function must contain a return statement.
The RETURN clause specifies the data type you are going to return from the function.
function-body contains the executable part.
The AS keyword is used instead of the IS keyword for creating a standalone function.
Calling a Function
When a main program calls a function, the program control is transferred to the
called function.
A called function performs the defined task and when its return statement is executed
or when the last end statement is reached, it returns the program control back to the
main program.
Syntax to call a function :
function_name(parameter_list) Example:
K = sum(15,12);
Example :
1 Ramesh 23 25000
2 Suresh 22 27000
3 Mahesh 24 29000
RETURN total;
END;
/
Function created.
25
UNIT V - RDBMS
--Calling function
DECLARE
c number(2);
BEGIN
c := totalCustomers();
dbms_output.put_line('Total no. of Customers: ' || c);
END;
/
OUTPUT:
Total no. of Customers : 3
PL/SQL procedure successfully completed.
--------------------------------------------------------------------------------------------------------
PL/SQL PACKAGES
Packages are schema objects that groups logically related PL/SQL types, variables, and
subprograms.
A package will have two mandatory parts −
• Package specification
• Package body or definition
•Package specification:
The specification is the interface to the package.
It just DECLARES the types, variables, constants, exceptions, cursors, and
subprograms that can be referenced from outside the package. ( ie, it contains all
information about the content of the package)
All objects placed in the specification are called public objects. is visible everywhere
in the schema.
Any subprogram not in the package specification but coded in the package body is
called a
private object.
Syntax for creating package
CREATE [OR specification:
REPLACE] PACKAGE <package_name> IS
<sub_program and public element declaration>
.
.
.
2. Package Body
It consists of the definition of all the elements that are present in the package
specification.
It can also have a definition of elements that are not declared in the specification,
these elements are called private elements and can be called only from inside the
26
package.
UNIT V - RDBMS
syntax for creating package body
(Definition):
CREATE [OR REPLACE] PACKAGE BODY <package_name> IS
<global_declaration part>
<Private element definition>
<sub_program and public element definition>
.
<Package Initialization> END <package_name>
27
UNIT V - RDBMS
Package
created.
DECLARE BEGIN
emp_package.add_employee(107,'PALANIVEL','KOVAI',1000);
END;
/
OUTPUT:
Inserted record successfully
PL/SQL procedure successfully completed
System-defined exceptions
Database server automatically raised the exceptions in case of any internal database
error.
These exceptions have a unique exception name and error number. These exceptions
are already defined in the ‘STANDARD’ package.
Examples of system- defined exceptions include ZERO_DIVIDE, NO_DATA_FOUND,
TOO_MANY_ROWS, and STORAGE_ERROR, etc.
DECLARE
s_rollNo students.rollNo%type := 10; s_name students.name%type;
s_address students.address%type; BEGIN
SELECT rollNo, name, address FROM students WHERE rollNo = s_rollNo;
dbms_output.put_line(s_rollNo || ' ' || s_name || ' ' || s_address);
EXCEPTION
OUTPUT:
No such student!
User-defined exceptions
The programmer can create their own exception and handle them.
They can be created at a subprogram level in the declaration part.
These exceptions are visible only in that subprogram.
The exception that is defined in the package specification is public exception,
and it is visible wherever the package is accessible.
Database exceptions can be raised explicitly by the programmer by using
RAISE command.
Syntax of raising an exception:
DECLARE
exception_name EXCEPTION; BEGIN
IF condition THEN
RAISE exception_name; END IF;
EXCEPTION
WHEN exception_name THEN statement;
END;
/
30
UNIT V - RDBMS
Example for user-defined exception handling:
DECLARE
s_rollNo students.rollNo%type := &ss_rollNo; s_name students.name%type;
s_address students.address%type;
-- user defined exception ex_invalid_rollNo EXCEPTION;
BEGIN
IF c_id <= 0 THEN
RAISE ex_invalid_rollNo;
ELSE
SELECT rollNo, name, address FROM students WHERE rollNo = s_rollNo; dbms_output.put_line(s_rollNo || ' ' ||
s_name || ' ' || s_address);
END IF;
EXCEPTION
WHEN ex_invalid_rollNo THEN
dbms_output.put_line('rollNo must be greater than zero!');
WHEN no_data_found THEN dbms_output.put_line('No such student!');
WHEN others THEN dbms_output.put_line('Error!');
END;
/
Output:
(Enter a value less than 0 for rollNo): -12
----------------------------------------------------------------------------------------------------------------------------
TRIGGERS
Triggers are stored programs, which are automatically executed or fired when some events
occur.
Triggers are written to be executed in response to any of the following events.
A database manipulation (DML) statement (DELETE, INSERT, or UPDATE).
A database definition (DDL) statement (CREATE, ALTER, or DROP).
A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).
Triggers could be defined on the table, view, schema, or database with which the event is
associated.
Benefits of Triggers
Triggers can be written for the following purposes :-
Generating some derived column values automatically
Enforcing referential integrity
Event logging and storing information on table access
Auditing
31
UNIT V - RDBMS
Synchronous replication of
tables
Imposing security
authorizations
Preventing invalid
transactions
CREATE [OR REPLACE ] TRIGGER trigger_name
Creating a trigger {BEFORE | AFTER | INSTEAD OF }
Syntax for creating trigger:
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n] [FOR EACH
ROW]
WHEN (condition)
DECLARE
Declaration-statements BEGIN
Executable-statements EXCEPTION
Exception-handling-statements END;
/
Here,
CREATE [OR REPLACE] TRIGGER trigger_name - It creates or replaces an existing trigger with the
trigger_name.
{BEFORE | AFTER | INSTEAD OF} - This specifies when the trigger would be executed. The
INSTEAD OF clause is used for creating trigger on a view.
{INSERT [OR] | UPDATE [OR] | DELETE}- This specifies the DML operation.
[OF col_name] - This specifies the column name that would be updated.
[ON table_name] - This specifies the name of the table associated with the trigger.
[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.
[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.
WHEN (condition) - This provides a condition for rows for which the trigger would fire. This
clause is valid only for row level triggers.
Example for Trigger:
bank_customer table
ACCNO CUSTNAME ACCTYPE BALANCEAMT
------ --------------- -------------------------------------------------- ----------
100 kamal savings 12500
101 David raj savings 20000
32
UNIT V - RDBMS
102 John current 85000
103 Backia savings 10500
------------------------------------------------------------------------------------
OUTPUT:
INSERT INTO bank_transaction VALUES(15,103,to_date('11-09-2022','dd-mm-yyyy'),
'debit',12000)
*
ERROR at line 1:
ORA-20001: ----------Insufficient Balance!!-------------
ORA-06512: at "SYSTEM.TRANSACTION_BALANCE_CHECK", line 9
ORA-04088: error during execution of trigger 'SYSTEM.
TRANSACTION_BALANCE_CHECK‘
UNIT V - RDBMS 33