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

unit 2 sql

SQL, or Structured Query Language, is a database language used for managing and manipulating structured data in relational database management systems. It allows users to perform various operations such as creating, updating, and querying databases, and it is standardized by ANSI and ISO. SQL has advantages like high-speed query processing and ease of use, but also has disadvantages such as high costs and complex interfaces.

Uploaded by

1gurugantaal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

unit 2 sql

SQL, or Structured Query Language, is a database language used for managing and manipulating structured data in relational database management systems. It allows users to perform various operations such as creating, updating, and querying databases, and it is standardized by ANSI and ISO. SQL has advantages like high-speed query processing and ease of use, but also has disadvantages such as high costs and complex interfaces.

Uploaded by

1gurugantaal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

What is SQL

SQL is a short-form of the structured query language, and it is pronounced as S-Q-L or


sometimes as See-Quell.

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 also helps them to describe the structured data.

○ 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

○ Classic Query Engine

○ SQL Query Engine, etc.

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.

2. High-Speed Query Processing

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.

6. More than one Data View

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.

3. Partial Database control

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.

Types of SQL Commands


There are five types of SQL commands: DDL, DML, DCL, TCL, and DQL.
1. Data Definition Language (DDL)

○ 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.

Here are some commands that come under DDL:

○ CREATE

○ ALTER

○ DROP

○ TRUNCATE

a. CREATE It is used to create a new table in the database.


Syntax:

1. CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);

Example:

1. CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(100), DOB


DATE);

b. DROP: It is used to delete both the structure and record stored in the table.

Syntax

1. DROP TABLE table_name;

Example

1. DROP TABLE EMPLOYEE;

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:

To add a new column in the table

1. ALTER TABLE table_name ADD column_name COLUMN-definition;

To modify existing column in the table:

1. ALTER TABLE table_name MODIFY(column_definitions....);

EXAMPLE

1. ALTER TABLE STU_DETAILS ADD(ADDRESS VARCHAR2(20));


2. ALTER TABLE STU_DETAILS MODIFY (NAME VARCHAR2(20));

d. TRUNCATE: It is used to delete all the rows from the table and free the space
containing the table.
Syntax:

1. TRUNCATE TABLE table_name;

Example:

1. TRUNCATE TABLE EMPLOYEE;

2. Data Manipulation Language

○ DML commands are used to modify the database. It is responsible for all form of
changes in the database.

○ The command of DML is not auto-committed that means it can't permanently


save all the changes in the database. They can be rollback.

Here are some commands that come under DML:

○ 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:

1. INSERT INTO TABLE_NAME


2. (col1, col2, col3,.... col N)
3. VALUES (value1, value2, value3, .... valueN);
4. NSERT INTO TABLE_NAME
5. VALUES (value1, value2, value3, .... valueN);

For example:

1. INSERT INTO javatpoint (Author, Subject) VALUES ("Sonoo", "DBMS");


b. UPDATE: This command is used to update or modify the value of a column in the
table.

Syntax:

1. UPDATE table_name SET [column_name1= value1,...column_nameN = valueN]


[WHERE CONDITION]

For example:

1. UPDATE students
2. SET User_Name = 'Sonoo'
3. WHERE Student_Id = '3'

c. DELETE: It is used to remove one or more row from a table.

Syntax:

1. DELETE FROM table_name [WHERE condition];

For example:

1. DELETE FROM javatpoint


2. WHERE Author="Sonoo";

3. Data Control Language

DCL commands are used to grant and take back authority from any database user.

Here are some commands that come under DCL:

○ Grant

○ Revoke

a. Grant: It is used to give user access privileges to a database.

Example
1. GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;

b. Revoke: It is used to take back permissions from the user.

Example

1. REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;

4. Transaction Control Language

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.

Here are some commands that come under TCL:

○ COMMIT

○ ROLLBACK

○ SAVEPOINT

a. Commit: Commit command is used to save all the transactions to the database.

Syntax:

1. COMMIT;

Example:

1. DELETE FROM CUSTOMERS


2. WHERE AGE = 25;
3. COMMIT;

b. Rollback: Rollback command is used to undo transactions that have not already been
saved to the database.

Syntax:
1. ROLLBACK;

Example:

1. DELETE FROM CUSTOMERS


2. WHERE AGE = 25;
3. ROLLBACK;

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;

5. Data Query Language

DQL is used to fetch the data from the database.

It uses only one command:

○ 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.

Constraints in SQL can be categorized into two types:

1. Column Level Constraint:


Column Level Constraint is used to apply a constraint on a single column.

2. Table Level Constraint:


Table Level Constraint is used to apply a constraint on multiple columns.

Constraints available in SQL are:

1. NOT NULL

2. UNIQUE

3. PRIMARY KEY

4. FOREIGN KEY

5. CHECK

6. DEFAULT

7. CREATE INDEX

1. NOT NULL

○ NULL means empty, i.e., the value is not available.

○ 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.

Syntax to apply the NOT NULL constraint during table creation:

1. CREATE TABLE TableName (ColumnName1 datatype NOT NULL, ColumnName2

datatype,…., ColumnNameN datatype); 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:

1. CREATE TABLE TableName (ColumnName1 datatype UNIQUE, ColumnName2


datatype,…., ColumnNam

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:

1. CREATE TABLE TableName (ColumnName1 datatype UNIQUE, ColumnName2


datatype,…., ColumnNam

3. PRIMARY KEY

○ PRIMARY KEY Constraint is a combination of NOT NULL and Unique constraints.

○ NOT NULL constraint and a UNIQUE constraint together forms a PRIMARY


constraint.

○ The column to which we have applied the primary constraint will always contain a
unique value and will not allow null values.

Syntax of primary key constraint during table creation:

1. CREATE TABLE TableName (ColumnName1 datatype PRIMARY KEY,


ColumnName2 datatype,…., Colu

4. FOREIGN KEY

○ A foreign key is used for referential integrity.

○ 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.

Syntax to apply a foreign key constraint during table creation:

1. CREATE TABLE tablename(ColumnName1 Datatype(SIZE) PRIMARY KEY,


ColumnNameN Datatype(SIZE), FOREIGN KEY( ColumnName ) REFERENCES
PARENT_TABLE_NAME(Primary_Key_ColumnName));
5. CHECK

○ 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.

Syntax to apply check constraint on a single column:

1. CREATE TABLE TableName (ColumnName1 datatype CHECK (ColumnName1


Condition), ColumnName2

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.

Syntax to apply default constraint during table creation:

1. CREATE TABLE TableName (ColumnName1 datatype DEFAULT Value,


ColumnName2 datatype,…., Colum

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.

Syntax to create an index on single column:

1. CREATE INDEX IndexName ON TableName (ColumnName 1);

SQL Aggregate Functions


○ SQL aggregation function is used to perform the calculations on multiple rows of
a single column of a table. It returns a single value.

○ It is also used to summarize the data.

Types of SQL Aggregation Function

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

SQL Server has many built-in functions.

This reference contains string, numeric, date, conversion, and some


advanced functions in SQL Server.
String Functions

Function Description

ASCII Returns the ASCII value for the specific character

CHAR Returns the character based on the ASCII code

CHARINDEX Returns the position of a substring in a string

CONCAT Adds two or more strings together

Concat with + Adds two or more strings together

CONCAT_WS Adds two or more strings together with a separator

DATALENGTH Returns the number of bytes used to represent an


expression
DIFFERENCE Compares two SOUNDEX values, and returns an integer
value

FORMAT Formats a value with the specified format

LEFT Extracts a number of characters from a string (starting


from left)

LEN Returns the length of a string

LOWER Converts a string to lower-case

LTRIM Removes leading spaces from a string

NCHAR Returns the Unicode character based on the number


code

PATINDEX Returns the position of a pattern in a string


QUOTENAME Returns a Unicode string with delimiters added to make
the string a valid SQL Server delimited identifier

REPLACE Replaces all occurrences of a substring within a string,


with a new substring

REPLICATE Repeats a string a specified number of times

REVERSE Reverses a string and returns the result

RIGHT Extracts a number of characters from a string (starting


from right)

RTRIM Removes trailing spaces from a string

SOUNDEX Returns a four-character code to evaluate the similarity


of two strings

SPACE Returns a string of the specified number of space


characters
STR Returns a number as string

STUFF Deletes a part of a string and then inserts another part


into the string, starting at a specified position

SUBSTRING Extracts some characters from a string

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.

TRIM Removes leading and trailing spaces (or other specified


characters) from a string

UNICODE Returns the Unicode value for the first character of the
input expression

UPPER Converts a string to upper-case

Numeric Functions
Function Description

ABS Returns the absolute value of a number

ACOS Returns the arc cosine of a number

ASIN Returns the arc sine of a number

ATAN Returns the arc tangent of a number

ATN2 Returns the arc tangent of two numbers

AVG Returns the average value of an expression

CEILING Returns the smallest integer value that is >= a


number

COUNT Returns the number of records returned by a


select query
COS Returns the cosine of a number

COT Returns the cotangent of a number

DEGREES Converts a value in radians to degrees

EXP Returns e raised to the power of a specified


number

FLOOR Returns the largest integer value that is <= to a


number

LOG Returns the natural logarithm of a number, or the


logarithm of a number to a specified base

LOG10 Returns the natural logarithm of a number to


base 10

MAX Returns the maximum value in a set of values


MIN Returns the minimum value in a set of values

PI Returns the value of PI

POWER Returns the value of a number raised to the


power of another number

RADIANS Converts a degree value into radians

RAND Returns a random number

ROUND Rounds a number to a specified number of


decimal places

SIGN Returns the sign of a number

SIN Returns the sine of a number

SQRT Returns the square root of a number


SQUARE Returns the square of a number

SUM Calculates the sum of a set of values

TAN Returns the tangent of a number

Date Functions

Function Description

CURRENT_TIMES Returns the current date and time


TAMP

DATEADD Adds a time/date interval to a date and then


returns the date

DATEDIFF Returns the difference between two dates


DATEFROMPART Returns a date from the specified parts (year,
S month, and day values)

DATENAME Returns a specified part of a date (as string)

DATEPART Returns a specified part of a date (as integer)

DAY Returns the day of the month for a specified date

GETDATE Returns the current database system date and


time

GETUTCDATE Returns the current database system UTC date


and time

ISDATE Checks an expression and returns 1 if it is a valid


date, otherwise 0

MONTH Returns the month part for a specified date (a


number from 1 to 12)
SYSDATETIME Returns the date and time of the SQL Server

YEAR Returns the year part for a specified date

SQL Set Operation


The SQL Set operation is used to combine the two or more
SQL SELECT statements.

Types of Set Operation

1. Union

2. UnionAll

3. Intersect

4. Minus
1. Union

○ The SQL Union operation is used to combine the


result of two or more SQL SELECT queries.

○ In the union operation, all the number of datatype and


columns must be same in both the tables on which
UNION operation is being applied.

○ The union operation eliminates the duplicate rows


from its resultset.

Syntax

1. SELECT column_name FROM table1


2. UNION
3. SELECT column_name FROM table2;
Example:

The First table

ID NAME

1 Jack

2 Harry

3 Jackson

The Second table

ID NAME

3 Jackson

4 Stephan
5 David

Union SQL query will be:

1. SELECT * FROM First


2. UNION
3. SELECT * FROM Second;

The resultset table will look like:

ID NAME

1 Jack

2 Harry

3 Jackson

4 Stephan
5 David

2. Union All

Union All operation is equal to the Union operation. It


returns the set without removing duplication and sorting the
data.

Syntax:

1. SELECT column_name FROM table1


2. UNION ALL
3. SELECT column_name FROM table2;

Example: Using the above First and Second table.

Union All query will be like:

1. SELECT * FROM First


2. UNION ALL
3. SELECT * FROM Second;

The resultset table will look like:

ID NAME

1 Jack
2 Harry

3 Jackson

3 Jackson

4 Stephan

5 David

3. Intersect

○ It is used to combine two SELECT statements. The


Intersect operation returns the common rows from
both the SELECT statements.

○ In the Intersect operation, the number of datatype


and columns must be the same.

○ It has no duplicates and it arranges the data in


ascending order by default.

Syntax

1. SELECT column_name FROM table1


2. INTERSECT
3. SELECT column_name FROM table2;

Example:

Using the above First and Second table.

Intersect query will be:

1. SELECT * FROM First


2. INTERSECT
3. SELECT * FROM Second;

The resultset table will look like:

ID NAME

3 Jackson

4. Minus

○ It combines the result of two SELECT statements.


Minus operator is used to display the rows which are
present in the first query but absent in the second
query.

○ It has no duplicates and data arranged in ascending


order by default.
Syntax:

1. SELECT column_name FROM table1


2. MINUS
3. SELECT column_name FROM table2;

Example

Using the above First and Second table.

Minus query will be:

1. SELECT * FROM First


2. MINUS
3. SELECT * FROM Second;

The resultset table will look like:

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,

○ INSERT statement, and

○ 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.

Subquery with SELECT statement


In SQL, inner queries or nested queries are used most frequently with the SELECT
statement. The syntax of Subquery with the SELECT statement is described in the
following block:
1. SELECT Column_Name1, Column_Name2, ...., Column_NameN
2. FROM Table_Name WHERE Column_Name Comparison_Operator
3. ( SELECT Column_Name1, Column_Name2, ...., Column_NameN
4. FROM Table_Name WHERE condition;

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.

○ WHERE clause is placed before the GROUP BY clause in SQL.

○ ORDER BY clause is placed after the GROUP BY clause in SQL.

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.

SQL ORDER BY Clause


○ Whenever we want to sort the records based on the columns stored in the tables
of the SQL database, then we consider using the ORDER BY clause in SQL.
○ The ORDER BY clause in SQL will help us to sort the records based on the
specific column of a table. This means that all the values stored in the column
on which we are applying ORDER BY clause will be sorted, and the
corresponding column values will be displayed in the sequence in which we
have obtained the values in the earlier step.

○ 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.

Syntax to sort the records in ascending order:


1. SELECT ColumnName1,...,ColumnNameN FROM TableName ORDER BY
ColumnName ASC;

Syntax to sort the records in descending order:


1. SELECT ColumnName1,...,ColumnNameN FROM TableName ORDER BY
ColumnNameDESC;

Syntax to sort the records in ascending order without using ASC


keyword:
1. SELECT ColumnName1,...,ColumnNameN FROM TableName ORDER BY
ColumnName
HAVING Clause in SQL
The HAVING clause places the condition in the groups defined by the GROUP BY
clause in the SELECT statement.

Syntax of HAVING clause in SQL


1. SELECT column_Name1, column_Name2, ....., column_NameN
aggregate_function_name(column_Name) FROM table_name GROUP BY
column_Name1 HAVING condition;

Example 1: Let's take the following Employee table, which helps you to analyze the
HAVING clause with SUM aggregate function:

Emp_Id Emp_Name Emp_Salary Emp_City

201 Abhay 2000 Goa

202 Ankit 4000 Delhi

203 Bheem 8000 Jaipur

204 Ram 2000 Goa

205 Sumit 5000 Delhi


If you want to add the salary of employees for each city, you have to write the following
query:

1. SELECT SUM(Emp_Salary), Emp_City FROM Employee GROUP BY Emp_City;

The output of the above query shows the following output:

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:

1. SELECT SUM(Emp_Salary), Emp_City FROM Employee GROUP BY Emp_City


HAVING SUM(Emp_Salary)>5000;

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

Different Types of SQL JOINs


Here are the different types of the JOINs in SQL:

● (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

ID Staff_NAME Staff_AGE STAFF_ADDRESS Monthley_Package

1 ARYAN 22 MUMBAI 18000

2 SUSHIL 32 DELHI 20000

3 MONTY 25 MOHALI 22000


4 AMIT 20 ALLAHABAD 12000

2.Payment table

Payment_ID DATE Staff_ID AMOUNT

101 30/12/2009 1 3000.00

102 22/02/2010 3 2500.00

103 23/02/2010 4 3500.00

So if you follow this JOIN statement to join these two tables ?

1. SELECT Staff_ID, Staff_NAME, Staff_AGE, AMOUNT


2. FROM STAFF s, PAYMENT p
3. WHERE s.ID =p.STAFF_ID;

This will produce the result like this:

STAFF_ID NAME Staff_AGE AMOUNT

3 MONTY 25 2500
1 ARYAN 22 3000

4 AMIT 25 3500

1 ARYAN 22 3000

SQL LEFT JOIN


The SQL left join returns all the values from the left table and it also includes matching
values from right table, if there are no matching join value it returns NULL.

BASIC SYNTAX FOR LEFT JOIN:

1. SELECT table1.column1, table2.column2....


2. FROM table1
3. LEFTJOIN table2
4. ON table1.column_field = table2.column_field;

let us take two tables in this example to elaborate all the things:

CUSTOMER TABLE:

ID NAME AGE SALARY

1 ARYAN 51 56000

2 AROHI 21 25000
3 VINEET 24 31000

4 AJEET 23 32000

5 RAVI 23 42000

This is second table

ORDER TABLE:

O_ID DATE CUSTOMER_ID AMOUNT

001 20-01-2012 2 3000

002 12-02-2012 2 2000

003 22-03-2012 3 4000

004 11-04-2012 4 5000

join these two tables with LEFT JOIN:

1. SQL SELECT ID, NAME, AMOUNT,DATE


2. FROM CUSTOMER
3. LEFT JOIN ORDER
4. ON CUSTOMER.ID = ORDER.CUSTOMER_ID;

This will produce the following result:

ID NAME AMOUNT DATE

1 ARYAN NULL NULL


2 AROHI 3000 20-01-2012

2 AROHI 2000 12-02-2012

3 VINEET 4000 22-03-2012

4 AJEET 5000 11-04-2012

5 RAVI NULL NULL

SQL RIGHT JOIN


The SQL right join returns all the values from the rows of right table. It also includes the
matched values from left table but if there is no matching in both tables, it returns NULL.

Basic syntax for right join:

1. SELECT table1.column1, table2.column2.....


2. FROM table1
3. RIGHT JOIN table2
4. ON table1.column_field = table2.column_field;

let us take an example with 2 tables table1 is CUSTOMERS table and table2 is ORDERS
table.

CUSTOMER TABLE:

ID NAME AGE SALARY

1 ARYAN 51 56000

2 AROHI 21 25000

3 VINEET 24 31000
4 AJEET 23 32000

5 RAVI 23 42000

and this is the second table:

ORDER TABLE:

DATE O_ID CUSTOMER_ID AMOUNT

20-01-2012 001 2 3000

12-02-2012 002 2 2000

22-03-2012 003 3 4000

11-04-2012 004 4 5000

Here we will join these two tables with SQL RIGHT JOIN:

1. SQL> SELECT ID,NAME,AMOUNT,DATE


2. FROM CUSTOMER
3. RIGHT JOIN ORDER
4. ON CUSTOMER.ID = ORDER.CUSTOMER_ID;

ID NAME AMOUNT DATE

2 AROHI 3000 20-01-2012

2 AROHI 2000 12-02-2012

3 VINEET 4000 22-03-2012


4 AJEET 5000 11-04-2012

SQL FULL JOIN


The SQL full join is the result of combination of both left and right outer join and the join
tables have all the records from both tables. It puts NULL on the place of matches not
found.

SQL full outer join:


What is SQL full outer 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.

Syntax for full outer join:

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.

Let us take two tables to demonstrate full outer join:


table_A

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.

SQL EXISTS Operator

The SQL EXISTS Operator


The EXISTS operator is used to test for the existence of any record in a
subquery.

The EXISTS operator returns TRUE if the subquery returns one or more records.
EXISTS Syntax

SELECT column_name(s)

FROM table_name

WHERE EXISTS

(SELECT column_name FROM table_name WHERE condition);

The SQL ANY and ALL Operators


The ANY and ALL operators allow you to perform a comparison between a single
column value and a range of other values.

The SQL ANY Operator


The ANY operator:

● returns a boolean value as a result


● returns TRUE if ANY of the subquery values meet the condition

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

WHERE column_name operator ANY

(SELECT column_name

FROM table_name

WHERE condition);

Note: The operator must be a standard comparison operator (=, <>, !=, >, >=, <, or
<=).

The SQL ALL Operator


The ALL operator:

● returns a boolean value as a result


● returns TRUE if ALL of the subquery values meet the condition
● is used with SELECT, WHERE and HAVING statements

ALL means that the condition will be true only if the operation is true for all
values in the range.

ALL Syntax With SELECT

SELECT ALL column_name(s)

FROM table_name
WHERE condition;

ALL Syntax With WHERE or HAVING

SELECT column_name(s)

FROM table_name

WHERE column_name operator ALL

(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.

CREATE VIEW Syntax

CREATE VIEW view_name AS

SELECT column1, column2, ...

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.

SQL CREATE VIEW Examples


The following SQL creates a view that shows all customers from Brazil:

CREATE VIEW [Brazil Customers] AS

SELECT CustomerName, ContactName

FROM Customers

WHERE Country = 'Brazil';


We can query the view above as follows:

Example

SELECT * FROM [Brazil Customers];

The following SQL creates a view that selects every product in the "Products"
table with a price higher than the average price:

Example

CREATE VIEW [Products Above Average Price] AS

SELECT ProductName, Price

FROM Products

WHERE Price > (SELECT AVG(Price) FROM Products);

We can query the view above as follows:

Example

SELECT * FROM [Products Above Average Price];

SQL Updating a View


A view can be updated with the CREATE OR REPLACE VIEW statement.

SQL CREATE OR REPLACE VIEW Syntax

CREATE OR REPLACE VIEW view_name AS

SELECT column1, column2, ...

FROM table_name

WHERE condition;

The following SQL adds the "City" column to the "Brazil Customers" view:

Example

CREATE OR REPLACE VIEW [Brazil Customers] AS

SELECT CustomerName, ContactName, City

FROM Customers

WHERE Country = 'Brazil';

SQL Dropping a View


A view is deleted with the DROP VIEW statement.
SQL DROP VIEW Syntax

DROP VIEW view_name;

The following SQL drops the "Brazil Customers" view:

Example

DROP VIEW [Brazil Customers];

TCL Commands in SQL


○ In SQL, TCL stands for Transaction control language.

○ A single unit of work in a database is formed after the consecutive execution of


commands is known as a transaction.

○ 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

COMMIT command in SQL is used to save all the transaction-related changes


permanently to the disk. Whenever DDL commands such as INSERT, UPDATE and
DELETE are used, the changes made by these commands are permanent only after
closing the current session. So before closing the session, one can easily roll back the
changes made by the DDL commands. Hence, if we want the changes to be saved
permanently to the disk without closing the session, we will use the commit command.

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;

Cursor in SQL Server


A cursor in SQL Server is a database object that allows us to retrieve each row at a time
and manipulate its data. A cursor is nothing more than a pointer to a row. It's always
used in conjunction with a SELECT statement. It is usually a collection of SQL logic that
loops through a predetermined number of rows one by one. A simple illustration of the
cursor is when we have an extensive database of worker's records and want to calculate
each worker's salary after deducting taxes and leaves.
The SQL Server cursor's purpose is to update the data row by row, change it, or perform
calculations that are not possible when we retrieve all records at once. It's also useful
for performing administrative tasks like SQL Server database backups in sequential
order. Cursors are mainly used in the development, DBA, and ETL processes.

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.

Life Cycle of the cursor


We can describe the life cycle of a cursor into the five different sections as follows:

1: Declare Cursor

The first step is to declare the cursor using the below SQL statement:

1. DECLARE cursor_name CURSOR


2. FOR select_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:

1. FETCH NEXT FROM cursor INTO variable_list;

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;

Uses of SQL Server Cursor


We know that relational database management systems, including SQL Server, are
excellent in handling data on a set of rows called result sets. For example, we have a
table product_table that contains the product descriptions. If we want to update the
price of the product, then the below 'UPDATE' query will update all records that match
the condition in the 'WHERE' clause:

1. UPDATE product_table SET unit_price = 100 WHERE product_id = 105;

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.

Types of Cursors in SQL Server


The following are the different types of cursors in SQL Server listed below:

○ 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.

The Forward-Only cursors are three categorize into three types:

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:

1. INSERT INTO customer (id, c_name, email, city)


2. VALUES (1,'Steffen', '[email protected]', 'Texas'),
3. (2, 'Joseph', '[email protected]', 'Alaska'),
4. (3, 'Peter', '[email protected]', 'California'),
5. (4,'Donald', '[email protected]', 'New York'),
6. (5, 'Kevin', '[email protected]', 'Florida'),
7. (6, 'Marielia', '[email protected]', 'Arizona'),
8. (7,'Antonio', '[email protected]', 'New York'),
9. (8, 'Diego', '[email protected]', 'California');

We can verify the data by executing the SELECT statement:

1. SELECT * FROM customer;

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:

1. --Declare the variables for holding data.


2. DECLARE @id INT, @c_name NVARCHAR(50), @city NVARCHAR(50)
3.
4. --Declare and set counter.
5. DECLARE @Counter INT
6. SET @Counter = 1
7.
8. --Declare a cursor
9. DECLARE PrintCustomers CURSOR
10. FOR
11. SELECT id, c_name, city FROM customer
12.
13. --Open cursor
14. OPEN PrintCustomers
15.
16. --Fetch the record into the variables.
17. FETCH NEXT FROM PrintCustomers INTO
18. @id, @c_name, @city
19.
20. --LOOP UNTIL RECORDS ARE AVAILABLE.
21. WHILE @@FETCH_STATUS = 0
22. BEGIN
23. IF @Counter = 1
24. BEGIN
25. PRINT 'id' + CHAR(9) + 'c_name' + CHAR(9) + CHAR(9) + 'city'
26. PRINT '--------------------------'
27. END
28.
29. --Print the current record
30. PRINT CAST(@id AS NVARCHAR(10)) + CHAR(9) + @c_name + CHAR(9) +
CHAR(9) + @city
31.
32. --Increment the counter variable
33. SET @Counter = @Counter + 1
34.
35. --Fetch the next record into the variables.
36. FETCH NEXT FROM PrintCustomers INTO
37. @id, @c_name, @city
38. END
39.
40. --Close the cursor
41. CLOSE PrintCustomers
42.
43. --Deallocate the cursor
44. DEALLOCATE PrintCustomers

After executing a cursor, we will get the below output:


Limitations of SQL Server Cursor
A cursor has some limitations so that it should always use only when there is no option
except the cursor. These limitations are:

○ Cursor consumes network resources by requiring a network roundtrip each time


it fetches a record.

○ A cursor is a memory resident set of pointers, which means it takes some


memory that other processes could use on our machine.

○ 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.

Stored Procedure in SQL Server


stored procedure is a group of one or more pre-compiled SQL statements into a logical
unit. It is stored as an object inside the database server. It is a subroutine or a
subprogram in the common computing language that has been created and stored in
the database. Each procedure in SQL Server always contains a name, parameter lists,
and Transact-SQL statements. The SQL Database Server stores the stored procedures
as named objects. We can invoke the procedures by using triggers, other procedures,
and applications such as Java, Python, PHP, etc. It can support almost all relational
database systems.

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.

Features of Stored Procedures in SQL Server


The following are the features of stored procedure in SQL Server:

○ Reduced Traffic: A stored procedure reduces network traffic between the


application and the database server, resulting in increased performance. It is
because instead of sending several SQL statements, the application only needs
to send the name of the stored procedure and its parameters.

○ Stronger Security: The procedure is always secure because it manages which


processes and activities we can perform. It removes the need for permissions to
be granted at the database object level and simplifies the security layers.

○ Reusable: Stored procedures are reusable. It reduces code inconsistency,


prevents unnecessary rewrites of the same code, and makes the code
transparent to all applications or users.

○ Easy Maintenance: The procedures are easier to maintain without restarting or


deploying the application.

○ Improved Performance: Stored Procedure increases the application


performance. Once we create the stored procedures and compile them the first
time, it creates an execution plan reused for subsequent executions. The
procedure is usually processed quicker because the query processor does not
have to create a new plan.
Types of Stored Procedures
SQL Server categorizes the stored procedures mainly in two types:

1. User-defined Stored Procedures

2. System Stored Procedures

User-defined Stored Procedures

Database developers or database administrators build user-defined stored procedures.


These procedures provide one or more SQL statements for selecting, updating, or
removing data from database tables. A stored procedure specified by the user accepts
input parameters and returns output parameters. DDL and DML commands are used
together in a user-defined procedure.

We can further divide this procedure into two types:

○ 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.

System Stored Procedures

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:

1. CREATE PROCEDURE [schema_name].procedure_name


2. @parameter_name data_type,
3. ....
4. parameter_name data_type
5. AS
6. BEGIN
7. -- SQL statements
8. -- SELECT, INSERT, UPDATE, or DELETE statement
9. END

Parameter Explanations

The stored procedure syntax has the following parameters:

Schema_name: It is the name of your database or schema. By default, a procedure is


associated with the current database, but we can also create it into another database by
specifying the DB name.

Procedure_Name: It represents the name of your stored procedure that should be


meaningful names so that you can identify them quickly. It cannot be the system
reserved keywords.

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.

Creating Stored Functions


Here's a skeleton example to see a stored function in action:

DELIMITER //

CREATE FUNCTION FortyTwo() RETURNS TINYINT DETERMINISTIC


BEGIN
DECLARE x TINYINT;
SET x = 42;
RETURN x;
END

//

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.

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:

○ We cannot manually execute/invoked triggers.

○ Triggers have no chance of receiving parameters.

○ 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 VARCHAR(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:

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:

○ When we need to prevent the database schema from changing

○ When we need to audit changes made in the database schema

○ When we need to respond to a change made in the database schema

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:

○ 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.

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.

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';

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 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;

You might also like