9 DB Unit 3
9 DB Unit 3
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
Table 2: t2_employees
Table 3: t_students
Table 4: t2_students
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:
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:
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:
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:
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:
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:
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:
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:
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
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.
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;
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
% Attribute indicator
. Component selector
, Item separator
= Relational operator
; Statement terminator
:= Assignment operator
|| Concatenation operator
** Exponentiation operator
.. Range operator
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
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.
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
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
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.
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:
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
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
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.