unit 2 sql
unit 2 sql
This database language is mainly designed for maintaining the data in relational
database management systems. It is a special tool used by data professionals for
handling structured data (data which is stored in the form of tables). It is also designed
for stream processing in RDSMS.
You can easily create and manipulate the database, access and modify the table rows
and columns, etc. This query language became the standard of ANSI in the year of 1986
and ISO in the year of 1987.
Nowadays, SQL is widely used in data science and analytics. Following are the reasons
which explain why it is widely used:
○ The basic use of SQL for data professionals and SQL users is to insert, update,
and delete the data from the relational database.
○ SQL allows the data professionals and users to retrieve the data from the
relational database management systems.
○ It allows SQL users to create, drop, and manipulate the database and its tables.
○ It also helps in creating the view, stored procedure, and functions in the relational
database.
○ It allows you to define the data and modify that stored data in the relational
database.
○ It also allows SQL users to set the permissions or constraints on table columns,
views, and stored procedures.
Structured Query Language contains the following four components in its process:
○ Query Dispatcher
○ Optimization Engines
A classic query engine allows data professionals and users to maintain non-SQL
queries. The architecture of SQL is shown in the following diagram:
Advantages of SQL
SQL provides various advantages which make it more popular in the field of data
science. It is a perfect query language which allows data professionals and users to
communicate with the database. Following are the best advantages or benefits of
Structured Query Language:
1. No programming needed
SQL does not require a large number of coding lines for managing the database
systems. We can easily access and maintain the database by using simple SQL
syntactical rules. These simple rules make the SQL user-friendly.
A large amount of data is accessed quickly and efficiently from the database by using
SQL queries. Insertion, deletion, and updation operations on data are also performed in
less time.
3. Standardized Language
SQL follows the long-established standards of ISO and ANSI, which offer a uniform
platform across the globe to all its users.
4. Portability
The structured query language can be easily used in desktop computers, laptops,
tablets, and even smartphones. It can also be used with other applications according to
the user's requirements.
5. Interactive language
We can easily learn and understand the SQL language. We can also use this language
for communicating with the database because it is a simple query language. This
language is also used for receiving the answers to complex queries in a few seconds.
The SQL language also helps in making the multiple views of the database structure for
the different database users.
Disadvantages of SQL
With the advantages of SQL, it also has some disadvantages, which are as follows:
1. Cost
The operation cost of some SQL versions is high. That's why some programmers cannot
use the Structured Query Language.
2. Interface is Complex
Another big disadvantage is that the interface of Structured query language is difficult,
which makes it difficult for SQL users to use and manage it.
The business rules are hidden. So, the data professionals and users who are using this
query language cannot have full database control.
SQL Commands
○ SQL commands are instructions. It is used to communicate with the database. It
is also used to perform specific tasks, functions, and queries of data.
○ SQL can perform various tasks like create a table, add data to tables, drop the
table, modify the table, set permission for users.
○ DDL changes the structure of the table like creating a table, deleting a table,
altering a table, etc.
○ All the command of DDL are auto-committed that means it permanently save all
the changes in the database.
○ CREATE
○ ALTER
○ DROP
○ TRUNCATE
Example:
b. DROP: It is used to delete both the structure and record stored in the table.
Syntax
Example
c. ALTER: It is used to alter the structure of the database. This change could be either to
modify the characteristics of an existing attribute or probably to add a new attribute.
Syntax:
EXAMPLE
d. TRUNCATE: It is used to delete all the rows from the table and free the space
containing the table.
Syntax:
Example:
○ DML commands are used to modify the database. It is responsible for all form of
changes in the database.
○ INSERT
○ UPDATE
○ DELETE
a. INSERT: The INSERT statement is a SQL query. It is used to insert data into the row of
a table.
Syntax:
For example:
Syntax:
For example:
1. UPDATE students
2. SET User_Name = 'Sonoo'
3. WHERE Student_Id = '3'
Syntax:
For example:
DCL commands are used to grant and take back authority from any database user.
○ Grant
○ Revoke
Example
1. GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;
Example
TCL commands can only use with DML commands like INSERT, DELETE and UPDATE
only.
These operations are automatically committed in the database that's why they cannot
be used while creating tables or dropping them.
○ COMMIT
○ ROLLBACK
○ SAVEPOINT
a. Commit: Commit command is used to save all the transactions to the database.
Syntax:
1. COMMIT;
Example:
b. Rollback: Rollback command is used to undo transactions that have not already been
saved to the database.
Syntax:
1. ROLLBACK;
Example:
c. SAVEPOINT: It is used to roll the transaction back to a certain point without rolling
back the entire transaction.
Syntax:
1. SAVEPOINT SAVEPOINT_NAME;
○ SELECT
a. SELECT: This is the same as the projection operation of relational algebra. It is used
to select the attribute based on the condition described by WHERE clause.
Syntax:
1. SELECT expressions
2. FROM TABLES
3. WHERE conditions;
For example:
1. SELECT emp_name
2. FROM employee
3. WHERE age > 20;
Constraints in SQL
Constraints in SQL means we are applying certain conditions or restrictions on the
database. This further means that before inserting data into the database, we are
checking for some conditions. If the condition we have applied to the database holds
true for the data which is to be inserted, then only the data will be inserted into the
database tables.
1. NOT NULL
2. UNIQUE
3. PRIMARY KEY
4. FOREIGN KEY
5. CHECK
6. DEFAULT
7. CREATE INDEX
1. NOT NULL
○ Whenever a table's column is declared as NOT NULL, then the value for that
column cannot be empty for any of the table's records.
○ There must exist a value in the column to which the NOT NULL constraint is
applied.
NOTE: NULL does not mean zero. NULL means empty column, not even zero.
○ The column with the unique constraint will always contain a unique value.
○ This constraint can be applied to one or more than one column of a table, which
means more than one unique constraint can exist on a single table.
○ Using the UNIQUE constraint, you can also modify the already created tables.
2. UNIQUE
○ Duplicate values are not allowed in the columns to which the UNIQUE constraint
is applied.
○ The column with the unique constraint will always contain a unique value.
○ This constraint can be applied to one or more than one column of a table, which
means more than one unique constraint can exist on a single table.
○ Using the UNIQUE constraint, you can also modify the already created tables.
Syntax to apply the UNIQUE constraint on a single column:
3. PRIMARY KEY
○ The column to which we have applied the primary constraint will always contain a
unique value and will not allow null values.
4. FOREIGN KEY
○ When we have two tables, and one table takes reference from another table, i.e.,
the same column is present in both the tables and that column acts as a primary
key in one table. That particular column will act as a foreign key in another table.
○ Whenever a check constraint is applied to the table's column, and the user wants
to insert the value in it, then the value will first be checked for certain conditions
before inserting the value into that column.
○ For example: if we have an age column in a table, then the user will insert any
value of his choice. The user will also enter even a negative value or any other
invalid value. But, if the user has applied check constraint on the age column with
the condition age greater than 18. Then in such cases, even if a user tries to
insert an invalid value such as zero or any other value less than 18, then the age
column will not accept that value and will not allow the user to insert it due to the
application of check constraint on the age column.
6. DEFAULT
Whenever a default constraint is applied to the table's column, and the user has not
specified the value to be inserted in it, then the default value which was specified while
applying the default constraint will be inserted into that particular column.
7. CREATE INDEX
CREATE INDEX constraint is used to create an index on the table. Indexes are not visible
to the user, but they help the user to speed up the searching speed or retrieval of data
from the database.
1. COUNT FUNCTION
○ 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.
○ 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 )
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 )
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 )
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 )
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 )
BUILT IN FUNCTION
Function Description
TRANSLATE Returns the string from the first argument after the
characters specified in the second argument are
translated into the characters specified in the third
argument.
UNICODE Returns the Unicode value for the first character of the
input expression
Numeric Functions
Function Description
Date Functions
Function Description
1. Union
2. UnionAll
3. Intersect
4. Minus
1. Union
Syntax
ID NAME
1 Jack
2 Harry
3 Jackson
ID NAME
3 Jackson
4 Stephan
5 David
ID NAME
1 Jack
2 Harry
3 Jackson
4 Stephan
5 David
2. Union All
Syntax:
ID NAME
1 Jack
2 Harry
3 Jackson
3 Jackson
4 Stephan
5 David
3. Intersect
Syntax
Example:
ID NAME
3 Jackson
4. Minus
Example
ID NAME
1 Jack
2 Harry
SQL Subquery
The Subquery or Inner query is an SQL query placed inside another SQL query. It is
embedded in the HAVING or WHERE clause of the SQL statements.
Following are the important rules which must be followed by the SQL Subquery:
1. The SQL subqueries can be used with the following statements along with the SQL
expression operators:
○ SELECT statement,
○ UPDATE statement,
○ DELETE statement.
2. The subqueries in SQL are always enclosed in the parenthesis and placed on the
right side of the SQL operators.
3. We cannot use the ORDER BY clause in the subquery. But, we can use the GROUP BY
clause, which performs the same function as the ORDER BY clause.
4. If the subquery returns more than one record, we have to use the multiple value
operators before the Subquery.
5. We can use the BETWEEN operator within the subquery but not with the subquery.
SQL group by
In SQL, The Group By statement is used for organizing similar data into groups. The
data is further organized with the help of equivalent function. It means, if different
rows in a precise column have the same values, it will arrange those rows in a group.
○ The SELECT statement is used with the GROUP BY clause in the SQL query.
Syntax:
1. SELECT column1, function_name(column2)
2. FROM table_name
3. WHERE condition
4. GROUP BY column1, column2
5. ORDER BY column1, column2;
6. function_name: Table name.
7. Condition: which we used.
○ Using the ORDER BY clause, we can sort the records in ascending or descending
order as per our requirement. The records will be sorted in ascending order
whenever the ASC keyword is used with ORDER by clause. DESC keyword will
sort the records in descending order.
○ If no keyword is specified after the column based on which we have to sort the
records, in that case, the sorting will be done by default in the ascending order.
Before writing the queries for sorting the records, let us understand the syntax.
Example 1: Let's take the following Employee table, which helps you to analyze the
HAVING clause with SUM aggregate function:
SUM(Emp_Salary) Emp_City
4000 Goa
9000 Delhi
8000 Jaipur
Now, suppose that you want to show those cities whose total salary of employees is
more than 5000. For this case, you have to type the following query with the HAVING
clause in SQL:
The output of the above SQL query shows the following table in the output:
SUM(Emp_Salary) Emp_City
9000 Delhi
8000 Jaipur
SQL JOIN
As the name shows, JOIN means to combine something. In case of SQL, JOIN means "to
combine two or more tables".
If you want to access more than one table through a select statement.
If you want to combine two or more table then SQL JOIN statement is used .it combines
rows of that tables in one table and one can retrieve the information by a SELECT
statement.
The joining of two or more tables is based on common field between them
● (INNER) JOIN: Returns records that have matching values in both tables
● LEFT (OUTER) JOIN: Returns all records from the left table, and the
matched records from the right table
● RIGHT (OUTER) JOIN: Returns all records from the right table, and the
matched records from the left table
● FULL (OUTER) JOIN: Returns all records when there is a match in either
left or right table
How to use SQL join or SQL Inner Join?
Let an example to deploy SQL JOIN process:
1.Staff table
2.Payment table
3 MONTY 25 2500
1 ARYAN 22 3000
4 AMIT 25 3500
1 ARYAN 22 3000
let us take two tables in this example to elaborate all the things:
CUSTOMER TABLE:
1 ARYAN 51 56000
2 AROHI 21 25000
3 VINEET 24 31000
4 AJEET 23 32000
5 RAVI 23 42000
ORDER TABLE:
let us take an example with 2 tables table1 is CUSTOMERS table and table2 is ORDERS
table.
CUSTOMER TABLE:
1 ARYAN 51 56000
2 AROHI 21 25000
3 VINEET 24 31000
4 AJEET 23 32000
5 RAVI 23 42000
ORDER TABLE:
Here we will join these two tables with SQL RIGHT JOIN:
SQL full outer join is used to combine the result of both left and right outer join and
returns all rows (don't care its matched or unmatched) from the both participating
tables.
1. SELECT *
2. FROM table1
3. FULL OUTER JOIN table2
4. ON table1.column_name = table2.column_name;
Note:here table1 and table2 are the name of the tables participating in joining and
column_name is the column of the participating tables.
A M
1 m
2 n
4 o
table_B
A N
2 p
3 q
5 r
Resulting table
A M A N
2 n 2 p
1 m - -
4 o - -
- - 3 q
- - 5 r
Because this is a full outer join so all rows (both matching and non-matching) from both
tables are included in the output. Here only one row of output displays values in all
columns because there is only one match between table_A and table_B.
The EXISTS operator returns TRUE if the subquery returns one or more records.
EXISTS Syntax
SELECT column_name(s)
FROM table_name
WHERE EXISTS
ANY means that the condition will be true if the operation is true for any of the
values in the range.
ANY Syntax
SELECT column_name(s)
FROM table_name
(SELECT column_name
FROM table_name
WHERE condition);
Note: The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or
<=).
ALL means that the condition will be true only if the operation is true for all
values in the range.
FROM table_name
WHERE condition;
SELECT column_name(s)
FROM table_name
(SELECT column_name
FROM table_name
WHERE condition);
Note: The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or
<=).
SQL Views
SQL CREATE VIEW Statement
In SQL, a view is a virtual table based on the result-set of an SQL statement.
A view contains rows and columns, just like a real table. The fields in a view are
fields from one or more real tables in the database.
You can add SQL statements and functions to a view and present the data as if
the data were coming from one single table.
A view is created with the CREATE VIEW statement.
FROM table_name
WHERE condition;
Note: A view always shows up-to-date data! The database engine recreates the view,
every time a user queries it.
FROM Customers
Example
The following SQL creates a view that selects every product in the "Products"
table with a price higher than the average price:
Example
FROM Products
Example
FROM table_name
WHERE condition;
The following SQL adds the "City" column to the "Brazil Customers" view:
Example
FROM Customers
Example
○ There are certain commands present in SQL known as TCL commands that help
the user manage the transactions that take place in a database.
○ COMMIT. ROLLBACK and SAVEPOINT are the most commonly used TCL
commands in SQL.
1. COMMIT
Syntax: COMMIT;
2. SAVEPOINT
We can divide the database operations into parts. For example, we can consider all the
insert related queries that we will execute consecutively as one part of the transaction
and the delete command as the other part of the transaction. Using the SAVEPOINT
command in SQL, we can save these different parts of the same transaction using
different names. For example, we can save all the insert related queries with the
savepoint named INS. To save all the insert related queries in one savepoint, we have to
execute the SAVEPOINT query followed by the savepoint name after finishing the insert
command execution.
Syntax:
1. SAVEPOINT savepoint_name;
3. ROLLBACK
While carrying a transaction, we must create savepoints to save different parts of the
transaction. According to the user's changing requirements, he/she can roll back the
transaction to different savepoints. Consider a scenario: We have initiated a transaction
followed by the table creation and record insertion into the table. After inserting records,
we have created a savepoint INS. Then we executed a delete query, but later we thought
that mistakenly we had removed the useful record. Therefore in such situations, we
have an option of rolling back our transaction. In this case, we have to roll back our
transaction using the ROLLBACK command to the savepoint INS, which we have created
before executing the DELETE query.
Syntax:
1. ROLLBACK TO savepoint_name;
This article explains everything about SQL Server cursor, such as cursor life cycle, why
and when the cursor is used, how to implement cursors, its limitations, and how we can
replace a cursor.
1: Declare Cursor
The first step is to declare the cursor using the below SQL statement:
We can declare a cursor by specifying its name with the data type CURSOR after the
DECLARE keyword. Then, we will write the SELECT statement that defines the output for
the cursor.
2: Open Cursor
It's a second step in which we open the cursor to store data retrieved from the result set.
We can do this by using the below SQL statement:
1. OPEN cursor_name;
3: Fetch Cursor
It's a third step in which rows can be fetched one by one or in a block to do data
manipulation like insert, update, and delete operations on the currently active row in the
cursor. We can do this by using the below SQL statement:
We can also use the @@FETCHSTATUS function in SQL Server to get the status of the
most recent FETCH statement cursor that was executed against the cursor. The FETCH
statement was successful when the @@FETCHSTATUS gives zero output. The WHILE
statement can be used to retrieve all records from the cursor. The following code
explains it more clearly:
1. WHILE @@FETCH_STATUS = 0
2. BEGIN
3. FETCH NEXT FROM cursor_name;
4. END;
4: Close Cursor
It's a fourth step in which the cursor should be closed after we finished work with a
cursor. We can do this by using the below SQL statement:
1. CLOSE cursor_name;
5: Deallocate Cursor
It is the fifth and final step in which we will erase the cursor definition and release all the
system resources associated with the cursor. We can do this by using the below SQL
statement:
1. DEALLOCATE cursor_name;
Sometimes the application needs to process the rows in a singleton fashion, i.e., on row
by row basis rather than the entire result set at once. We can do this process by using
cursors in SQL Server. Before using the cursor, we must know that cursors are very bad
in performance, so it should always use only when there is no option except the cursor.
The cursor uses the same technique as we use loops like FOREACH, FOR, WHILE, DO
WHILE to iterate one object at a time in all programming languages. Hence, it could be
chosen because it applies the same logic as the programming language's looping
process.
○ Static Cursors
○ Dynamic Cursors
○ Forward-Only Cursors
○ Keyset Cursors
○ Keyset Cursors
Static Cursors
The result set shown by the static cursor is always the same as when the cursor was
first opened. Since the static cursor will store the result in tempdb, they are always
read-only. We can use the static cursor to move both forward and backward. In contrast
to other cursors, it is slower and consumes more memory. As a result, we can use it
only when scrolling is necessary, and other cursors aren't suitable.
This cursor shows rows that were removed from the database after it was opened. A
static cursor does not represent any INSERT, UPDATE, or DELETE operations (unless the
cursor is closed and reopened).
Dynamic Cursors
The dynamic cursors are opposite to the static cursors that allow us to perform the data
updation, deletion, and insertion operations while the cursor is open. It is scrollable by
default. It can detect all changes made to the rows, order, and values in the result set,
whether the changes occur inside the cursor or outside the cursor. Outside the cursor,
we cannot see the updates until they are committed.
Forward-Only Cursors
It is the default and fastest cursor type among all cursors. It is called a forward-only
cursor because it moves only forward through the result set. This cursor doesn't
support scrolling. It can only retrieve rows from the beginning to the end of the result
set. It allows us to perform insert, update, and delete operations. Here, the effect of
insert, update and delete operations made by the user that affect rows in the result set
are visible as the rows are fetched from the cursor. When the row was fetched, we
cannot see the changes made to rows through the cursor.
1. Forward_Only Keyset
2. Forward_Only Static
3. Fast_Forward
Keyset Driven Cursors
This cursor functionality lies between a static and a dynamic cursor regarding its ability
to detect changes. It can't always detect changes in the result set's membership and
order like a static cursor. It can detect changes in the result set's rows values as like a
dynamic cursor. It can only move from the first to last and last to the first row. The
order and the membership are fixed whenever this cursor is opened.
It is operated by a set of unique identifiers the same as the keys in the keyset. The
keyset is determined by all rows that qualified the SELECT statement when the cursor
was first opened. It can also detect any changes to the data source, which supports
update and delete operations. It is scrollable by default.
Implementation of Example
Let us implement the cursor example in the SQL server. We can do this by first creating
a table named "customer" using the below statement:
1. CREATE TABLE customer (
2. id int PRIMARY KEY,
3. c_name nvarchar(45) NOT NULL,
4. email nvarchar(45) NOT NULL,
5. city nvarchar(25) NOT NULL
6. );
Next, we will insert values into the table. We can execute the below statement to add
data into a table:
After executing the query, we can see the below output where we have eight rows into
the table:
Now, we will create a cursor to display the customer records. The below code snippets
explain the all steps of the cursor declaration or creation by putting everything together:
○ It imposes locks on a portion of the table or the entire table when processing
data.
○ The cursor's performance and speed are slower because they update table
records one row at a time.
○ Cursors are quicker than while loops, but they do have more overhead.
○ The number of rows and columns brought into the cursor is another aspect that
affects cursor speed. It refers to how much time it takes to open your cursor and
execute a fetch statement.
SQL Server builds an execution plan when the stored procedure is called the first time
and stores them in the cache memory. The plan is reused by SQL Server in subsequent
executions of the stored procedure, allowing it to run quickly and efficiently.
○ T-SQL Stored Procedures: Transact-SQL procedures are one of the most popular
types of SQL Server procedures. It takes parameters and returns them. These
procedures handle INSERT, UPDATE, and DELETE statements with or without
parameters and output row data.
○ CLR Stored Procedures: The SQL Server procedures are a group of SQL
commands, and the CLR indicates the common language runtime. CLR stored
procedures are made up of the CLR and a stored procedure, which is written in a
CLR-based language like VB.NET or C#. CLR procedures are .Net objects that run
in the SQL Server database's memory.
The server's administrative tasks depend primarily on system stored procedures. When
SQL Server is installed, it creates system procedures. The system stored procedures
prevent the administrator from querying or modifying the system and database catalog
tables directly. Developers often ignore system stored procedures.
SQL Server Stored Procedures Syntax
The following are the basic syntax to create stored procedures in SQL Server:
Parameter Explanations
Stored Function
A Stored Function is a defined function that is called from within an SQL statement like a regular
function, and returns a single value.
DELIMITER //
//
DELIMITER ;
First, the delimiter is changed, since the function definition will contain the regular semicolon
delimiter. See Delimiters in the mariadb client for more. Then the function is named FortyTwo and
defined to return a tinyin. The DETERMINISTIC keyword is not necessary in all cases (although if
binary logging is on, leaving it out will throw an error), and is to help the query optimizer choose a
query plan. A deterministic function is one that, given the same arguments, will always return the
same result.
Next, the function body is placed between BEGIN and END statements. It declares a tinyint, X, which
is simply set to 42, and this is the result returned.
SELECT FortyTwo();
+------------+
| FortyTwo() |
+------------+
| 42 |
+------------+
Of course, a function that doesn't take any arguments is of little use. Here's a more complex
example:
DELIMITER //
CREATE FUNCTION VatCents(price DECIMAL(10,2)) RETURNS INT DETERMINISTIC
BEGIN
DECLARE x INT;
SET x = price * 114;
RETURN x;
END //
Query OK, 0 rows affected (0.04 sec)
DELIMITER ;
This function takes an argument, price which is defined as a DECIMAL, and returns an INT.
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.
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 can verify the insert operation by using the SELECT statement. We will get the below
output:
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.
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.
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.
○ After Triggers
○ 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 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.
The following is an illustration of the Instead of Triggers syntax in SQL Server:
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.
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:
If we want to remove more than one trigger at once, we must separate the trigger using
the comma operator:
We can use the DROP TRIGGER statement in the below format to delete one or more
DDL triggers: