Module 3
Module 3
Module 3
SQL: Form of basic SQL query, Nested queries, Aggregate operators, Null
values, Complex integrity constrains in SQL, Triggers and active databases.
PL/SQL: Generic PL/SQL block, PL/SQL data types, Control structure, Procedures
and functions, Cursors, Database triggers
INTRODUCTION OF SQL
SQL or Structured Query Language is simply a computer language that is used to establish a
communication between the user and the database i.e. all the database related operations are performed using
this Structured Query Language.
As the name suggests, SQL is used to manage the structured databases like RDBMS. Non-Structured databases
can't be managed by SQL. Some of the Relational Database Management Systems like Oracle, MS Access, MySQL,
etc uses SQL for all the operations on the database.
Some of the operations that can be performed with the help of SQL are:
In SQL, we give some commands to the system to perform some operation. That command or the instruction is
known as a Query. The system will take this query as an input and will give the desired output. So, there are some
steps that are included in this whole process. So, let's look at the process involved in executing a SQL query.
Query Processing
In SQL, we write queries to perform certain operations. But those queries are in some high-level language and
this high-level language must be converted to some low-level language because the system can understand the
low-level languages only. So, following is the block diagram of Query processing in SQL:
Following is the description of the same:
• SQL Query: It is the query that you are want to execute to get some data from the database. It can be
some create table query or delete table query or something else that you want to perform on the
database.
• Parser and Translator: The SQL query is in high-level language and we need to convert this high-level
language in low-level language. So, a translator translates the SQL queries into some relational algebraic
expressions. At the same time, the Parser checks for some syntax error(if any) and the relations that are
used in the RDBMS.
• Query Optimizer: There can be a number of ways for writing the same query. But your query should be
such that it should be the most efficient query. So, the Query Optimizer optimizes the query in such a way
that it is the efficient query that can be executed.
• Query Evaluation: Finally the optimized query will be evaluated and the result will be shown to the users.
The SQL SELECT statement is used to select (retrieve) data from a database table.
For example,
Here, the SQL command selects the first_name and last_name of all Customers.
Example: SQL SELECT
SQL SELECT ALL
To select all columns from a database table, we use the * character. For example,
SELECT * FROM Customers;
Here, the SQL command selects all columns of the Customers table.
Example: SQL SELECT All
For example,
SELECT * FROM Customers WHERE last_name = 'Doe';
Here, the SQL command selects all customers from the Customers table with last_name Doe.
Example: SQL SELECT with WHERE
SQL Operators
The WHERE clause uses operators to construct conditions. Some of the commonly used operators are:
1. Equal to Operator (=)
SELECT * FROM Customers WHERE first_name = 'John';
Run Code
This SQL command selects all customers from the Customers table having first_name John.
Run Code
This SQL command selects all customers from the Customers table having age greater than 25.
Run Code
This SQL command selects all customers from the Customers table having last_name Doe and country USA
NESTED QUERIES
A Subquery is a query within another SQL query and embedded within the WHERE clause.
Subquery is also known as Nested Query.
Important Rule:
o A subquery can be placed in a number of SQL clauses like WHERE clause, FROM clause, HAVING clause.
o You can use Subquery with SELECT, UPDATE, INSERT, DELETE statements along with the operators like =, <, >,
>=, <=, IN, BETWEEN, etc.
o A subquery is a query within another query. The outer query is known as the main query, and the inner query
is known as a subquery.
o Subqueries are on the right side of the comparison operator.
o A subquery is enclosed in parentheses.
o In the Subquery, ORDER BY command cannot be used. But GROUP BY command can be used to perform the
same function as ORDER BY command.
Note: SQL subqueries are most frequently used with the Select statement.
Example
Consider the EMPLOYEE table have the following records:
ID NAME AGE ADDRESS SALARY
1 John 20 US 2000.00
2 Stephan 26 Dubai 1500.00
3 David 27 Bangkok 2000.00
4 Alina 29 UK 6500.00
5 Kathrin 34 Bangalore 8500.00
6 Harry 42 China 4500.00
7 Jackson 25 Mizoram 10000.00
The subquery with a SELECT statement will be:
SELECT * FROM EMPLOYEE WHERE ID IN (SELECT ID FROM EMPLOYEE WHERE SALARY > 4500);
This would produce the following result:
ID NAME AGE ADDRESS SALARY
4 Alina 29 UK 6500.00
5 Kathrin 34 Bangalore 8500.00
7 Jackson 25 Mizoram 10000.00
1. Independent Nested Queries: In independent nested queries, query execution starts from innermost query to
outermost queries. The execution of inner query is independent of outer query, but the result of inner query is
used in execution of outer query. Various operators like IN, NOT IN, ANY, ALL etc are used in writing independent
nested queries.
STUDENT
S_ID S_NAME S_ADDRESS S_PHONE S_AGE
S1 RAM DELHI 9455123451 18
S2 RAMESH GURGAON 9652431543 18
S3 SUJIT ROHTAK 9156253131 20
S4 SURESH DELHI 9156768971 18
COURSE
C_ID C_NAME
C1 DSA
C2 Programming
C3 DBMS
IN: If we want to find out S_ID who are enrolled in C_NAME ‘DSA’ or ‘DBMS’, we can write it with the help of
independent nested query and IN operator. From COURSE table, we can find out C_ID for C_NAME ‘DSA’ or DBMS’
and we can use these C_IDs for finding S_IDs from STUDENT_COURSE TABLE.
The inner query will return a set with members C1 and C3 and outer query will return those S_IDs for which C_ID is
equal to any member of set (C1 and C3 in this case). So, it will return S1, S2 and S4.
Note: If we want to find out names of STUDENTs who have either enrolled in ‘DSA’ or ‘DBMS’, it can be done as:
Select S_NAME from STUDENT where S_ID IN
(Select S_ID from STUDENT_COURSE where C_ID IN
(SELECT C_ID from COURSE where C_NAME=’DSA’ or C_NAME=’DBMS’));
NOT IN: If we want to find out S_IDs of STUDENTs who have neither enrolled in ‘DSA’ nor in ‘DBMS’, it can be done
as:
Select S_ID from STUDENT where S_ID NOT IN (Select S_ID from STUDENT_COURSE where C_ID IN
(SELECT C_ID from COURSE where C_NAME=’DSA’ or C_NAME=’DBMS’));
The innermost query will return a set with members C1 and C3. Second inner query will return those S_IDs for
which C_ID is equal to any member of set (C1 and C3 in this case) which are S1, S2 and S4. The outermost query
will return those S_IDs where S_ID is not a member of set (S1, S2 and S4). So it will return S3.
2. Co-related Nested Queries: In co-related nested queries, the output of inner query depends on the row which
is being currently executed in outer query. e.g.; If we want to find out S_NAME of STUDENTs who are enrolled
in C_ID ‘C1’, it can be done with the help of co-related nested query as:
Select S_NAME from STUDENT S where EXISTS
( select * from STUDENT_COURSE SC where S.S_ID=SC.S_ID and SC.C_ID=’C1’);
For each row of STUDENT S, it will find the rows from STUDENT_COURSE where S.S_ID = SC.S_ID and
SC.C_ID=’C1’. If for a S_ID from STUDENT S, atleast a row exists in STUDENT_COURSE SC with C_ID=’C1’, then inner
query will return true and corresponding S_ID will be returned as output.
AGGREGATE OPERATORS
In database management systems, an aggregate function is a function that performs calculations on a group
of values and returns a single value.
It is used to summarize the data. It performs calculations on multiple rows of a single column of a t able to form
a single value of more significant meaning.
These Aggregate functions are inbuilt SQL functions. They are often used with the GROUP BY clause to
calculate an aggregate value for each group.
AVG : The SQL AVG function calculates the average value of a column of numeric type. It returns the average of
all non-NULL values.
For example:
SELECT AVG(Salary) FROM Employees;
This query returns the average salary of all the employees.
COUNT : The COUNT function is used to count the number of rows in a database table. It can work on both
numeric and non-numeric data types.
The SQL COUNT function returns the number of rows in a table satisfying the criteria specified in the WHERE
clause. It sets on the number of rows or non-NULL column values.
COUNT function uses the COUNT(*) that returns the count of all the rows in a specified table.
COUNT(*) considers duplicate and Null while Count(column_name) removes Null values records from counting.
Syntax
COUNT(*)
or
COUNT( [ALL | DISTINCT] expression )
[ALL | DISTINCT] is optional. By default it is ALL. DISTINCT keyword removes duplicate and Null values from
operation.
For example:
SELECT COUNT(*) FROM Employees;
This query will return the total number of records in the Employees table.
SELECT COUNT(DISTINCT Dept_Id) FROM Employees;
This query will return the count total number of Dept_Id. It does not consider duplicate Dept_Id and Null.
MAX : The aggregate function MAX() is used to find the maximum value or highest value of a certain column or
expression or a set of values.
It is applicable to all the data types.
It excludes NULL values and return distinct value as a result.
Syntax MAX(expression)
For example:
SELECT MAX(Salary) FROM Employees;
This query will return maximum salary from the Employees table.
MIN : The aggregate function MIN() is used to find the minimum value or lowest value of a certain column or
expression or a set of values.
It is applicable to all the data types.
It excludes NULL values and return distinct value as a result.
Syntax : MIN(expression)
For example
SELECT MIN(Salary) FROM Employees;
This query will return minimum salary from the Employees table.
SUM : The aggregate function SUM() is used to calculate the sum of all the values of the select column. It
returns the sum of values in a set.
SUM function ignores the NULL values. If no matching records are found, it returns NULL.
It is applicable to numeric values.
Syntax
SUM([ALL | DISTINCT]) expression)
DISTINCT is used to select unique values.
For example:
SELECT SUM(Salary) FROM Employees;
This query will return total salary of all the Employees.
GROUP BY – We can combine specific categories of columns together and show the results. For example, there are
multiple employees working in different department. Using group by option we can display how many employees
are working in each department.
Having Clause – Using this clause we can add conditions to the grouped categories and filter the records. For
examples, if we want to display the details of the department which has more than 100 employees.
NULL VALUES
In SQL there may be some records in a table that do not have values or data for every field. This could
be possible because at a time of data entry information is not available. So SQL supports a special value known as
NULL which is used to represent the values of attributes that may be unknown or not apply to a tuple. SQL places
a NULL value in the field in the absence of a user-defined value. For example, the Apartment_number attribute of
an address applies only to address that are in apartment buildings and not to other types of residences.
Importance of NULL value:
• It is important to understand that a NULL value is different from a zero value.
• A NULL value is used to represent a missing value, but that it usually has one of three different
interpretations:
• The value unknown (value exists but is not known)
• Value not available (exists but is purposely withheld)
• Attribute not applicable (undefined for this tuple)
• It is often not possible to determine which of the meanings is intended. Hence, SQL does not distinguish
between the different meanings of NULL.
Principles of NULL values:
• Setting a NULL value is appropriate when the actual value is unknown, or when a value would not be
meaningful.
• A NULL value is not equivalent to a value of ZERO if the data type is a number and is not equivalent to
spaces if the data type is character.
• A NULL value can be inserted into columns of any data type.
• A NULL value will evaluate NULL in any expression.
• Suppose if any column has a NULL value, then UNIQUE, FOREIGN key, CHECK constraints will ignore by
SQL.
Consider the sample table ‘emp’
IS NULL operator
All operations upon null values present in the table must be done using this ‘is null’ operator .we cannot compare
null value using the assignment operator
The details of those employees whose commission value is Null are displayed.
IS NOT NULL
Ex: select * from emp where comm is not null;
Details of all those employees whose Commission value is not null value are displayed.
Ex: SELECT COUNT(*) AS Count FROM Employee WHERE mgr IS NOT NULL;
Example
• Using NVL function you can substitute a value in the place of NULL values.
• The substituted value then temporarily replaces the NULL values in your calculations or expression.
Remember that the substituted value only replaces the NULL value temporarily for the session and does not
affect the value stored in the table.
• Here is the syntax of NVL function NVL (exp, replacement-exp)
• As you can see NVL function takes two parameters exp and replacement exp. First parameter exp can be a
column name of a table or an arithmetic expression and the second parameter replacement expression will
be the value which you want to substitute when a NULL value is encountered.
• Always remember the data type of both the parameters must match otherwise the compiler will raise an
error.
• On execution all the null values in the result set will get replaced by 500.
• Similarly we can use NVL null function while performing arithmetic expression.
• Again let’s take the same arithmetic expression which we used in the previous query where we added 100 to
the values of commission column.
For example, either the employee's Social Security number or an assigned employee identification number
is the logical primary key for an employee table. The objective is for every record to have a unique primary key or
value for the employee's identification number. Because there is probably no need to have more than one record for
each employee in an employee table, the employee identification number makes a logical primary key. The primary
key is assigned at table creation.
The following example identifies the EMP_ID column as the PRIMARY KEY for the EMPLOYEES table:
CREATE TABLE EMPLOYEE_TBL
(EMP_ID CHAR(9) NOT NULL PRIMARY KEY,
EMP_NAME VARCHAR (40) NOT NULL,
EMP_ST_ADDR VARCHAR (20) NOT NULL,
EMP_CITY VARCHAR (15) NOT NULL,
EMP_ST CHAR(2) NOT NULL,
EMP_ZIP INTEGER(5) NOT NULL,
EMP_PHONE INTEGER(10) NULL,
EMP_PAGER INTEGER(10) NULL);
2. Unique Constraints
A unique column constraint in a table is similar to a primary key in that the value in that column for every row
of data in the table must have a unique value. Although a primary key constraint is placed on one column, you can
place a unique constraint on another column even though it is not actually for use as the primary key.
Syntax to define a Unique key at column level:
[CONSTRAINT constraint_name] UNIQUE
Ex:
CREATE TABLE EMPLOYEE_TBL
(EMP_ID CHAR(9) NOT NULL PRIMARY KEY,
EMP_NAME VARCHAR (40) NOT NULL,
EMP_ST_ADDR VARCHAR (20) NOT NULL,
EMP_CITY VARCHAR (15) NOT NULL,
EMP_ST CHAR(2) NOT NULL,
EMP_ZIP INTEGER(5) NOT NULL,
EMP_PHONE INTEGER(10) NULL UNIQUE,
EMP_PAGER INTEGER(10) NULL)
Ex:
CREATE TABLE EMPLOYEE_PAY_TBL
(EMP_ID CHAR(9) NOT NULL,
POSITION VARCHAR2(15) NOT NULL,
DATE_HIRE DATE NULL,
PAY_RATE NUMBER(4,2) NOT NULL,
DATE_LAST_RAISE DATE NULL,
5. Check Constraints
Check (CHK) constraints can be utilized to check the validity of data entered into particular table columns. Check
constraints are used to provide back-end database edits, although edits are commonly found in the front-end
application as well. General edits restrict values that can be entered into columns or objects, whether within the
database itself or on a front-end application. The check constraint is a way of providing another protective layer for
the data.
Ex:
CREATE TABLE EMPLOYEE_TBL
(EMP_ID CHAR(9) NOT NULL,
EMP_NAME VARCHAR2(40) NOT NULL,
EMP_ST_ADDR VARCHAR2(20) NOT NULL,
EMP_CITY VARCHAR2(15) NOT NULL,
EMP_ST CHAR(2) NOT NULL,
EMP_ZIP NUMBER(5) NOT NULL,
EMP_PHONE NUMBER(10) NULL,
EMP_PAGER NUMBER(10) NULL),
PRIMARY KEY (EMP_ID),
CONSTRAINT CHK_EMP_ZIP CHECK ( EMP_ZIP = '46234');
Active Databases :
Active Database is a database consisting of set of triggers. These databases are very difficult to be
maintained because of the complexity that arises in understanding the effect of these triggers. In such database,
DBMS initially verifies whether the particular trigger specified in the statement that modifies the database) is
activated or not, prior to executing the statement.
If the trigger is active then DBMS executes the condition part and then executes the action part only if the
specified condition is evaluated to true. It is possible to activate more than one trigger within a single statement.
In such situation, DBMS processes each of the trigger randomly. The execution of an action part of a
trigger may either activate other triggers or the same trigger that Initialized this action. Such types of trigger that
activates itself is called as ‘recursive trigger’. The DBMS executes such chains of trigger in some pre-defined
manner but it effects the concept of understanding.
Features of Active Database:
1. It possess all the concepts of a conventional database i.e. data modelling facilities, query language etc.
2. It supports all the functions of a traditional database like data definition, data manipulation, storage
management etc.
3. It supports definition and management of ECA rules.
4. It detects event occurrence.
5. It must be able to evaluate conditions and to execute actions.
6. It means that it has to implement rule execution.
Advantages :
1. Enhances traditional database functionalities with powerful rule processing capabilities.
2. Enable a uniform and centralized description of the business rules relevant to the information system.
3. Avoids redundancy of checking and repair operations.
4. Suitable platform for building large and efficient knowledge base and expert systems.
Triggers
Triggers are the SQL statements that are automatically executed when there is any change in the database. The
triggers are executed in response to certain events(INSERT, UPDATE or DELETE) in a particular table. These
triggers help in maintaining the integrity of the data by changing the data of the database in a systematic fashion.
Syntax
create trigger Trigger_name
(before | after)
[insert | update | delete]
on [table_name]
[for each row]
[trigger_body]
1. CREATE TRIGGER: These two keywords specify that a triggered block is going to be declared.
2. TRIGGER_NAME: It creates or replaces an existing trigger with the Trigger_name. The trigger name should
be unique.
3. BEFORE | AFTER: It specifies when the trigger will be initiated i.e. before the ongoing event or after the
ongoing event.
4. INSERT | UPDATE | DELETE: These are the DML operations and we can use either of them in a given
trigger.
5. ON[TABLE_NAME]: It specifies the name of the table on which the trigger is going to be applied.
6. FOR EACH ROW: Row-level trigger gets executed when any row value of any column changes.
7. TRIGGER BODY: It consists of queries that need to be executed when the trigger is called.
1. DESC Student_Trigger;
Field Type NULL Key Default Extra
Student_RollNo INT NO PRIMARY NULL
Student_FirstName Varchar(100) YES NULL
Student_EnglishMarks INT YES NULL
Student_PhysicsMarks INT YES NULL
Student_ChemistryMarks INT YES NULL
Student_MathsMarks INT YES NULL
Student_TotalMarks INT YES NULL
Student_Percentage INT YES NULL
The following query fires a trigger before the insertion of the student record in the table:
To check the output of the above INSERT statement, you have to type the following SELECT statement:
Output:
Advantages : Following are the three main advantages of triggers in Structured Query Language:
1. SQL provides an alternate way for maintaining the data and referential integrity in the tables.
2. Triggers helps in executing the scheduled tasks because they are called automatically.
3. They catch the errors in the database layer of various businesses.
4. They allow the database users to validate values before inserting and updating.
Disadvantages: Following are the main disadvantages of triggers in Structured Query Language:
1. They are not compiled.
2. It is not possible to find and debug the errors in triggers.
3. If we use the complex code in the trigger, it makes the application run slower.
4. Trigger increases the high load on the database system.
PL/SQL: Generic PL/SQL block, PL/SQL data types, Control structure, Procedures and
functions, Cursors, Database triggers.
Block Structure
PL/SQL blocks have a pre-defined structure in which the code is to be grouped. Below are different sections of
PL/SQL blocks.
1. Declaration section
2. Execution section
3. Exception-Handling section
Declaration Section
This is the first section of the PL/SQL blocks. This section is an optional part. This is the section in which the
declaration of variables, cursors, exceptions, subprograms, pragma instructions and collections that are needed in
the block will be declared. Below are few more characteristics of this part.
• This particular section is optional and can be skipped if no declarations are needed.
• This should be the first section in a PL/SQL block, if present.
• This section starts with the keyword ‘DECLARE’ for triggers and anonymous block. For other subprograms,
this keyword will not be present. Instead, the part after the subprogram name definition marks the
declaration section.
• This section should always be followed by execution section.
Execution Section
Execution part is the main and mandatory part which actually executes the code that is written inside it. Since the
PL/SQL expects the executable statements from this block this cannot be an empty block, i.e., it should have at least
one valid executable code line in it. Below are few more characteristics of this part.
Exception-Handling Section
The exception is unavoidable in the program which occurs at run-time and to handle this Oracle has provided an
Exception-handling section in blocks. This section can also contain PL/SQL statements. This is an optional section of
the PL/SQL blocks.
• This is the section where the exception raised in the execution block is handled.
• This section is the last part of the PL/SQL block.
• Control from this section can never return to the execution block.
• This section starts with the keyword ‘EXCEPTION’.
• This section should always be followed by the keyword ‘END’.
• These blocks don’t have any reference name specified for them.
• These blocks start with the keyword ‘DECLARE’ or ‘BEGIN’.
• Since these blocks do not have any reference name, these cannot be stored for later purpose. They shall be
created and executed in the same session.
• They can call the other named blocks, but call to anonymous block is not possible as it is not having any
reference.
• It can have nested block in it which can be named or anonymous. It can also be nested in any blocks.
• These blocks can have all three sections of the block, in which execution section is mandatory, the other two
sections are optional.
Ex:
DECLARE
-- declare variable a, b and c
-- and these three variables datatype are integer
a number;
b number;
c number;
BEGIN
a:= 10;
b:= 100;
--find largest number
--take it in c variable
IF a > b THEN
c:= a;
ELSE
c:= b;
END IF;
dbms_output.put_line(' Maximum number in 10 and 100: ' || c);
END;
/
Named blocks: Named blocks have a specific and unique name for them. They are stored as the database
objects in the server. Since they are available as database objects, they can be referred to or used as long as it is
present on the server. The compilation process for named blocks happens separately while creating them as a
database objects.
Below are few more characteristics of Named blocks.
1. Procedure
2. Function
Ex:
DECLARE
Following datatypes can be used in PL/SQL depending upon the type of data required:
2. LOB Types: This datatype deals with large objects and is used to specify location of these large objects like
text files, images etc which are generally not stored outside the database.
3. Reference Types: This datatype is used to hold pointer values which generally stores address of other
program items.
4. Composite Types: Last but not the least, as the name suggests this type of data is a composition of individual
data which can be manipulated/processed separate as well.
CONTROL STRUCTURE
IF - THEN statement
It is the simplest form of the IF control statement, frequently used in decision-making and changing the
control flow of the program execution.
The IF statement associates a condition with a sequence of statements enclosed by the
keywords THEN and END IF. If the condition is TRUE, the statements get executed, and if the condition
is FALSE or NULL, then the IF statement does nothing.
Syntax for IF-THEN statement is −
IF condition THEN
S;
END IF;
Where condition is a Boolean or relational condition and S is a simple or compound statement. Following is
an example of the IF-THEN statement −
IF (a <= 20) THEN
c:= c+1;
END IF;
If the Boolean expression condition evaluates to true, then the block of code inside the if statement will be
executed. If the Boolean expression evaluates to false, then the first set of code after the end of the if
statement (after the closing end if) will be executed.
Flow Diagram
Example 1
Let us try an example that will help you understand the concept −
DECLARE
a number(2) := 10;
BEGIN
a:= 10;
-- check the boolean condition using if statement
IF( a < 20 ) THEN
-- if condition is true then print the following
dbms_output.put_line('a is less than 20 ' );
END IF;
dbms_output.put_line('value of a is : ' || a);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
a is less than 20
value of a is : 10
Example
Let us try an example that will help you understand the concept −
DECLARE
a number(3) := 100;
BEGIN
-- check the boolean condition using if statement
IF( a < 20 ) THEN
-- if condition is true then print the following
dbms_output.put_line('a is less than 20 ' );
ELSE
dbms_output.put_line('a is not less than 20 ' );
END IF;
dbms_output.put_line('value of a is : ' || a);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
a is not less than 20
value of a is : 100
IF-THEN-ELSIF Statement
The IF-THEN-ELSIF statement allows you to choose between several alternatives. An IF-THEN statement can
be followed by an optional ELSIF...ELSE statement. The ELSIF clause lets you add additional conditions.
When using IF-THEN-ELSIF statements there are a few points to keep in mind.
• It's ELSIF, not ELSEIF.
• An IF-THEN statement can have zero or one ELSE's and it must come after any ELSIF's.
• An IF-THEN statement can have zero to many ELSIF's and they must come before the ELSE.
• Once an ELSIF succeeds, none of the remaining ELSIF's or ELSE's will be tested.
CASE Statement
Like the IF statement, the CASE statement selects one sequence of statements to execute. However, to
select the sequence, the CASE statement uses a selector rather than multiple Boolean expressions. A
selector is an expression, the value of which is used to select one of several alternatives.
The syntax for the case statement in PL/SQL is −
CASE selector
WHEN 'value1' THEN S1;
WHEN 'value2' THEN S2;
WHEN 'value3' THEN S3;
...
ELSE Sn; -- default case
END CASE;
Flow Diagram
Example
DECLARE
grade char(1) := 'A';
BEGIN
CASE grade
when 'A' then dbms_output.put_line('Excellent');
when 'B' then dbms_output.put_line('Very good');
when 'C' then dbms_output.put_line('Well done');
when 'D' then dbms_output.put_line('You passed');
when 'F' then dbms_output.put_line('Better try again');
else dbms_output.put_line('No such grade');
END CASE;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Excellent
Example
DECLARE
grade char(1) := 'B';
BEGIN
case
when grade = 'A' then dbms_output.put_line('Excellent');
when grade = 'B' then dbms_output.put_line('Very good');
when grade = 'C' then dbms_output.put_line('Well done');
when grade = 'D' then dbms_output.put_line('You passed');
when grade = 'F' then dbms_output.put_line('Better try again');
else dbms_output.put_line('No such grade');
end case;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Very good
Looping Statements:
There may be a situation when you need to execute a block of code several number of times. In general,
statements are executed sequentially: The first statement in a function is executed first, followed by the second, and
so on.
Programming languages provide various control structures that allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and following is the general
form of a loop statement in most of the programming languages −
PL/SQL provides the following types of loop to handle the looping requirements. Click the following links to check
their detail.
S.No Loop Type & Description
1 PL/SQL Basic LOOP
In this loop structure, sequence of statements is enclosed between the LOOP and the END LOOP
statements. At each iteration, the sequence of statements is executed and then control resumes at the
top of the loop.
2 PL/SQL WHILE LOOP
Repeats a statement or group of statements while a given condition is true. It tests the condition before
executing the loop body.
3 PL/SQL FOR LOOP
Execute a sequence of statements multiple times and abbreviates the code that manages the loop
variable.
4 Nested loops in PL/SQL
You can use one or more loop inside any another basic loop, while, or for loop.
Nested Loops
PL/SQL allows using one loop inside another loop. Following section shows a few examples to illustrate the
concept.
The syntax for a nested basic LOOP statement in PL/SQL is as follows −
LOOP
Sequence of statements1
LOOP
Sequence of statements2
END LOOP;
END LOOP;
The syntax for a nested FOR LOOP statement in PL/SQL is as follows −
FOR counter1 IN initial_value1 .. final_value1 LOOP
sequence_of_statements1
FOR counter2 IN initial_value2 .. final_value2 LOOP
sequence_of_statements2
END LOOP;
END LOOP;
The syntax for a nested WHILE LOOP statement in Pascal is as follows −
WHILE condition1 LOOP
sequence_of_statements1
WHILE condition2 LOOP
sequence_of_statements2
END LOOP;
END LOOP;
Example
The following program uses a nested basic loop to find the prime numbers from 2 to 100 −
DECLARE
i number(3);
j number(3);
BEGIN
i := 2;
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 || ' is prime');
END IF;
i := i + 1;
exit WHEN i = 50;
END LOOP;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
Procedure:
A Procedure in PL/SQL is a subprogram unit that consists of a group of PL/SQL statements that can be
called by name. Each procedure in PL/SQL has its own unique name by which it can be referred to and called. This
subprogram unit in the Oracle database is stored as a database object.
Note: Subprogram is nothing but a procedure, and it needs to be created manually as per the requirement. Once
created they will be stored as database objects.
Syntax:
CREATE OR REPLACE PROCEDURE
<procedure_name>
(
<parameterl IN/OUT <datatype>
..
.
)
[ IS | AS ]
<declaration_part>
BEGIN
<execution part>
EXCEPTION
<exception handling part>
END;
• CREATE PROCEDURE instructs the compiler to create new procedure in Oracle. Keyword ‘OR REPLACE’
instructs the compile to replace the existing procedure (if any) with the current one.
• Procedure name should be unique.
• Keyword ‘IS’ will be used, when the stored procedure in Oracle is nested into some other blocks. If the
procedure is standalone then ‘AS’ will be used. Other than this coding standard, both have the same
meaning.
In this example, we are going to create an Oracle procedure that takes the name as input and prints the welcome
message as output. We are going to use EXEC command to call procedure.
Code Explanation:
• Code line 1: Creating the procedure with name ‘welcome_msg’ and with one parameter ‘p_name’ of ‘IN’
type.
• Code line 4: Printing the welcome message by concatenating the input name.
• Procedure is compiled successfully.
• Code line 7: Calling the procedure using EXEC command with the parameter ‘MBU’. Procedure is executed,
and the message is printed out as “Welcome MBU”.
Functions
Functions is a standalone PL/SQL subprogram. Like PL/SQL procedure, functions have a unique name by which it can
be referred. These are stored as PL/SQL database objects. Below are some of the characteristics of functions.
• Functions are a standalone block that is mainly used for calculation purpose.
• Function use RETURN keyword to return the value, and the datatype of this is defined at the time of
creation.
• A Function should either return a value or raise the exception, i.e. return is mandatory in functions.
• Function with no DML statements can be directly called in SELECT query whereas the function with DML
operation can only be called from other PL/SQL blocks.
• It can have nested blocks, or it can be defined and nested inside the other blocks or packages.
• It contains declaration part (optional), execution part, exception handling part (optional).
• The values can be passed into the function or fetched from the procedure through the parameters.
• These parameters should be included in the calling statement.
• A PLSQL function can also return the value through OUT parameters other than using RETURN.
• Since it will always return the value, in calling statement it always accompanies with assignment operator to
populate the variables.
Syntax
CREATE OR REPLACE FUNCTION
<procedure_name>
(
<parameterl IN/OUT <datatype>
)
RETURN <datatype>
[ IS | AS ]
<declaration_part>
BEGIN
<execution part>
EXCEPTION
<exception handling part>
END;
• CREATE FUNCTION instructs the compiler to create a new function. Keyword ‘OR REPLACE’ instructs the
compiler to replace the existing function (if any) with the current one.
• The Function name should be unique.
• RETURN datatype should be mentioned.
• Keyword ‘IS’ will be used, when the procedure is nested into some other blocks. If the procedure is
standalone then ‘AS’ will be used. Other than this coding standard, both have the same meaning.
In this program, we are going to create a function that takes the name as input and returns the welcome message
as output. We are going to use anonymous block and select statement to call the function.
CREATE OR REPLACE FUNCTION welcome_msgJune ( p_name IN VARCHAR2) RETURN VAR.CHAR2
IS
BEGIN
RETURN (‘Welcome ‘|| p_name);
END;
/
DECLARE
lv_msg VARCHAR2(250);
BEGIN
lv_msg := welcome_msg_func (‘Guru99’);
dbms_output.put_line(lv_msg);
END;
SELECT welcome_msg_func(‘Guru99:) FROM DUAL;
Code Explanation:
• Code line 1: Creating the Oracle function with name ‘welcome_msg_func’ and with one parameter ‘p_name’
of ‘IN’ type.
• Code line 2: declaring the return type as VARCHAR2
• Code line 5: Returning the concatenated value ‘Welcome’ and the parameter value.
• Code line 8: Anonymous block to call the above function.
• Code line 9: Declaring the variable with datatype same as the return datatype of the function.
• Code line 11: Calling the function and populating the return value to the variable ‘lv_msg’.
• Code line 12: Printing the variable value. The output you will get here is “Welcome Guru99”
• Code line 14: Calling the same function through SELECT statement. The return value is directed to the
standard output directly.
DATABASE TRIGGERS
A trigger is a set of SQL statements that reside in system memory with unique names. It is a specialized category
of stored procedure that is called automatically when a database server event occurs. Each trigger is always associated
with a table.
A trigger is called a special procedure because it cannot be called directly like a stored procedure. The key
distinction between the trigger and procedure is that a trigger is called automatically when a data modification event
occurs against a table. A stored procedure, on the other hand, must be invoked directly.
The following are the main characteristics that distinguish triggers from stored procedures:
o We cannot manually execute/invoked triggers.
o Triggers have no chance of receiving parameters.
o A transaction cannot be committed or rolled back inside a trigger.
Syntax of Trigger
We can create a trigger in SQL Server by using the CREATE TRIGGER statement as follows:
1. CREATE TRIGGER schema.trigger_name
2. ON table_name
3. AFTER {INSERT, UPDATE, DELETE}
4. [NOT FOR REPLICATION]
5. AS
6. {SQL_Statements}
We can verify the insert operation by using the SELECT statement. We will get the below output:
1. SELECT * FROM Employee;
We will also create another table named 'Employee_Audit_Test' to automatically store transaction records of each
operation, such as INSERT, UPDATE, or DELETE on the Employee table:
1. CREATE TABLE Employee_Audit_Test
2. (
3. Id int IDENTITY,
4. Audit_Action text
5. )
Now, we will create a trigger that stores transaction records of each insert operation on the Employee table into the
Employee_Audit_Test table. Here we are going to create the insert trigger using the below statement:
After creating a trigger, we will try to add the following record into the table:
1. INSERT INTO Employee VALUES (6,'Peter', 62000, 'Male', 3)
If no error is found, execute the SELECT statement to check the audit records.