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

9 DB Unit 3

SET operators in SQL are used to combine the results of two queries. The main SET operators are UNION, UNION ALL, INTERSECT, and MINUS. UNION combines results and eliminates duplicate rows, while UNION ALL combines results but keeps duplicate rows. When using SET operators, the number and order of columns must be the same and data types must be compatible. Examples demonstrate using UNION and UNION ALL to combine results from different tables.

Uploaded by

iamchirec
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

9 DB Unit 3

SET operators in SQL are used to combine the results of two queries. The main SET operators are UNION, UNION ALL, INTERSECT, and MINUS. UNION combines results and eliminates duplicate rows, while UNION ALL combines results but keeps duplicate rows. When using SET operators, the number and order of columns must be the same and data types must be compatible. Examples demonstrate using UNION and UNION ALL to combine results from different tables.

Uploaded by

iamchirec
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

SET Operators in SQL

SET operators are special type of operators which are used to combine the result of two queries.
Operators covered under SET operators are:
1. UNION
2. UNION ALL
3. INTERSECT
4. MINUS

There are certain rules which must be followed to perform operations using SET operators in SQL. Rules are as follows:
1. The number and order of columns must be the same.
2. Data types must be compatible.
Let us see each of the SET operators in more detail with the help of examples.
All the examples will be written using the MySQL database.
Consider we have the following tables with the given data.
Table 1: t_employees

ID Name Department Salary Year_of_Experience

1 Aakash Singh Development 72000 2

2 Abhishek Pawar Production 45000 1

3 Pranav Deshmukh HR 59900 3

4 Shubham Mahale Accounts 57000 2

5 Sunil Kulkarni Development 87000 3

6 Bhushan Wagh R&D 75000 2

7 Paras Jaiswal Marketing 32000 1

Table 2: t2_employees

ID Name Department Salary Year_of_Experience

1 Prashant Wagh R&D 49000 1

2 Abhishek Pawar Production 45000 1

3 Gautam Jain Development 56000 4

4 Shubham Mahale Accounts 57000 2

5 Rahul Thakur Production 76000 4


6 Bhushan Wagh R&D 75000 2

7 Anand Singh Marketing 28000 1

Table 3: t_students

ID Name Hometown Percentage Favourite_Subject

1 Soniya Jain Udaipur 89 Physics

2 Harshada Sharma Kanpur 92 Chemistry

3 Anuja Rajput Jaipur 78 History

4 Pranali Singh Nashik 88 Geography

5 Renuka Deshmukh Panipat 90 Biology

6 Swati Kumari Faridabad 93 English

7 Prachi Jaiswal Gurugram 96 Hindi

Table 4: t2_students

ID Name Hometown Percentage Favourite_Subject

1 Soniya Jain Udaipur 89 Physics

2 Ishwari Dixit Delhi 86 Hindi

3 Anuja Rajput Jaipur 78 History

4 Pakhi Arora Surat 70 Sanskrit

5 Renuka Deshmukh Panipat 90 Biology

6 Jayshree Patel Pune 91 Maths

7 Prachi Jaiswal Gurugram 96 Hindi

1. UNION:
o UNION will be used to combine the result of two select statements.
o Duplicate rows will be eliminated from the results obtained after performing the UNION operation.
Example 1:
Write a query to perform union between the table t_employees and the table t2_employees.
Query:
1. mysql> SELECT *FROM t_employees UNION SELECT *FROM t2_employees;
Here, in a single query, we have written two SELECT queries. The first SELECT query will fetch the records from the
t_employees table and perform a UNION operation with the records fetched by the second SELECT query from the
t2_employees table.
You will get the following output:

ID Name Department Salary Year_of_Experience

1 Aakash Singh Development 72000 2


2 Abhishek Pawar Production 45000 1

3 Pranav Deshmukh HR 59900 3

4 Shubham Mahale Accounts 57000 2

5 Sunil Kulkarni Development 87000 3

6 Bhushan Wagh R&D 75000 2

7 Paras Jaiswal Marketing 32000 1

1 Prashant Wagh R&D 49000 1

3 Gautam Jain Development 56000 4

5 Rahul Thakur Production 76000 4

7 Anand Singh Marketing 28000 1

Since we have performed union operation between both the tables, so only the records from the first and second table are
displayed except for the duplicate records.
Example 2:
Write a query to perform union between the table t_students and the table t2_students.
Query:
1. mysql> SELECT *FROM t_students UNION SELECT *FROM t2_students;
Here, in a single query, we have written two SELECT queries. The first SELECT query will fetch the records from the t_students
table and perform a UNION operation with the records fetched by the second SELECT query from the t2_students table.
You will get the following output:

ID Name Department Salary Year_of_Experience

1 Soniya Jain Udaipur 89 Physics

2 Harshada Sharma Kanpur 92 Chemistry

3 Anuja Rajput Jaipur 78 History

4 Pranali Singh Nashik 88 Geography

5 Renuka Deshmukh Panipat 90 Biology

6 Swati Kumari Faridabad 93 English

7 Prachi Jaiswal Gurugram 96 Hindi

2 Ishwari Dixit Delhi 86 Hindi

4 Pakhi Arora Surat 70 Sanskrit

6 Jayshree Patel Pune 91 Maths

Since we have performed union operation between both the tables, so only the records from the first and second table are
displayed except for the duplicate records.
AD

2. UNION ALL
o This operator combines all the records from both the queries.
o Duplicate rows will be not be eliminated from the results obtained after performing the UNION ALL operation.
AD

Example 1:
Write a query to perform union all operation between the table t_employees and the table t2_employees.
Query:
1. mysql> SELECT *FROM t_employees UNION ALL SELECT *FROM t2_employees;
Here, in a single query, we have written two SELECT queries. The first SELECT query will fetch the records from the
t_employees table and perform UNION ALL operation with the records fetched by the second SELECT query from the
t2_employees table.
You will get the following output:

ID Name Department Salary Year_of_Experience

1 Aakash Singh Development 72000 2

2 Abhishek Pawar Production 45000 1

3 Pranav Deshmukh HR 59900 3

4 Shubham Mahale Accounts 57000 2

5 Sunil Kulkarni Development 87000 3

6 Bhushan Wagh R&D 75000 2

7 Paras Jaiswal Marketing 32000 1

1 Prashant Wagh R&D 49000 1

2 Abhishek Pawar Production 45000 1

3 Gautam Jain Development 56000 4

4 Shubham Mahale Accounts 57000 2

5 Rahul Thakur Production 76000 4

6 Bhushan Wagh R&D 75000 2

7 Anand Singh Marketing 28000 1

Since we have performed union all operation between both the tables, so all the records from the first and second table are
displayed, including the duplicate records.
Example 2:
Write a query to perform union all operation between the table t_students and the table t2_students.
Query:
1. mysql> SELECT *FROM t_students UNION ALL SELECT *FROM t2_students;
Here, in a single query, we have written two SELECT queries. The first SELECT query will fetch the records from the t_students
table and perform UNION ALL operation with the records fetched by the second SELECT query from the t2_students table.
You will get the following output:

ID Name Hometown Percentage Favourite_Subject

1 Soniya Jain Udaipur 89 Physics


2 Harshada Sharma Kanpur 92 Chemistry

3 Anuja Rajput Jaipur 78 History

4 Pranali Singh Nashik 88 Geography

5 Renuka Deshmukh Panipat 90 Biology

6 Swati Kumari Faridabad 93 English

7 Prachi Jaiswal Gurugram 96 Hindi

1 Soniya Jain Udaipur 89 Physics

2 Ishwari Dixit Delhi 86 Hindi

3 Anuja Rajput Jaipur 78 History

4 Pakhi Arora Surat 70 Sanskrit

5 Renuka Deshmukh Panipat 90 Biology

6 Jayshree Patel Pune 91 Maths

7 Prachi Jaiswal Gurugram 96 Hindi

Since we have performed union all operation between both the tables, so all the records from the first and second table are
displayed, including the duplicate records.

3. INTERSECT:
o It is used to combine two SELECT statements, but it only returns the records which are common from both SELECT
statements.
Example 1:
Write a query to perform intersect operation between the table t_employees and the table t2_employees.
Query:
1. mysql> SELECT *FROM t_employees INTERSECT SELECT *FROM t2_employees;
Here, in a single query, we have written two SELECT queries. The first SELECT query will fetch the records from the
t_employees table and perform INTERSECT operation with the records fetched by the second SELECT query from the
t2_employees table.
You will get the following output:

ID Name Hometown Percentage Favourite_Subject

2 Abhishek Pawar Production 45000 1

4 Shubham Mahale Accounts 57000 2

6 Bhushan Wagh R&D 75000 2

Since we have performed intersect operation between both the tables, so only the common records from both the tables are
displayed.
Example 2:
Write a query to perform intersect operation between the table t_students and the table t2_students.
Query:
1. mysql> SELECT *FROM t_students INTERSECT SELECT *FROM t2_students;
Here, in a single query, we have written two SELECT queries. The first SELECT query will fetch the records from the t_students
table and perform a UNION operation with the records fetched by the second SELECT query from the t2_students table.
You will get the following output:

ID Name Hometown Percentage Favourite_Subject

1 Soniya Jain Udaipur 89 Physics

3 Anuja Rajput Jaipur 78 History

5 Renuka Deshmukh Panipat 90 Biology

7 Prachi Jaiswal Gurugram 96 Hindi

Since we have performed intersect operation between both the tables, so only the common records from both the tables are
displayed.
4. MINUS
o It displays the rows which are present in the first query but absent in the second query with no duplicates.
Example 1:
Write a query to perform a minus operation between the table t_employees and the table t2_employees.
Query:
1. mysql> SELECT *FROM t_employees MINUS SELECT *FROM t2_employees;
Here, in a single query, we have written two SELECT queries. The first SELECT query will fetch the records from the
t_employees table and perform MINUS operation with the records fetched by the second SELECT query from the
t2_employees table.
You will get the following output:

ID Name Department Salary Year_of_Experience

1 Aakash Singh Development 72000 2

3 Pranav Deshmukh HR 59900 3

5 Sunil Kulkarni Development 87000 3

7 Paras Jaiswal Marketing 32000 1

Since we have performed Minus operation between both the tables, so only the unmatched records from both the tables are
displayed.
Example 2:
Write a query to perform a minus operation between the table t_students and the table t2_students.
Query:
1. mysql> SELECT *FROM t_students MINUS SELECT *FROM t2_students;
Here, in a single query, we have written two SELECT queries. The first SELECT query will fetch the records from the
t_employees table and perform a UNION operation with the records fetched by the second SELECT query from the
t2_employees table.
You will get the following output:

ID Name Hometown Percentage Favourite_Subject

2 Harshada Sharma Kanpur 92 Chemistry

4 Pranali Singh Nashik 88 Geography

6 Swati Kumari Faridabad 93 English


Since we have performed a minus operation between both the tables, so only the Unmatched records from both the tables
are displayed
Nested queries in SQL can be classified into two different types:
 Independent Nested Queries

 Co-related Nested Queries


Independent Nested Queries
In independent nested queries, the execution order is from the innermost query to the outer
query. An outer query won't be executed until its inner query completes its execution. The result
of the inner query is used by the outer query. Operators such as IN, NOT IN, ALL,
and ANY are used to write independent nested queries.
 The IN operator checks if a column value in the outer query's result is present in the inner
query's result. The final result will have rows that satisfy the IN condition.
 The NOT IN operator checks if a column value in the outer query's result is not present in the
inner query's result. The final result will have rows that satisfy the NOT IN condition.
 The ALL operator compares a value of the outer query's result with all the values of the inner
query's result and returns the row if it matches all the values.
 The ANY operator compares a value of the outer query's result with all the inner query's result
values and returns the row if there is a match with any value.

Co-related Nested Queries


In co-related nested queries, the inner query uses the values from the outer query so that the inner query is executed
for every row processed by the outer query. The co-related nested queries run slow because the inner query is
executed for every row of the outer query's result.
How to Write Nested Query in SQL?
We can write a nested query in SQL by nesting a SELECT statement within another SELECT statement. The
outer SELECT statement uses the result of the inner SELECT statement for processing.
The general syntax of nested queries will be:

SELECT column_name [, column_name ]


FROM table1 [, table2 ]
WHERE column_name OPERATOR
(
SELECT column_name [, column_name ]
FROM table1 [, table2 ]
[WHERE]
)
The SELECT query inside the brackets (()) is the inner query, and the SELECT query outside the brackets is the outer query. The
result of the inner query is used by the outer query.

Examples of Nested Query in SQL


We will use the Employees and Awards table below to understand independent and co-related nested queries. We will be
using Oracle SQL syntax in our queries.
Let's create the Employees and Awards tables:
CREATE TABLE employee (
id NUMBER PRIMARY KEY,
name VARCHAR2(100) NOT NULL,
salary NUMBER NOT NULL,
role VARCHAR2(100) NOT NULL
);
CREATE TABLE awards(
id NUMBER PRIMARY KEY,
employee_id NUMBER NOT NULL,
award_date DATE NOT NULL
);
Let's add data to the tables created above:
INSERT INTO employees VALUES (1, 'Augustine Hammond', 10000, 'Developer');
INSERT INTO employees VALUES (2, 'Perice Mundford', 10000, 'Manager');
INSERT INTO employees VALUES (3, 'Cassy Delafoy', 30000, 'Developer');
INSERT INTO employees VALUES (4, 'Garwood Saffen', 40000, 'Manager');
INSERT INTO employees VALUES (5, 'Faydra Beaves', 50000, 'Developer');
INSERT INTO awards VALUES(1, 1, TO_DATE('2022-04-01', 'YYYY-MM-DD'));
INSERT INTO awards VALUES(2, 3, TO_DATE('2022-05-01', 'YYYY-MM-DD'));

Employees
id name salary role
1 Augustine Hammond 10000 Developer
2 Perice Mundford 10000 Manager
3 Cassy Delafoy 30000 Developer
4 Garwood Saffen 40000 Manager
5 Faydra Beaves 50000 Developer

Awards
id employee_id award_date
1 1 2022-04-01
2 3 2022-05-01

Independent Nested Queries


Example 1: IN
Select all employees who won an award.
SELECT id, name FROM employees
WHERE id IN (SELECT employee_id FROM awards);
Output
id name
2 Perice Mundford
4 Garwood Saffen
5 Faydra Beaves
Example 2: NOT IN
Select all employees who never won an award.
SELECT id, name FROM employees
WHERE id NOT IN (SELECT employee_id) FROM awards);
Output
id name
1 Augustine Hammond
3 Cassy Delafoy
Example 3: ALL
Select all Developers who earn more than all the Managers
SELECT * FROM employees
WHERE role = 'Developer'
AND salary > ALL (
SELECT salary FROM employees WHERE role = 'Manager'
);
Output
id name salary role
5 Faydra Beaves 50000 Developer
Explanation
The developer with id 5 earns (50000) more than all the managers: 2 (10000) and 4 (40000)
Example 4: ANY
Select all Developers who earn more than any Manager
SELECT * FROM employees
WHERE role = 'Developer'
AND salary > ANY (
SELECT salary FROM employees WHERE role = 'Manager'
);
Output
id name salary role
5 Faydra Beaves 50000 Developer
3 Cassy Delafoy 30000 Developer
Explanation
The developers with id 3 and 5 earn more than any manager:
The developer with id 3 earns (30000) more than the manager with id 2 (10000)
 The developer with id 5 earns (50000) more than the managers with id 2 (10000) and 4 (40000)
Co-related Nested Queries
Select all employees whose salary is above the average salary of employees in their role.
SELECT * FROM employees emp1
WHERE salary > (
SELECT AVG(salary) FROM employees emp2
WHERE emp1.role = emp2.role
);
Output
id name salary role
4 Garwood Saffen 40000 Manager
5 Faydra Beaves 50000 Developer
Explanation
The manager with id 4 earns more than the average salary of all managers (25000), and the
developer with id 5 earns more than the average salary of all developers (30000). The inner
query is executed for all rows fetched by the outer query. The role value (emp1.role) of every
outer query's row is used by the inner query (emp1.role = emp2.role).
We can find the average salary of managers and developers using the below query:
SELECT role, AVG(salary) FROM employees GROUP BY role;
role avg(salary)
Developer 30000
Manager 25000
Conclusion
 A nested query in SQL contains a query inside another query, and the outer query will use the
result of the inner query.
 We can classify nested queries into independent and co-related nested queries.
 In independent nested queries, the order of execution is from the innermost query to the
outermost query
 In co-related nested queries, the inner query uses the values from the outer query so that the
inner query is executed for every row processed by the outer query
 Co-related nested query runs slow when compared with independent nested query.
Introduction to SQL aggregate functions

An aggregate function allows you to perform a calculation on a set of values to return a single scalar value. We often use
aggregate functions with the GROUP BY and HAVING clauses of the SELECT statement.
The following are the most commonly used SQL aggregate functions:
 AVG – calculates the average of a set of values.
 COUNT – counts rows in a specified table or view.
 MIN – gets the minimum value in a set of values.
 MAX – gets the maximum value in a set of values.
 SUM – calculates the sum of values.
Notice that all aggregate functions above ignore NULL values except for the COUNT function.

SQL aggregate functions syntax


To call an aggregate function, you use the following syntax:
aggregate_function (DISTINCT | ALL expression)
Let’s examine the syntax above in greater detail:
 First, specify an aggregate function that you want to use e.g., MIN, MAX, AVG, SUM or COUNT.
 Second, put DISTINCT or ALL modifier followed by an expression inside parentheses. If you explicitly use
the DISTINCT modifier, the aggregate function ignores duplicate values and only consider the unique values. If
you use the ALL modifier, the aggregate function uses all values for calculation or evaluation. The ALL modifier
is used by default if you do not specify any modifier explicitly.

SQL aggregate function examples


Let’s take a look some examples of using SQL aggregate functions.
COUNT function example
To get the number of products in the products table, you use the COUNT function as follows:
SELECT
COUNT(*)
FROM
products;

More information on the COUNT function.


AVG function example
To calculate the average units in stock of the products, you use the AVG function as follows:
SELECT
AVG(unitsinstock)
FROM
products;

To calculate units in stock by product category, you use the AVG function with the GROUP BY clause as follows:
SELECT
categoryid, AVG(unitsinstock)
FROM
products
GROUP BY categoryid;
More information on AVG function.
SUM function example
To calculate the sum of units in stock by product category, you use the SUM function with the GROUP BY clause as the
following query:
SELECT
categoryid, SUM(unitsinstock)
FROM
products
GROUP BY categoryid;

Check it out the SUM function tutorial for more information on how to use the SUM function.
MIN function example
To get the minimum units in stock of products in the products table, you use the MIN function as follows:
SELECT
MIN(unitsinstock)
FROM
products;

More information on the MIN function.


MAX function example
To get the maximum units in stock of products in the products table, you use the MAX function as shown in the following
query:
SELECT
MAX(unitsinstock)
FROM
products;

Procedures in sql
we will discuss the Basic Syntax of PL/SQL which is a block-structured language; this means that the PL/SQL programs
are divided and written in logical blocks of code. Each block consists of three sub-parts −
S.No Sections & Description

Declarations
1 This section starts with the keyword DECLARE. It is an optional section and defines all variables, cursors, subprograms,
and other elements to be used in the program.

Executable Commands
This section is enclosed between the keywords BEGIN and END and it is a mandatory section. It consists of the
2
executable PL/SQL statements of the program. It should have at least one executable line of code, which may be just
a NULL command to indicate that nothing should be executed.

Exception Handling
3 This section starts with the keyword EXCEPTION. This optional section contains exception(s) that handle errors in the
program.
Every PL/SQL statement ends with a semicolon (;). PL/SQL blocks can be nested within other PL/SQL blocks
using BEGIN and END. Following is the basic structure of a PL/SQL block −
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;
The 'Hello World' Example
DECLARE
message varchar2(20):= 'Hello, World!';
BEGIN
dbms_output.put_line(message);
END;
/
The end; line signals the end of the PL/SQL block. To run the code from the SQL command line, you may need to type / at
the beginning of the first blank line after the last line of the code. When the above code is executed at the SQL prompt, it
produces the following result −
Hello World

PL/SQL procedure successfully completed.


AD

The PL/SQL Identifiers


PL/SQL identifiers are constants, variables, exceptions, procedures, cursors, and reserved words. The identifiers consist of
a letter optionally followed by more letters, numerals, dollar signs, underscores, and number signs and should not exceed 30
characters.
By default, identifiers are not case-sensitive. So you can use integer or INTEGER to represent a numeric value. You
cannot use a reserved keyword as an identifier.
The PL/SQL Delimiters
A delimiter is a symbol with a special meaning. Following is the list of delimiters in PL/SQL −
Delimiter Description
+, -, *, / Addition, subtraction/negation, multiplication, division

% Attribute indicator

' Character string delimiter

. Component selector

(,) Expression or list delimiter

: Host variable indicator

, Item separator

" Quoted identifier delimiter

= Relational operator

@ Remote access indicator

; Statement terminator

:= Assignment operator

=> Association operator

|| Concatenation operator

** Exponentiation operator

<<, >> Label delimiter (begin and end)

/*, */ Multi-line comment delimiter (begin and end)

-- Single-line comment indicator

.. Range operator

<, >, <=, >= Relational operators

<>, '=, ~=, ^= Different versions of NOT EQUAL


AD

The PL/SQL Comments


Program comments are explanatory statements that can be included in the PL/SQL code that you write and helps anyone
reading its source code. All programming languages allow some form of comments.
The PL/SQL supports single-line and multi-line comments. All characters available inside any comment are ignored by the
PL/SQL compiler. The PL/SQL single-line comments start with the delimiter -- (double hyphen) and multi-line comments are
enclosed by /* and */.
DECLARE
-- variable declaration
message varchar2(20):= 'Hello, World!';
BEGIN
/*
* PL/SQL executable statement(s)
*/
dbms_output.put_line(message);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Hello World
PL/SQL procedure successfully completed.

PL/SQL Program Units


A PL/SQL unit is any one of the following −
 PL/SQL block
 Function
 Package
 Package body
 Procedure
 Trigger
 Type
 Type body
Variable Declaration in PL/SQL
PL/SQL variables must be declared in the declaration section or in a package as a global variable. When you declare a
variable, PL/SQL allocates memory for the variable's value and the storage location is identified by the variable name.
The syntax for declaring a variable is −
variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT initial_value]
Where, variable_name is a valid identifier in PL/SQL, datatype must be a valid PL/SQL data type or any user defined data
type which we already have discussed in the last chapter. Some valid variable declarations along with their definition are
shown below −
sales number(10, 2);
pi CONSTANT double precision := 3.1415;
name varchar2(25);
address varchar2(100);
When you provide a size, scale or precision limit with the data type, it is called a constrained declaration. Constrained
declarations require less memory than unconstrained declarations. For example −
sales number(10, 2);
name varchar2(25);
address varchar2(100);

procedures
Creating a Procedure
A procedure is created with the CREATE OR REPLACE PROCEDURE statement. The simplified syntax for the CREATE
OR REPLACE PROCEDURE statement is as follows −
CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
{IS | AS}
BEGIN
< procedure_body >
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 types of the parameters. IN represents the value that will be
passed from outside and OUT represents the parameter that will be used to return a value outside of the procedure.
 procedure-body contains the executable part.
 The AS keyword is used instead of the IS keyword for creating a standalone procedure.
Example
The following example creates a simple procedure that displays the string 'Hello World!' on the screen when executed.
CREATE OR REPLACE PROCEDURE greetings
AS
BEGIN
dbms_output.put_line('Hello World!');
END;
/
When the above code is executed using the SQL prompt, it will produce the following result −
Procedure created.
Executing a Standalone Procedure
A standalone procedure can be called in two ways −
 Using the EXECUTE keyword
 Calling the name of the procedure from a PL/SQL block
The above procedure named 'greetings' can be called with the EXECUTE keyword as −
EXECUTE greetings;
The above call will display −
Hello World

PL/SQL procedure successfully completed.


The procedure can also be called from another PL/SQL block −
BEGIN
greetings;
END;
/
The above call will display −
Hello World

PL/SQL procedure successfully completed.


AD

Deleting a Standalone Procedure


A standalone procedure is deleted with the DROP PROCEDURE statement. Syntax for deleting a procedure is −
DROP PROCEDURE procedure-name;
You can drop the greetings procedure by using the following statement −
DROP PROCEDURE greetings;
Parameter Modes in PL/SQL Subprograms
The following table lists out the parameter modes in PL/SQL subprograms −
S.No Parameter Mode & Description

IN
An IN parameter lets you pass a value to the subprogram. It is a read-only parameter. Inside the subprogram, an IN
1 parameter acts like a constant. It cannot be assigned a value. You can pass a constant, literal, initialized variable, or
expression as an IN parameter. You can also initialize it to a default value; however, in that case, it is omitted from the
subprogram call. It is the default mode of parameter passing. Parameters are passed by reference.

OUT
An OUT parameter returns a value to the calling program. Inside the subprogram, an OUT parameter acts like a variable.
2
You can change its value and reference the value after assigning it. The actual parameter must be variable and it is
passed by value.

IN OUT
An IN OUT parameter passes an initial value to a subprogram and returns an updated value to the caller. It can be
3 assigned a value and the value can be read.
The actual parameter corresponding to an IN OUT formal parameter must be a variable, not a constant or an expression.
Formal parameter must be assigned a value. Actual parameter is passed by value.

IN & OUT Mode Example 1


This program finds the minimum of two values. Here, the procedure takes two numbers using the IN mode and returns their
minimum using the OUT parameters.
DECLARE
a number;
b number;
c number;
PROCEDURE findMin(x IN number, y IN number, z OUT number) IS
BEGIN
IF x < y THEN
z:= x;
ELSE
z:= y;
END IF;
END;
BEGIN
a:= 23;
b:= 45;
findMin(a, b, c);
dbms_output.put_line(' Minimum of (23, 45) : ' || c);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Minimum of (23, 45) : 23

PL/SQL procedure successfully completed.


IN & OUT Mode Example 2
This procedure computes the square of value of a passed value. This example shows how we can use the same parameter
to accept a value and then return another result.
DECLARE
a number;
PROCEDURE squareNum(x IN OUT number) IS
BEGIN
x := x * x;
END;
BEGIN
a:= 23;
squareNum(a);
dbms_output.put_line(' Square of (23): ' || a);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Square of (23): 529

PL/SQL procedure successfully completed.


Methods for Passing Parameters
Actual parameters can be passed in three ways −
 Positional notation
 Named notation
 Mixed notation
Positional Notation
In positional notation, you can call the procedure as −
findMin(a, b, c, d);
In positional notation, the first actual parameter is substituted for the first formal parameter; the second actual parameter is
substituted for the second formal parameter, and so on. So, a is substituted for x, b is substituted for y, c is substituted
for z and d is substituted for m.
Named Notation
In named notation, the actual parameter is associated with the formal parameter using the arrow symbol ( => ). The
procedure call will be like the following −
findMin(x => a, y => b, z => c, m => d);
Mixed Notation
In mixed notation, you can mix both notations in procedure call; however, the positional notation should precede the named
notation.
The following call is legal −
findMin(a, b, c, m => d);
However, this is not legal:
findMin(x => a, b, c, d);

Creating a Function
A standalone function is created using the CREATE FUNCTION statement. The simplified syntax for the CREATE OR
REPLACE PROCEDURE statement is as follows −
CREATE [OR REPLACE] FUNCTION function_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
END [function_name];
Where,
 function-name specifies the name of the function.
 [OR REPLACE] option allows the modification of an existing function.
 The optional parameter list contains name, mode and types of the parameters. IN represents the value that will be
passed from outside and OUT represents the parameter that will be used to return a value outside of the procedure.
 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.
Example
The following example illustrates how to create and call a standalone function. This function returns the total number of
CUSTOMERS in the customers table.
We will use the CUSTOMERS table, which we had created in the PL/SQL Variables chapter −
Select * from customers;

+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
CREATE OR REPLACE FUNCTION totalCustomers
RETURN number IS
total number(2) := 0;
BEGIN
SELECT count(*) into total
FROM customers;

RETURN total;
END;
/
When the above code is executed using the SQL prompt, it will produce the following result −
Function created.
AD

Calling a Function
While creating a function, you give a definition of what the function has to do. To use a function, you will have to call that
function to perform the defined task. When a 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.
To call a function, you simply need to pass the required parameters along with the function name and if the function returns
a value, then you can store the returned value. Following program calls the function totalCustomers from an anonymous
block −
DECLARE
c number(2);
BEGIN
c := totalCustomers();
dbms_output.put_line('Total no. of Customers: ' || c);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Total no. of Customers: 6

PL/SQL procedure successfully completed.


Example
The following example demonstrates Declaring, Defining, and Invoking a Simple PL/SQL Function that computes and
returns the maximum of two values.
DECLARE
a number;
b number;
c number;
FUNCTION findMax(x IN number, y IN number)
RETURN number
IS
z number;
BEGIN
IF x > y THEN
z:= x;
ELSE
Z:= y;
END IF;
RETURN z;
END;
BEGIN
a:= 23;
b:= 45;
c := findMax(a, b);
dbms_output.put_line(' Maximum of (23,45): ' || c);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Maximum of (23,45): 45

PL/SQL procedure successfully completed.


PL/SQL Recursive Functions
We have seen that a program or subprogram may call another subprogram. When a subprogram calls itself, it is referred to
as a recursive call and the process is known as recursion.
To illustrate the concept, let us calculate the factorial of a number. Factorial of a number n is defined as −
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;

FUNCTION fact(x number)


RETURN number
IS
f number;
BEGIN
IF x=0 THEN
f := 1;
ELSE
f := x * fact(x-1);
END IF;
RETURN f;
END;

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

PL/SQL procedure successfully completed.

Triggers in SQL Server


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}
The parameter descriptions of this syntax illustrate below:
schema: It is an optional parameter that defines which schema the new trigger belongs to.
trigger_name: It is a required parameter that defines the name for the new trigger.
table_name: It is a required parameter that defines the table name to which the trigger applies. Next to the table name, we
need to write the AFTER clause where any events like INSERT, UPDATE, or DELETE could be listed.
NOT FOR REPLICATION: This option tells that SQL Server does not execute the trigger when data is modified as part of a
replication process.
SQL_Statements: It contains one or more SQL statements that are used to perform actions in response to an event that
occurs.
When we use triggers?
Triggers will be helpful when we need to execute some events automatically on certain desirable scenarios. For example, we
have a constantly changing table and need to know the occurrences of changes and when these changes happen. If the
primary table made any changes in such scenarios, we could create a trigger to insert the desired data into a separate table.

Example of Trigger in SQL Server


Let us understand how we can work with triggers in the SQL Server. We can do this by first creating a table named
'Employee' using the below statements:
1. CREATE TABLE Employee
2. (
3. Id INT PRIMARY KEY,
4. Name VARCHAR(45),
5. Salary INT,
6. Gender VARCHAR(12),
7. DepartmentId INT
8. )
Next, we will insert some record into this table as follows:
1. INSERT INTO Employee VALUES (1,'Steffan', 82000, 'Male', 3),
2. (2,'Amelie', 52000, 'Female', 2),
3. (3,'Antonio', 25000, 'male', 1),
4. (4,'Marco', 47000, 'Male', 2),
5. (5,'Eliana', 46000, 'Female', 3)
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:
1. CREATE TRIGGER trInsertEmployee
2. ON Employee
3. FOR INSERT
4. AS
5. BEGIN
6. Declare @Id int
7. SELECT @Id = Id from inserted
8. INSERT INTO Employee_Audit_Test
9. VALUES ('New employee with Id = ' + CAST(@Id AS VARCHAR(10)) + ' is added at ' + CAST(Getdate() AS VARCHAR(22)))
10. END
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. We will get the output as follows:

We are going to create another trigger to store transaction records of each delete operation on the Employee table into
the Employee_Audit_Test table. We can create the delete trigger using the below statement:
1. CREATE TRIGGER trDeleteEmployee
2. ON Employee
3. FOR DELETE
4. AS
5. BEGIN
6. Declare @Id int
7. SELECT @Id = Id from deleted
8. INSERT INTO Employee_Audit_Test
9. VALUES ('An existing employee with Id = ' + CAST(@Id AS VARCHAR(10)) + ' is deleted at ' + CAST(Getdate() AS VARCHA
R(22)))
10. END
After creating a trigger, we will delete a record from the Employee table:
1. DELETE FROM Employee WHERE Id = 2;
If no error is found, it gives the message as below:

Finally, execute the SELECT statement to check the audit records:


AD

In both the triggers code, you will notice these lines:


1. SELECT @Id = Id from inserted
2. SELECT @Id = Id from deleted
Here inserted and deleted are special tables used by the SQL Server. The inserted table keeps the copy of the row when you
insert a new row into the actual table. And the deleted table keeps the copy of the row you have just deleted from the actual
table.

Types of SQL Server Triggers


We can categorize the triggers in SQL Server in mainly three types:
1. Data Definition Language (DDL) Triggers
2. Data Manipulation Language (DML) Triggers
3. Logon Triggers

DDL Triggers
DDL triggers are fired in response to the DDL events, such as CREATE, ALTER, and DROP statements. We can create these
triggers at the database level or server level, depending on the type of DDL events. It can also be executed in response to
certain system-defined stored procedures that do DDL-like operations.
The DDL triggers are useful in the following scenario:
o When we need to prevent the database schema from changing
o When we need to audit changes made in the database schema
o When we need to respond to a change made in the database schema
AD

DML Triggers
DML triggers are fired in response to DML events like INSERT, UPDATE, and DELETE statements in the user's table or view. It
can also be executed in response to DML-like operations performed by system-defined stored procedures.
The DML triggers can be classified into two types:
o After Triggers
o Instead Of Triggers
After Triggers
After trigger fires, when SQL Server completes the triggering action successfully, that fired it. Generally, this trigger is
executed when a table completes an insert, update or delete operations. It is not supported in views. Sometimes it is known
as FOR triggers.
We can classify this trigger further into three types:
1. AFTER INSERT Trigger
2. AFTER UPDATE Trigger
3. AFTER DELETE Trigger

Example: When we insert data into a table, the trigger associated with the insert operation on that table will not fire until the
row has passed all constraints, such as the primary key constraint. SQL Server cannot fire the AFTER trigger when the data
insertion failed.
The following is illustration of the After Triggers syntax in SQL Server:
1. CREATE TRIGGER schema_name.trigger_name
2. ON table_name
3. AFTER {INSERT | UPDATE | DELETE}
4. AS
5. BEGIN
6. -- Trigger Statements
7. -- Insert, Update, Or Delete Statements
8. END
Instead of Triggers
Instead of Trigger fires before SQL Server begins to execute the triggering operation that triggered it. It means that no
condition constraint check is needed before the trigger runs. As a result, even if the constraint check fails, this trigger will fire.
It is the opposite of the AFTER trigger. We can create the INSTEAD OF triggers on a table that executes successfully but
doesn't contain the table's actual insert, update, or delete operations.
We can classify this trigger further into three types:
1. INSTEAD OF INSERT Trigger
2. INSTEAD OF UPDATE Trigger
3. INSTEAD OF DELETE Trigger
Example: When we insert data into a table, the trigger associated with the insert operation on that table will fire before the
data has passed all constraints, such as the primary key constraint. SQL Server also fires the Instead of Trigger if the data
insertion fails.
The following is an illustration of the Instead of Triggers syntax in SQL Server:
1. CREATE TRIGGER schema_name.trigger_name
2. ON table_name
3. INSTEAD OF {INSERT | UPDATE | DELETE}
4. AS
5. BEGIN
6. -- trigger statements
7. -- Insert, Update, or Delete commands
8. END
Logon Triggers
Logon triggers are fires in response to a LOGON event. The LOGON event occurs when a user session is generated with an
SQL Server instance, which is made after the authentication process of logging is completed but before establishing a user
session. As a result, the SQL Server error log will display all messages created by the trigger, including error messages and
the PRINT statement messages. If authentication fails, logon triggers do not execute. These triggers may be used to audit
and control server sessions, such as tracking login activity or limiting the number of sessions for a particular login.
AD

How to SHOW Triggers in SQL Server?


When we have many databases with multiple tables, the show or list trigger comes in handy. When the table names in
multiple databases are the same, this query is extremely helpful. Using the following command, we can see a list of all the
triggers available in SQL Server:
1. SELECT name, is_instead_of_trigger
2. FROM sys.triggers
3. WHERE type = 'TR';
If we are using the SQL Server Management Studio, it is very easy to show or list all triggers available in any specific table.
We can do this using the following steps:
o Go to the Databases menu, select desired database, and then expand it.
o Select the Tables menu and expand it.
o Select any specific table and expand it.
We will get various options here. When we choose the Triggers option, it displays all the triggers available in this table.
How to UPDATE Triggers in SQL Server?
The data stored in the table can be changed over a period of time. In that case, we also need to make changes in the
triggers. We can do this in two ways into the SQL Server. The first one is to use the SQL Server Management Studio, and the
second one is the Transact-SQL Query.
Modify Triggers using SSMS
First, open the Management Studio to modify the trigger. Next, go to the database and then the table where the trigger is
stored. Now, right-click on the trigger that you are going to change or update. It will open the context menu where you will
choose Modify option:

When you select the Modify option, you will see a new query window with automatically generated ALTER TRIGGER code.
We can change it according to our needs.
Modify Triggers using SQL Command
We can use the ALTER TRIGGER statement to modify the triggers in MS SQL. The following statement allows us to do
modifications to the triggers:
1. ALTER TRIGGER [dbo].[triggers_in_sql]
2. ON [dbo].[EmployeeTable]
3. AFTER INSERT
4. AS
5. BEGIN
6. -- Modify as per your needs
7. END

How to DELETE Triggers in SQL Server?


We can remove an existing trigger in SQL Server using the DROP TRIGGER statement. We must be very careful while
removing a trigger from the table. Because once we have deleted the trigger, it cannot be recovered. If a trigger is not found,
the DROP TRIGGER statement throws an error.
The following syntax removes DML triggers:
1. DROP TRIGGER [IF EXISTS] schema_name.trigger_name;
If we want to remove more than one trigger at once, we must separate the trigger using the comma operator:
1. DROP TRIGGER schema_name.trigger_name1, trigger_name2.....n;
We can use the DROP TRIGGER statement in the below format to delete one or more LOGON triggers:
1. DROP TRIGGER [ IF EXISTS ] trigger_name1, trigger_name2.....n
2. ON { DATABASE | ALL SERVER };
We can use the DROP TRIGGER statement in the below format to delete one or more DDL triggers:
1. DROP TRIGGER [ IF EXISTS ] trigger_name1, trigger_name2.....n
2. ON ALL SERVER;
If we are using the SQL Server Management Studio, it makes it very easy to delete triggers from the table. We can do this
using the following steps:
o Go to the Databases -> Tables menu and expand it.
o Select any specific table, expand it, and choose the Triggers option
This option displays all the available triggers in this table. Now, right-click on any specific trigger that you want to remove
and choose the Delete option from the drop-down menu.
Advantages of Triggers
The following are the advantages of using triggers in SQL Server:
o Triggers set database object rules and roll back if any change does not satisfy those rules. The trigger will inspect
the data and make changes if necessary.
o Triggers help us to enforce data integrity.
o Triggers help us to validate data before inserted or updated.
o Triggers help us to keep a log of records.
o Triggers increase SQL queries' performance because they do not need to compile each time they are executed.
o Triggers reduce the client-side code that saves time and effort.
o Triggers are easy to maintain.

Disadvantages of Triggers
The following are the disadvantages of using triggers in SQL Server:
o Triggers only allow using extended validations.
o Triggers are invoked automatically, and their execution is invisible to the user. Therefore, it isn't easy to
troubleshoot what happens in the database layer.
o Triggers may increase the overhead of the database server.
o We can define the same trigger action for multiple user actions such as INSERT and UPDATE in the same CREATE
TRIGGER statement.
o We can create a trigger in the current database only, but it can reference objects outside the current database.

You might also like