Cursors, Triggers
Cursors, Triggers
1. COUNT FUNCTION
o 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.
o COUNT function uses the COUNT(*) that returns the count of all the rows in a
specified table. COUNT(*) considers duplicate and Null.
Syntax
1. COUNT(*)
2. or
3. COUNT( [ALL|DISTINCT] expression )
Sample table:
PRODUCT_MAST
Item1 Com1 2 10 20
Item2 Com2 3 25 75
Item3 Com1 2 30 60
Item4 Com3 5 10 50
Item5 Com2 2 20 40
Item6 Cpm1 3 25 75
Item8 Com1 3 10 30
Item9 Com2 2 25 50
Example: COUNT()
1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;
Output:
10
1. SELECT COUNT(*)
2. FROM PRODUCT_MAST;
3. WHERE RATE>=20;
Output:
Output:
Output:
Com1 5
Com2 3
Com3 2
Output:
Com1 5
Com2 3
2. SUM Function
Sum function is used to calculate the sum of all selected columns. It works on numeric
fields only.
Syntax
1. SUM()
2. or
3. SUM( [ALL|DISTINCT] expression )
Example: SUM()
1. SELECT SUM(COST)
2. FROM PRODUCT_MAST;
Output:
670
1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3;
Output:
320
1. SELECT SUM(COST)
2. FROM PRODUCT_MAST
3. WHERE QTY>3
4. GROUP BY COMPANY;
Output:
Com1 150
Com2 170
Output:
Com1 335
Com3 170
3. AVG function
The AVG function is used to calculate the average value of the numeric type. AVG function
returns the average of all non-Null values.
Syntax
1. AVG()
2. or
3. AVG( [ALL|DISTINCT] expression )
Example:
1. SELECT AVG(COST)
2. FROM PRODUCT_MAST;
Output:
67.00
4. MAX Function
MAX function is used to find the maximum value of a certain column. This function
determines the largest value of all selected values of a column.
Syntax
1. MAX()
2. or
3. MAX( [ALL|DISTINCT] expression )
Example:
1. SELECT MAX(RATE)
2. FROM PRODUCT_MAST;
30
5. MIN Function
MIN function is used to find the minimum value of a certain column. This function
determines the smallest value of all selected values of a column.
Syntax
1. MIN()
2. or
3. MIN( [ALL|DISTINCT] expression )
Example:
1. SELECT MIN(RATE)
2. FROM PRODUCT_MAST;
Output:
10
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:
Syntax of Trigger
We can create a trigger in SQL Server by using the CREATE TRIGGER statement as
follows:
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.
We can verify the insert operation by using the SELECT statement. We will get the below
output:
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:
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:
After creating a trigger, we will delete a record from the Employee table:
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.
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.
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.
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.
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.
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.
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.
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.
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.
We can use the DROP TRIGGER statement in the below format to delete one or more
LOGON triggers:
We can use the DROP TRIGGER statement in the below format to delete one or more DDL
triggers:
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:
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:
Cursor in SQL
In SQL, a cursor is a temporary workstation that is allocated by the database server during
the execution of a statement.
It is a database object that allows us to access data of one row at a time. This concept of
SQL is useful when the user wants to update the rows of the table one by one.
The cursor in SQL is the same as the looping technique of other programming languages.
The collection of tuples held by the cursor is known as the active set.
In SQL database systems, users define the cursor using DECLARE statement and take the
SELECT statement as the parameter, which helps in returning the set of rows.
In this SQL article, we will learn about the types of a cursor, the life cycle of a cursor, syntax
of a cursor, and the implementation of a cursor.
1. Implicit Cursor
2. Explicit Cursor
Implicit Cursor
These types of cursors are generated and allocated by the SQL server when the system
performs INSERT, DELETE, and UPDATE operations on SQL queries.
This cursor is also referred to as the default cursor in SQL.
An implicit cursor is also created by the system when the SELECT query selects the single
row.
Explicit Cursor
These types of cursors are created by the user using the SELECT query.
An explicit cursor holds multiple records but processes a single row at a time. It uses the
pointer, which moves to another row after reading one row.
It is basically used for gaining extra control over the temporary workstation.
1. Declare a Cursor
2. Open Cursor
3. Fetch Data from Cursor
4. Close Cursor Connection
5. Deallocate cursor
1. Declare a Cursor
First, we have to declare the cursor by using the following SQL syntax:
In this syntax, we have to specify the name and data type of the cursor just after the
DECLARE keyword. After that, we have to write the SELECT statement, which defines the
result set for the cursor.
2. Open Cursor
It is the second stage that opens the cursor for storing the data retrieved from the result
set. We can open the cursor by using the following SQL syntax:
1. OPEN Cursor_Name;
3. Fetch Cursor
It is the third stage in the cursor life cycle that fetches the rows for performing the
insertion, deletion, and updation operations on the currently active tuple in the cursor.
Following are the six options that are used in syntax for fetching data from the cursor:
i. FIRST: This option allows the system to access only the first record from the cursor
table. The syntax for the FIRST option is given below:
ii. LAST: This option allows the system to access only the last record from the cursor table.
The syntax for the LAST option is as follows:
iii. NEXT: This method allows the system to access the data in the forward direction from
the cursor table. It is the default option. The syntax of this method is as follows:
iv. PRIOR: This method allows the system to access the data in the backward direction
from the cursor table. The syntax of this option is as follows:
v. ABSOLUTE n: This method allows the system to access the data of the exact nth row
from the cursor table. The syntax of this option is mentioned below:
vi. RELATIVE n: This method allows the system to access the data in both incremental
and decremental processes. The syntax of this option is mentioned below:
CLOSE Cursor_Name;
5. Deallocate Cursor
It is the last and fifth stage of the cursor life cycle. In this part, we have to erase the
definition of the cursor and discharge all the system resources combined with the cursor.
2. DECLARE My_Cursor_Name CURSOR // You have to declare the Name of your Curso
r
3. [LOCAL | GLOBAL] // You have to specify the Scope of your Cursor
4. [FORWARD_ONLY | SCROLL] // You have to specify the movement direction of y
our Cursor
5. [ KEYSET | DYNAMIC |STATIC | FAST_FORWARD] // You have to specify the Basic type
of your Cursor
6. [ SCROLL_LOCKS | OPTIMISTIC |READ_ONLY ] // You have to specify the Locks for your
Cursor
7. OPEN My_Cursor_Name // You have to Open Your Cursor
8. FETCH NEXT FROM My_Cursor_Name // This line fetches the data from your Cursor
9. CLOSE My_Cursor_Name // Here, you have to close Your Cursor
10. DEALLOCATE My_Cursor_Name // Here, you have to deallocate the cursor memory.
1. STATIC Cursor
2. Forward Only cursor
3. KEYSET Driven Cursor
4. Dynamic Cursor
STATIC Cursor
The static cursor can move in forward as well as backward direction. This type of cursor
populates the result set during the creation of a cursor. Compared to other cursors, it is
slow and uses more space in the memory.
By default, these types of cursors are scrollable. The static cursor does not allow the
database users to modify and delete data.
The main disadvantage of this cursor is that it does not support backward scrolling.
1. Forward_Only KEYSET,
2. Forward_Only KEYSET,
3. FAST_FORWARD
DYNAMIC Cursor
The dynamic cursor is just opposite to the static cursor. It allows us to execute the INSERT,
DELETE, and UPDATE operations while the cursor is open.
It checks all the modifications done on the rows and values in the result set.
Now, insert some values into the above Student table as shown in the following block:
We can check the data of the Student table by using the following SELECT statement in
SQL:
This query shows the data of the Student table in the output:
1 Amit BCA 19 88
2 Rahul MCA 21 98
3 Jones B.tech 20 93
4 Riya BCA 19 89
5 Aaniya BBA 21 92
6 Saket MCA 19 95
7 Shobhit MBA 20 90
8 Ishika BCA 21 89
9 Parul B.tech 19 91
10 Yukti BCA 20 96
Now, we will create the following cursor for displaying the record of students from the
Student table:
1 Amit BCA
2 Rahul MCA
3 Jones B.tech
4 Riya BCA
5 Aaniya BBA
6 Saket MCA
7 Shobhit MBA
8 Ishika BCA
9 Parul B.tech
10 Yukti BCA
PL/SQL Procedure
The PL/SQL stored procedure or simply a procedure is a PL/SQL block which performs
one or more specific tasks. It is just like procedures in other programming languages.
o Header: The header contains the name of the procedure and the parameters or variables
passed to the procedure.
o Body: The body contains a declaration section, execution section and exception section
similar to a general PL/SQL block.
In this example, we are going to insert record in user table. So you need to create user
table first.
Table creation:
Procedure Code:
Output:
Procedure created.