0% found this document useful (0 votes)
3 views141 pages

SQL Server Notes_Updated (1)

Sql Server Notes

Uploaded by

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

SQL Server Notes_Updated (1)

Sql Server Notes

Uploaded by

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

SQL SERVER

1) Programming in SQL Server


1)DECLARE - It is use to declare variables.

Syntax - DECLARE @a int

2) SET - It is use to SET the values to the declared variables.

Syntax - SET @a=0

3) PRINT –

It is use to print the data/output.

4)IF() & IF() ELSE Conditions- Using this statements we can give
conditions to the program. For example - If I want only salary >
10000 Employee list.

Systax 1-

IF(x>y)

BEGIN

END

Systax 2-

IF(x>y)

BEGIN

END

ELSE
BEGIN

END

5)WHILE LOOP - When we need to handle iterative situation in the


programme, we use WHILE LOOP. We can get values here one by
one. It is mostly used with CURSOR in SQL/PL SQL Development

Syntax-

WHILE(val<10)

BEGIN

Val++

END

6) CONVERT(Datatype, value)-

It is use to covert datatype of the value.

1) Factorial.
2) DECLARE @a INT =0
3) DECLARE @b VARCHAR(MAX)= 'it''sstirng'
4) DECLARE @fact INT =1
5) SET @a=10
6)
7) WHILE(@a>=1)
8) BEGIN
9) PRINT @a
10) SET @fact=@fact*@a
11) SET @a-=1
12) END
13) PRINT @fact

2) Prime Number.

3) Odd and even number list


2)THE STRUCTURED QUERY LANGUAGE
SQL Stands for Structured query language.

SQL Is the data sub language consisting of 3 sub languages

1)DDL Data definition language – Create, Alter, Drop,Truncate

2)DML - Data manipulation language – Insert, Update, Delete,Select

3)DCL - Data Control language.

4) T-SQL - Transaction

1) DDL -

It’s stands for Data Definition Language.

DDL Defines a set of command used in the creation and


modification of schema object such as table, indexes, views etc.

A) Create Table Command –


Syntax –
CREATE TABLE <Table Name>(
Col_NM1 Data Type(Col Width)[Constraints],
Col_NM2 Data Type(Col Width)[Constraints],
………………………..
);

Eg
CREATETABLE FirstTable
(
Id int,
Name varchar(50),
Salary decimal(10,2),
IsActive bit,
Class char(1)
)
Guideline for creation of tables:
1) Table name should start with an alphabet.
2) Table name – blank space and single quotes not allowed.
3) Reserve words of that DBMS cannot be used as table name.
4) Proper datatype and size should be specified.
5) Unique column name should be specified.

B) Column Constraints –
1) NOT NULL – Usingthese constraints we can restrict null in
the particular column.
2) UNIQUE – It is use to define column as a unique. It does not
accept duplicate value. It can be null. We can have multiple
UNIQUE columns in the single table. It can be used as a
reference key in another table.
3) PRIMARY KEY – Once columns defined as primary key; it
does not allow duplicate values in the table. It cannot accept
null value. We can have only 1 primary keys in single table in
SQL server. It can be used as a reference key in another
table.
4) CHECK- It is use to give the condition to the column while
entering data in the table.
5) DEFAULT – It is use to set default value to particular column.
6) REFERENCES/Foreign key –We can use one table primary key
as a reference key in another table. It can be null. It must be
primary key/Unique key in another table.
C) ON DELETE CASCADE – Using these optionswhenever parent rows
is deleted in the referenced table then all corresponding child
rows are deleted from referencing table. This constraint is a form
of referential integrity constraints.
Example –
CREATETABLE Product(
Pno intPRIMARYKEY,
Pname varchar(100)UNIQUE,
Qno intDEFAULT(100),
Class char(1)NOTNULL,
Rate numeric(10,2)NOTNULL,
CHECK((Class='A'and Rate<1000)OR(class='B'and
Rate>1000 and Rate < 4500))
)

CREATE TABLE ProductDtl(

pdno int PRIMARY KEY IDENTITY(1,1),

pno INT references Product(pno)

ON DELETE CASCADE

);

B) ALTER TABLE command-

It’s use for modification for existing structure of the table in the
following situation.

i) Adding or removing new column


ii) Change existing column definition.
iii) Include or drop integrity constrains and enable or disable
the constraints.

Syntax:

i) ALTER TABLE <tbl name> ADD <col nm><data type>


ii) ALTER TABLE <tbl name>ALTER COLUMN<col
nm><data type>
iii) ALTERTABLE<Table Name>ADDCONSTRAINT
(constrName_uc_Fname) UNIQUE(Col nm)
iv) ALTER TABLE <tbl name> DROP COLUMN<Cons nm>
v) ALTER TABLE <tbl name> ENABLE/DISABLE <Cons nm>
D) DROP TABLE Command –
It is use to delete the not required existing object from the
database.
Syntax:DROP TABLE <tbl name>;

-------------------------------------------------------------------------

2) DML-

It’s stands for Data Manipulation Language. It defines a set of


commands that are used to query and modify data within existing
schema objects. DML statements consist of SELECT, INSERT, UPDATE
and DELETE statements.

A) SELECT Statement –
Use to retrieve data from tables.
i) Using Arithmetic operator-
Eg. – SELECT Ename, Sal, Sal+300 From Emp;

ii) Operator Precedence –


Basic Operators - *, /, +, -;
E.g. – SELECT Ename, Sal, 12*Sal+300 From Emp;

iii) Using Column Aliases –


E.g. To print Column names as Name and ANNUAL
SALARY
SELECT ENAME “NAME”, SAL *12 “ANNUAL SALARY”
FROM EMP;
iv) Concatenation operator –
Eg. SELECT ENAME +’ ’+JOB “EMPLOYEES” FROM
EMP;

v) To Eliminate duplicate row (DISTINCT operator)


SELECT DISTINCT Deptno FROM EMP;

vi) Special ComparisonOptr-


a) between ……. And
b) in(list) and Not IN (list)
c) Like Optr - To match character pattern.
- Use only char and varchar datatype
- % Denotes zero or many char
- _ Denotes one char

Eg.

i) Select emp whose name start with s

SELECT Ename from EMP Where Ename Like ‘s%’

ii) Select name end with ‘S’


SELECT Ename FROM emp Where ENAME Like
‘%s’
iii) Select ename where I has a second char.
SELECT Ename FROM EMP WHERE Ename LIKE
‘_I%’;

d) IS NULL and IS NOT NULL Optr-

vii) Logical Operator –


All Comparison operator, NOT, AND, OR

viii) Order by Clause –


Defult is ascending order
Eg.
Select * From Employee ORDER BY ename, sal DESC
ix) Aggregate functions –
MIN (), MAX(),AVG(),SUM(),COUNT().
x) Group by Clause –
Use to group rows on the
perticular column basis.
Where clause still can be used here.
Select Deptno, Count(emp)
From EMP
GROUP BY Deptno.
xi) HAVING Clause –
It is use to create certain condition on grouped
information.
Eg.
Select Deptno, Count(emp)
From EMP
GROUP BY Deptno.
HAVING MAX(sal)>20000;

B) INSERT INTO Command –


We can insert all columns, selected columns in table with
specific conditions.q
Eg.
1) Insert into INCR
Select empno,500, getDate() from EMP where job=’Manager’
2) Insert into with parameter substitution (&optr is used)
Eg.
INSERT INTO EMP VALUES (&1,’&2’)
INSERT INTO EMP (col1, col2) VALUES (&1,’&2’)

C) UPDATE Command –
UPDATE <table name>
SET <col>=<val>
WHERE <Condi>

D) DELETE Command-
Syntax –
DELETE FROM <tblnm> where <condition>.

E)
3) DATA CONTROL - DCL
1) Create new user -
CREATELOGINNewAdminNameWITH PASSWORD = 'ABCD'
GO

Eg.
CREATELOGIN Aalim WITHPASSWORD='mansuri123'
GO
Eg.
UseYourDatabase;
GO

IFNOTEXISTS(SELECT*FROMsys.database_principalsWHERE name
=N'NewAdminName')
BEGIN
CREATEUSER[NewAdminName]FOR LOGIN [NewAdminName]
EXECsp_addrolememberN'db_owner',N'NewAdminName'
END;
GO
2) Grant –
It’s provide database access to usesr.

Syntax –
GRANTSELECT,INSERT,UPDATEON Product TO Aalim
GRANTSELECT,INSERTON dbo.YourTable2 TO YourUserName
GRANTSELECT,DELETEON dbo.YourTable3 TO YourUserName

3) User Maping–
Assigning Database to users.
4 .Joins in sql server, Inner Join,CrossJoin,Left Outer Join,Equi join, Right
Outer Join, Full Outer Join

Description:

In SQL joins are used to get data from two or more tables based on relationship between
some of the columns in tables. In most of the cases we will use primary key of first table
and foreign key of secondary table to get data from tables.By using this relationship, we can
reduce the duplication of data in every table.

Before enter into Joins concept first design two tables in database and enter data like as
shown below

Create one table with primary key and give name as “UserDetails”

UserID UserName FirstName LastName

1 SureshDasari Suresh Dasari

2 PrasanthiDonthi Prasanthi Donthi

3 MaheshDasari Mahesh Dasari

Here UserID is the Primary key in UserDetails table

After that create another table with Foreign Key and give name as OrderDetails

OrderID OrderNo UserID

1 543224 1

2 213424 2

3 977776 3

4 323233 3

5 998756 1

Here OrderID is the Primary key and UserID is the foreign key in OrderDetails table.

SQL contains different types of Joins we will see each concept with example by using
above tables.
Types of Joins

1) Inner Joins

2) Outer Joins

3) Self Join

Inner Join

The join that displays onlythe rows that have a match in both the joined tables is
known as inner join. This is default join in the query and view Designer.

Syntax for Inner Join

SELECT t1.column_name,t2.column_name
FROM table_name1 t1

INNER JOIN table_name2 t2

ON t1.column_name=t2.column_name

Now check the below query for inner join

Example

SELECT u.UserName,u.LastName,o.OrderNo
FROM UserDetails u

INNER JOIN OrderDetails o

ON u.UserID=o.UserID

Once we run that query our output will be like this

UserName LastName OrderNo

SureshDasari Dasari 543224

PrasanthiDonthi Donthi 213424

MaheshDasari Dasari 977776

MaheshDasari Dasari 323233


SureshDasari Dasari 998756

We can write our inner join query like this also it will give same result

SELECT u.UserName,u.LastName,o.OrderNo
FROM UserDetails u

JOIN OrderDetails o

ON u.UserID=o.UserID

Based on above result we can say that INNER JOIN keyword return rows when there is at
least one match in both tables. If there are rows in "UserDetails" that do not have
matches in "OrderDetails", those rows will NOT be listed.

In inner Join we are having different types of Joins those are

1) Equi Join

2) Natural Join - oracle

3) Cross Join

Equi Join

The Equi join is used to display all the matched records from the joined tables and also
display redundant values. In this join we need to use * sign to join the table.

Syntax for Equi Join

SELECT * FROM table_name1 t1


INNER JOIN table_name2 t2

ON t1.column_name=t2.column_name

Now check the below query for Equi join

Example

SELECT *
FROM UserDetails u
INNER JOIN OrderDetails o

ON u.UserID=o.UserID

Once we run above query our output will be like this

UserI FirstNa LastNa OrderI Order UserI


UserName
D me me D No D

1 SureshDasari Suresh Dasari 1 543224 1

PrasanthiDo
2 Prasanthi Donthi 2 213424 2
nthi

MaheshDasa
3 Mahesh Dasari 3 977776 3
ri

MaheshDasa
3 Mahesh Dasari 4 323233 3
ri

1 SureshDasari Suresh Dasari 5 998756 1

In equi join we need to use only equality comparisons in the join relation. If we use other
operators such as (<,>) for our comparison condition then our Joins disqualifies for equi
join.

Natural Joins

The Natural join is same as our Equi join but only the difference is it will restrict to display
redundant values.

Syntax for Natural Join

SELECT * FROM table_name1 t1


NATURAL JOIN table_name2 t2

Example

SELECT *
FROM UserDetails

NATURAL JOIN OrderDetails

Note: These NATURAL Joins won’t work in our SQL Server (only supports in Oracle) it will
throw syntax error. If you observe above code "NATURAL" is not highlighted, indicating
that it is not recognized as a keyword.
Cross Join

A cross join that produces Cartesian product of the tables that involved in the join. The
size of a Cartesian product is the number of the rows in first table multiplied by the
number of rows in the second table.

Syntax for Cross Join

SELECT * FROM table_name1


CROSS JOIN table_name2

Or we can write it in another way also

SELECT * FROM table_name1,table_name2

Now check the below query for Cross join

Example

SELECT * FROM UserDetails


CROSS JOIN OrderDetails

Or

SELECT * FROM UserDetails, OrderDetails

Once we run that query our output will be like this

UserI FirstNa LastNa OrderI Order UserI


UserName
D me me D No D

1 SureshDasari Suresh Dasari 1 543224 1

1 SureshDasari Suresh Dasari 2 213424 2

1 SureshDasari Suresh Dasari 3 977776 3

1 SureshDasari Suresh Dasari 4 323233 3

1 SureshDasari Suresh Dasari 5 998756 1

PrasanthiDon
2 Prasanthi Donthi 1 543224 1
thi
PrasanthiDon
2 Prasanthi Donthi 2 213424 2
thi

PrasanthiDon
2 Prasanthi Donthi 3 977776 3
thi

PrasanthiDon
2 Prasanthi Donthi 4 323233 3
thi

PrasanthiDon
2 Prasanthi Donthi 5 998756 1
thi

MaheshDasa
3 Mahesh Dasari 1 543224 1
ri

MaheshDasa
3 Mahesh Dasari 2 213424 2
ri

MaheshDasa
3 Mahesh Dasari 3 977776 3
ri

MaheshDasa
3 Mahesh Dasari 4 323233 3
ri

MaheshDasa
3 Mahesh Dasari 5 998756 1
ri

Outer Joins

A join that returns all the rows that satisfy the condition and unmatched rows in the
joined table is an Outer Join.

We are having three types of Outer Joins

Left Outer Join

Right Outer Join

Full Outer Join

Left Outer Join

The left outer join displays all the rows from the first table and matched rows from the
second table.
Syntax for Left Outer Join

SELECT Column_List FROM table_name1 t1


LEFT OUTER JOIN table_name2 t2

ON t1.column_name=t2.column_name

Now check the below query for Left Outer join

Example

SELECT u.UserID,u.UserName,o.OrderNo
FROM UserDetails u

LEFT OUTER JOIN OrderDetails o

ON u.UserID=o.UserID

Once we run that query our output will be like this

UserID UserName OrderNo

1 SureshDasari 543224

1 SureshDasari 998756

2 PrasanthiDonthi 213424

3 MaheshDasari 977776

3 MaheshDasari 323233

Right Outer Join

The right outer join displays all the rows from the second table and matched rows from
the first table.

Syntax for Right Outer Join

SELECT Column_List FROM table_name1 t1


RIGHT OUTER JOIN table_name2 t2
ON t1.column_name=t2.column_name

Now check the below query for Right Outer join

Example

SELECT u.UserID,u.UserName,o.OrderNo
FROM UserDetails u

RIGHT OUTER JOIN OrderDetails o

ON u.UserID=o.UserID

Once we run that query our output will be like this

UserID UserName OrderNo

1 SureshDasari 543224

2 PrasanthiDonthi 213424

3 MaheshDasari 977776

3 MaheshDasari 323233

1 SureshDasari 998756

Full Outer Join

Full Outer Join displays all the matching and non matching rows of both the tables.

Syntax for Full Outer Join

SELECT Column_List FROM table_name1 t1


FULL OUTER JOIN table_name2 t2

ON t1.column_name=t2.column_name

Now check the below query for Full Outer join

Example

SELECT u.UserID,u.UserName,o.OrderNo
FROM UserDetails u

FULL OUTER JOIN OrderDetails o

ON u.UserID=o.UserID

Once we run that query our output will be like this

User UserNam FirstN LastNa Orde Order User


ID e ame me rID No ID

SureshDas 54322
1 Suresh Dasari 1 1
ari 4

SureshDas 99875
1 Suresh Dasari 5 1
ari 6

PrasanthiD Prasant 21342


2 Donthi 2 2
onthi hi 4

MaheshDa 97777
3 Mahesh Dasari 3 3
sari 6

MaheshDa 32323
3 Mahesh Dasari 4 3
sari 3

Self Join

Joining the table itself called self-join. Self-join is used to retrieve the records having
some relation or similarity with other records in the same table. Here we need to use
aliases for the same table to set a self-join between single table and retrieve records
satisfying the condition in where clause.

To implement self join first design table and give a name as “EmployeeDetails”

EmpID EmpName EmpMgrID

1 Suresh 2

2 Prasanthi 4

3 Mahesh 2

4 Sai 1

5 Nagaraju 1

6 Mahendra 3
7 Sanjay 3

Now I want to get manager names of particular employee for that we need to write query
like this

select e2.EmpName,e1.EmpName as 'Manager'


from EmployeeDetails e1

INNER JOIN EmployeeDetails e2

on e1.EmpID=e2.EmpMgrID

Here if you observe above query EmployeeDetails table joined itself using table aliases
e1 and e2.

After that run our query output will be like this

EmpName Manger

Sai Suresh

Nagaraju Suresh

Suresh Prasanthi

Mahesh Prasanthi

Mahendra Mahesh

Sanjay Mahesh

Prasanthi Sai
VIEWS
Types of View

View is a database object which is use to fetch data from the database.
It only shows the data to user.

1. System View
2. User Define View

User Defined Views are important so I describe only User Defined


Views. They are of two types:

1. Simple View
2. Complex view

Simple View

When a View is created on a single Table then it is called a Simple View.


We can apply all DML operations on a Simple View that we can apply on
a table.

Creation of a simple view

1.create view v1
2.as
3.select * from emp

See the specific data of the view

1.select * from v1 where empId=4

Insertion

1.insert into v1 values(7,'raj','canada');

Updating

1.update v1 set empAdd='usa'where empId=7


Deletion

1.delete from v1 where empId=7

Renaming

1.exec sp_rename 'v1','v11'

Logic of the View

1.exec sp_helptext v1

Dropping the View

1.drop view v1

2. Complex view
3. Views created on more than one table are called Complex View.
We cannot perform all DML operations of a table on a Complex
View.

Creation of complex view

1.create View VComplex


2.as
3.select e.empId,e.empName,e1.empStatus from emp e
inner join empStatus e1 on e.empId=e1.empId

See all the records

1.select * from VComplex

See specific record

1.select * from VComplex where empId=4


If we try insert, update or delete in a complex view then it shows an error
as in the following

1.insert into vcomplex values(11,'d','inactive')


SEQUENCES
What is SQL Sequence

A SQL Sequence is a database object that generates numbers


in sequential order. SQL Sequences are available to all users of
the database. SQL Sequences are created using SQL
statements.

What is the need of a SQL Sequence?

A SQL Server sequence object generates a sequence of


numbers just like an identity column in SQL tables. But the
advantage of sequence numbers is the sequence number
object is not limited to a single SQL table. There is no direct
relation between tables, table identity columns and number
sequences.

Create SQL Sequence in SQL Server 2012

The following is the syntax of a SQL Sequence:

CREATE SEQUENCE [schema_name . ] sequence_name


[ AS [ built_in_integer_type | user-defined_integer_type ] ]
[ START WITH <constant> ]
[ INCREMENT BY <constant> ]
[ { MINVALUE [ <constant> ] } | { NO MINVALUE } ]
[ { MAXVALUE [ <constant> ] } | { NO MAXVALUE } ]
[ CYCLE | { NO CYCLE } ]
[ { CACHE [ <constant> ] } | { NO CACHE } ]
[;]

Example of Creating a SQL Sequence in SQL Server 2012

-- Create sequence of numbers starting from 1 with increment


by 1
CREATE SEQUENCE MyFirstSequence
START WITH 1
INCREMENT BY 1;
GO
Get the value of a number from SQL Sequence

After having created a SQL Sequence, you can get the number
value from your created sequence using the NEXT VALUE FOR
function. The NEXT VALUE FOR will return the next sequential
number, the same as in the above screenshot.

-- Read from Sequence of Numbers using Next Value For


Function
SELECT NEXT VALUE FOR dbo.MyFirstSequence

Use sequence in Insert operation

You can use a sequence in an Insert Query. You can insert a


record into a table with a sequence number from a SQL
Sequence object as shown in the following code.

Create SQL table Employees


-- Create sql table Employees
CREATE TABLE Employees (
EmployeeID int Identity(1,1) PRIMARY KEY,
UserID int,
FirstName nvarchar(100) NOT NULL,
LarstName nvarchar(100) NOT NULL
)

-- Insert new rows into sql tables


INSERT INTO Employees (
UserID, FirstName, LarstName
) VALUES (
NEXT VALUE FOR MyFirstSequence, 'Keyur', 'Patel'
);

Alter and Drop the Sequence object

We can also alter and drop the existing sequence. We can alter the
increment, cycle, minimum value and maximum value of a sequence.
Start with cannot be used with the alter statement.
ALTER SEQUENCE TableNextId
INCREMENT BY 2
MINVALUE 1000
MAXVALUE 100000

DROP SEQUENCE TableNextId

DROP SEQUENCE TableNextId

INDEXES
An Index is a database object that can be created on one or more
columns (16 max column combinations). When creating the index, it will
read the column(s) and forms a relevant data structure to minimize the
number of data comparisons. The index will improve the performance of
data retrieval and add some overhead to the data modification such as
create, delete and modify. So, it depends on how much data retrieval
can be done on table versus how much of DML (Insert, Delete and
Update) operations.

In short

An index is basically used for fast data retrieval from the database.

Type of Index

In a SQL Server database there are mainly the following two types of
indexes:

1. Clustered index and


2. Non-Clustered index

Syntax to create Index

The basic syntax of CREATE INDEX is as follows:

1.CREATE
CLUSTERED/NONCLUSTERED INDEX index_name ON table_
name(column nm);

Clustered Index

In a simple way a Primary key is a Clustered index.

Eg.

CREATECLUSTEREDINDEX CL_ID ON SALES(ID);

Non-Clustered Index

A Unique key is a non-Clustered index.


Eg.

CREATENONCLUSTEREDINDEX NONCI_PC ON
SALES(ProductCode);
The DROP INDEX Command

An index can be dropped using the SQL DROP command. Care should
be taken when dropping an index because performance may be
degraded or improved.

The basic syntax is as follows:

1.DROP INDEX index_name ON TableName;

Difference between Clustered Index and Non-Clustered Index in


SQL Server

1. One of the main differences between clustered and non-clustered


indexes in SQL Server is that, one table can only have one
clustered Index but It can have many non-clustered indexes,
approximately 250 because basically a Primary key is a Clustered
index and a Unique key is a non-Clustered index and one table
can have only one primary.
2. Basically, a Primary key is a Clustered index and a Unique key is a
non-Clustered index.
3. A clustered index determines the order in which the rows of the
table will be stored on disk. A non-clustered index has no effect on
which the order of the rows will be stored.
4. Non-clustered indexes store both a value and a pointer to the
actual row that holds that value. Clustered indexes don't need to
store a pointer to the actual row because of the fact that the rows
in the table are stored on disk in the same exact order as the
clustered index.
5. Non-Clustered Indexes require more space compared to Clustered
indexes because in non-Clustered indexes one separate table is
maintained.
Synonym in SQL Server

A synonym is nothing but a name. It does not store any data or any T-
SQL Query. It just refers to the database objects. Here the database
objects include the following:

The following is the basic syntax for creating a synonym:

1.CREATE SYNONYM schema_name.synonym_name FOR objec


t_name

CREATE SYNONM FOR EMP TABLE

1.CREATE SYNONYM SY_EMP FOREMP

Once a synonym is created we can use that synonym for what it stands
for, in other words in the preceding we created the synonym for the EMP
table. In this case we can use T-SQL statements like SELECT, INSERT,
UPDATE and DELETE.

SELECTING DATA FROM SYNONYM

1.SELECT * FROM DBO.SY_EMP

INSERTING DATA USING SYNONYM

1.INSERT INTO DBO.SY_EMP(FIRTSNAME,LASTNAME,LOCATIO


N,DOB,SALARY,DEPT)
2.VALUES
3.('RAMU','J','HYDERABAD','07-23-1989',24000,1)

DELETE RECORD FROM SYNONYM

1.DELETE FROM DBO.SY_EMP WHERE ID=3


The SQL SELECT DISTINCT Statement
The SELECT DISTINCT statement is used to return only distinct (different) values.

Inside a table, a column often contains many duplicate values; and sometimes you only want to list the
different (distinct) values.

The SELECT DISTINCT statement is used to return only distinct (different) values.

SELECT DISTINCT Syntax


SELECT DISTINCT column1, column2, ...
FROM table_name;

The SQL AND, OR and NOT Operators


The WHERE clause can be combined with AND, OR, and NOT operators.

The AND and OR operators are used to filter records based on more than one condition:

 The AND operator displays a record if all the conditions separated by AND is TRUE.
 The OR operator displays a record if any of the conditions separated by OR is TRUE.

The NOT operator displays a record if the condition(s) is NOT TRUE.

AND Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;

OR Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;

NOT Syntax
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;

The SQL ORDER BY Keyword


The ORDER BY keyword is used to sort the result-set in ascending or descending order.

The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending
order, use the DESC keyword.

ORDER BY Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;

SQL NULL Values


What is a NULL Value?
A field with a NULL value is a field with no value.

If a field in a table is optional, it is possible to insert a new record or update a record without adding a value to
this field. Then, the field will be saved with a NULL value.

How to Test for NULL Values?


It is not possible to test for NULL values with comparison operators, such as =, <, or <>.

We will have to use the IS NULL and IS NOT NULL operators instead.

IS NULL Syntax
SELECT column_names
FROM table_name
WHERE column_name IS NULL;

IS NOT NULL Syntax


SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;

The SQL SELECT TOP Clause


The SELECT TOP clause is used to specify the number of records to return.

The SELECT TOP clause is useful on large tables with thousands of records. Returning a large number of records
can impact on performance.

Note: Not all database systems support the SELECT TOP clause. MySQL supports the LIMIT clause to select a
limited number of records, while Oracle uses ROWNUM.

SQL Server / MS Access Syntax:

SELECT TOP number|percent column_name(s)


FROM table_name
WHERE condition;

he SQL MIN() and MAX() Functions


The MIN() function returns the smallest value of the selected column.

The MAX() function returns the largest value of the selected column.

MIN() Syntax
SELECT MIN(column_name)
FROM table_name
WHERE condition;
MAX() Syntax
SELECT MAX(column_name)
FROM table_name
WHERE condition;

The SQL COUNT(), AVG() and SUM() Functions


The COUNT() function returns the number of rows that matches a specified criteria.

The AVG() function returns the average value of a numeric column.

The SUM() function returns the total sum of a numeric column.

COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;

AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;

SUM() Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;

The SQL LIKE Operator


The LIKE operator is used in a WHERE clause to search for a specified pattern in a column.

There are two wildcards used in conjunction with the LIKE operator:

 % - The percent sign represents zero, one, or multiple characters


 _ - The underscore represents a single character

Note: MS Access uses a question mark (?) instead of the underscore (_).

The percent sign and the underscore can also be used in combinations!

LIKE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;

Tip: You can also combine any number of conditions using AND or OR operators.

Here are some examples showing different LIKE operators with '%' and '_' wildcards:

LIKE Operator Description


WHERE CustomerName LIKE 'a%' Finds any values that starts with "a"

WHERE CustomerName LIKE '%a' Finds any values that ends with "a"

WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any position

WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second position

WHERE CustomerName LIKE 'a_%_%' Finds any values that starts with "a" and are at least 3 characters in length

WHERE ContactName LIKE 'a%o' Finds any values that starts with "a" and ends with "o"

SQL LIKE Examples


The following SQL statement selects all customers with a CustomerName starting with "a":

Example
SELECT * FROM Customers
WHERE CustomerName LIKE 'a%';

Try it Yourself »

The following SQL statement selects all customers with a CustomerName ending with "a":

Example
SELECT * FROM Customers
WHERE CustomerName LIKE '%a';

Try it Yourself »

The following SQL statement selects all customers with a CustomerName that have "or" in any position:

Example
SELECT * FROM Customers
WHERE CustomerName LIKE '%or%';

Try it Yourself »

The following SQL statement selects all customers with a CustomerName that have "r" in the second position:

Example
SELECT * FROM Customers
WHERE CustomerName LIKE '_r%';

Try it Yourself »
The following SQL statement selects all customers with a CustomerName that starts with "a" and are at least 3
characters in length:

Example
SELECT * FROM Customers
WHERE CustomerName LIKE 'a_%_%';

Try it Yourself »

The following SQL statement selects all customers with a ContactName that starts with "a" and ends with "o":

Example
SELECT * FROM Customers
WHERE ContactName LIKE 'a%o';

Try it Yourself »

The following SQL statement selects all customers with a CustomerName that NOT starts with "a":

Example
SELECT * FROM Customers
WHERE CustomerName NOT LIKE 'a%';

SQL Wildcard Characters


A wildcard character is used to substitute any other character(s) in a string.

Wildcard characters are used with the SQL LIKE operator. The LIKE operator is used in a WHERE clause to
search for a specified pattern in a column.

There are two wildcards used in conjunction with the LIKE operator:

 % - The percent sign represents zero, one, or multiple characters


 _ - The underscore represents a single character

Note: MS Access uses a question mark (?) instead of the underscore (_).

In MS Access and SQL Server you can also use:

 [charlist] - Defines sets and ranges of characters to match


 [^charlist] or [!charlist] - Defines sets and ranges of characters NOT to match

The wildcards can also be used in combinations!

Here are some examples showing different LIKE operators with '%' and '_' wildcards:

LIKE Operator Description

WHERE CustomerName LIKE 'a%' Finds any values that starts with "a"

WHERE CustomerName LIKE '%a' Finds any values that ends with "a"
WHERE CustomerName LIKE '%or%' Finds any values that have "or" in any position

WHERE CustomerName LIKE '_r%' Finds any values that have "r" in the second position

WHERE CustomerName LIKE 'a_%_%' Finds any values that starts with "a" and are at least 3 characters in length

WHERE ContactName LIKE 'a%o' Finds any values that starts with "a" and ends with "o"

Using the % Wildcard


The following SQL statement selects all customers with a City starting with "ber":

Example
SELECT * FROM Customers
WHERE City LIKE 'ber%';

Try it Yourself »

The following SQL statement selects all customers with a City containing the pattern "es":

Example
SELECT * FROM Customers
WHERE City LIKE '%es%';

Try it Yourself »

Using the _ Wildcard


The following SQL statement selects all customers with a City starting with any character, followed by "erlin":

Example
SELECT * FROM Customers
WHERE City LIKE '_erlin';

Try it Yourself »

The following SQL statement selects all customers with a City starting with "L", followed by any character,
followed by "n", followed by any character, followed by "on":

Example
SELECT * FROM Customers
WHERE City LIKE 'L_n_on';

Try it Yourself »
Using the [charlist] Wildcard
The following SQL statement selects all customers with a City starting with "b", "s", or "p":

Example
SELECT * FROM Customers
WHERE City LIKE '[bsp]%';

Try it Yourself »

The following SQL statement selects all customers with a City starting with "a", "b", or "c":

Example
SELECT * FROM Customers
WHERE City LIKE '[a-c]%';

Try it Yourself »

Using the [!charlist] Wildcard


The two following SQL statements selects all customers with a City NOT starting with "b", "s", or "p":

Example
SELECT * FROM Customers
WHERE City LIKE '[!bsp]%';

Try it Yourself »

Or:

Example
SELECT * FROM Customers
WHERE City NOT LIKE '[bsp]%';

Try it Yourself »

The SQL IN Operator


The IN operator allows you to specify multiple values in a WHERE clause.

The IN operator is a shorthand for multiple OR conditions.

IN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);

or:
SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);

SQL Server NOT IN Operator


Example
SELECT * FROM Customers
WHERE Country NOT IN ('Germany', 'France', 'UK');

The SQL BETWEEN Operator


The BETWEEN operator selects values within a given range. The values can be numbers, text, or dates.

The BETWEEN operator is inclusive: begin and end values are included.

BETWEEN Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;

SQL Aliases
SQL Aliases
SQL aliases are used to give a table, or a column in a table, a temporary name.

Aliases are often used to make column names more readable.

An alias only exists for the duration of the query.

Alias Column Syntax


SELECT column_name AS alias_name
FROM table_name;

Alias Table Syntax


SELECT column_name(s)
FROM table_name AS alias_name;

Aliases can be useful when:

 There are more than one table involved in a query


 Functions are used in the query
 Column names are big or not very readable
 Two or more columns are combined together

The SQL UNION Operator


The UNION operator is used to combine the result-set of two or more SELECT statements.

 Each SELECT statement within UNION must have the same number of columns
 The columns must also have similar data types
 The columns in each SELECT statement must also be in the same order (of data types)

UNION Syntax
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;

UNION ALL Syntax

The UNION operator selects only distinct values by default. To allow duplicate values, use UNION ALL:

SELECT column_name(s) FROM table1


UNION ALL
SELECT column_name(s) FROM table2;

Note: The column names in the result-set are usually equal to the column names in the first SELECT statement
in the UNION.

The SQL GROUP BY Statement


The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN, SUM, AVG) to group the
result-set by one or more columns.

GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);

SQL GROUP BY Examples


The following SQL statement lists the number of customers in each country:

Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;

The following SQL statement lists the number of customers in each country, sorted high to low:

Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;

GROUP BY With JOIN Example


The following SQL statement lists the number of orders sent by each shipper:
Example
SELECT Shippers.ShipperName, COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
LEFT JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID
GROUP BY ShipperName;

The SQL HAVING Clause


The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate
functions.

HAVING Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);

Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID) DESC;

The SQL EXISTS/ NOT 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);

EG

IFNOTEXISTS(SELECT*FROM EmployeeMaster)
BEGIN
Print'done'
END
IFEXISTS(SELECT*FROM EmployeeMaster)
BEGIN
Print'done'
END
The SQL ANY and ALL Operators
The ANY and ALL operators are used with a WHERE or HAVING clause.

The ANY operator returns true if any of the subquery values meet the condition.

The ALL operator returns true if all of the subquery values meet the condition.

ANY Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
(SELECT column_name FROM table_name WHERE condition);

ALL Syntax
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 <=).

Example
SELECT ProductName
FROM Products
WHERE ProductID = ANY (SELECT ProductID FROM OrderDetails WHERE Quantity > 99);

Example
SELECT ProductName
FROM Products
WHERE ProductID = ALL (SELECT ProductID FROM OrderDetails WHERE Quantity = 10);

The SQL SELECT INTO Statement


The SELECT INTO statement copies data from one table into a new table.

SELECT INTO Syntax

Copy all columns into a new table:

SELECT *
INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;

Copy only some columns into a new table:

SELECT column1, column2, column3, ...


INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;

The new table will be created with the column-names and types as defined in the old table. You can create new
column names using the AS clause.

SQL SELECT INTO Examples


The following SQL statement creates a backup copy of Customers:

SELECT * INTO CustomersBackup2017


FROM Customers;

The following SQL statement uses the IN clause to copy the table into a new table in another database:

SELECT * INTO CustomersBackup2017 IN 'Backup.mdb'


FROM Customers;

The following SQL statement copies only a few columns into a new table:

SELECT CustomerName, ContactName INTO CustomersBackup2017


FROM Customers;

The following SQL statement copies only the German customers into a new table:

SELECT * INTO CustomersGermany


FROM Customers
WHERE Country = 'Germany';

The following SQL statement copies data from more than one table into a new table:

SELECT Customers.CustomerName, Orders.OrderID


INTO CustomersOrderBackup2017
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID;

Tip: SELECT INTO can also be used to create a new, empty table using the schema of another. Just add a
WHERE clause that causes the query to return no data:

SELECT * INTO newtable


FROM oldtable
WHERE 1 = 0;

The SQL INSERT INTO SELECT Statement


The INSERT INTO SELECT statement copies data from one table and inserts it into another table.

 INSERT INTO SELECT requires that data types in source and target tables match
 The existing records in the target table are unaffected

INSERT INTO SELECT Syntax

Copy all columns from one table to another table:


INSERT INTO table2
SELECT * FROM table1
WHERE condition;

Copy only some columns from one table into another table:

INSERT INTO table2 (column1, column2, column3, ...)


SELECT column1, column2, column3, ...
FROM table1
WHERE condition;

SQL INSERT INTO SELECT Examples


The following SQL statement copies "Suppliers" into "Customers" (the columns that are not filled with data, will
contain NULL):

Example
INSERT INTO Customers (CustomerName, City, Country)
SELECT SupplierName, City, Country FROM Suppliers;

The following SQL statement copies "Suppliers" into "Customers" (fill all columns):

Example
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
SELECT SupplierName, ContactName, Address, City, PostalCode, Country FROM Suppliers;

The following SQL statement copies only the German suppliers into "Customers":

Example
INSERT INTO Customers (CustomerName, City, Country)
SELECT SupplierName, City, Country FROM Suppliers
WHERE Country='Germany';

SQL Dates
The most difficult part when working with dates is to be sure that the format of the date you are trying to insert,
matches the format of the date column in the database.

As long as your data contains only the date portion, your queries will work as expected. However, if a time
portion is involved, it gets more complicated.

SQL Date Data Types


SQL Server comes with the following data types for storing a date or a date/time value in the database:

 DATE - format YYYY-MM-DD


 DATETIME - format: YYYY-MM-DD HH:MI:SS
 SMALLDATETIME - format: YYYY-MM-DD HH:MI:SS
 TIMESTAMP - format: a unique number

Note: The date types are chosen for a column when you create a new table in your database!
SQL Injection
SQL injection is a code injection technique that might destroy your database.

SQL injection is one of the most common web hacking techniques.

SQL injection is the placement of malicious code in SQL statements, via web page input.

SQL in Web Pages


SQL injection usually occurs when you ask a user for input, like their username/userid, and instead of a
name/id, the user gives you an SQL statement that you will unknowingly run on your database.

Look at the following example which creates a SELECT statement by adding a variable (txtUserId) to a select
string. The variable is fetched from user input (getRequestString):

Example
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;

The rest of this chapter describes the potential dangers of using user input in SQL statements.

SQL Injection Based on 1=1 is Always True


Look at the example above again. The original purpose of the code was to create an SQL statement to select a
user, with a given user id.
If there is nothing to prevent a user from entering "wrong" input, the user can enter some "smart" input like
this:

105 OR 1=1
UserId:

Then, the SQL statement will look like this:

SELECT * FROM Users WHERE UserId = 105 OR 1=1;

The SQL above is valid and will return ALL rows from the "Users" table, since OR 1=1 is always TRUE.

Does the example above look dangerous? What if the "Users" table contains names and passwords?

The SQL statement above is much the same as this:

SELECT UserId, Name, Password FROM Users WHERE UserId = 105 or 1=1;

A hacker might get access to all the user names and passwords in a database, by simply inserting 105 OR 1=1
into the input field.

SQL Injection Based on ""="" is Always True


Here is an example of a user login on a web site:

Username:
John Doe

Password:
myPass

Example
uName = getRequestString("username");
uPass = getRequestString("userpassword");

sql = 'SELECT * FROM Users WHERE Name ="' + uName + '" AND Pass ="' + uPass + '"'

Result
SELECT * FROM Users WHERE Name ="John Doe" AND Pass ="myPass"

A hacker might get access to user names and passwords in a database by simply inserting " OR ""=" into the
user name or password text box:

User Name:

Password:

The code at the server will create a valid SQL statement like this:
Result
SELECT * FROM Users WHERE Name ="" or ""="" AND Pass ="" or ""=""

The SQL above is valid and will return all rows from the "Users" table, since OR ""="" is always TRUE.

SQL Injection Based on Batched SQL Statements


Most databases support batched SQL statement.

A batch of SQL statements is a group of two or more SQL statements, separated by semicolons.

The SQL statement below will return all rows from the "Users" table, then delete the "Suppliers" table.

Example
SELECT * FROM Users; DROP TABLE Suppliers

Look at the following example:

Example
txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = " + txtUserId;

And the following input:

105; DROP TAB


User id:

The valid SQL statement would look like this:

Result
SELECT * FROM Users WHERE UserId = 105; DROP TABLE Suppliers;

Use SQL Parameters for Protection


To protect a web site from SQL injection, you can use SQL parameters.

SQL parameters are values that are added to an SQL query at execution time, in a controlled manner.

ASP.NET Razor Example


txtUserId = getRequestString("UserId");
txtSQL = "SELECT * FROM Users WHERE UserId = @0";
db.Execute(txtSQL,txtUserId);

Note that parameters are represented in the SQL statement by a @ marker.

The SQL engine checks each parameter to ensure that it is correct for its column and are treated literally, and
not as part of the SQL to be executed.
Another Example
txtNam = getRequestString("CustomerName");
txtAdd = getRequestString("Address");
txtCit = getRequestString("City");
txtSQL = "INSERT INTO Customers (CustomerName,Address,City) Values(@0,@1,@2)";
db.Execute(txtSQL,txtNam,txtAdd,txtCit);

Examples
The following examples shows how to build parameterized queries in some common web languages.

SELECT STATEMENT IN ASP.NET:

txtUserId = getRequestString("UserId");
sql = "SELECT * FROM Customers WHERE CustomerId = @0";
command = new SqlCommand(sql);
command.Parameters.AddWithValue("@0",txtUserID);
command.ExecuteReader();

INSERT INTO STATEMENT IN ASP.NET:

txtNam = getRequestString("CustomerName");
txtAdd = getRequestString("Address");
txtCit = getRequestString("City");
txtSQL = "INSERT INTO Customers (CustomerName,Address,City) Values(@0,@1,@2)";
command = new SqlCommand(txtSQL);
command.Parameters.AddWithValue("@0",txtNam);
command.Parameters.AddWithValue("@1",txtAdd);
command.Parameters.AddWithValue("@2",txtCit);
command.ExecuteNonQuery();

INSERT INTO STATEMENT IN PHP:

$stmt = $dbh->prepare("INSERT INTO Customers (CustomerName,Address,City)


VALUES (:nam, :add, :cit)");
$stmt->bindParam(':nam', $txtNam);
$stmt->bindParam(':add', $txtAdd);
$stmt->bindParam(':cit', $txtCit);
$stmt->execute();
SQL Server Functions
SQL Server has many built-in functions.

This reference contains the string, numeric, date, conversion, and advanced functions in SQL Server.

SQL Server String Functions

Function Description

ASCII Returns the number code that represents the specific character

CHAR Returns the ASCII character based on the number code

CHARINDEX Returns the location of a substring in a string

CONCAT Concatenates two or more strings together

Concat with + Concatenates two or more strings together

DATALENGTH Returns the length of an expression (in bytes)

LEFT Extracts a substring from a string (starting from left)


LEN Returns the length of the specified 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 location of a pattern in a string

REPLACE Replaces a sequence of characters in a string with another set of characters

RIGHT Extracts a substring from a string (starting from right)

RTRIM Removes trailing spaces from a string

SPACE Returns a string with a specified number of spaces

STR Returns a string representation of a number

STUFF Deletes a sequence of characters from a string and then inserts another sequence of
characters into the string, starting at a specified position

SUBSTRING Extracts a substring from a string

UPPER Converts a string to upper-case


SQL Server Numeric Functions

Function Description

ABS Returns the absolute value of a number

AVG Returns the average value of an expression

CEILING Returns the smallest integer value that is greater than or equal to a number

COUNT Returns the count of an expression

FLOOR Returns the largest integer value that is equal to or less than a number

MAX Returns the maximum value of an expression

MIN Returns the minimum value of an expression

RAND Returns a random number or a random number within a range

ROUND Returns a number rounded to a certain number of decimal places

SIGN Returns a value indicating the sign of a number

SUM Returns the summed value of an expression

SQL Server Date Functions

Function Description

CURRENT_TIMESTAMP Returns the current date and time


DATEADD Returns a date after a certain time/date interval has been added

DATEDIFF Returns the difference between two date values, based on the interval specified

DATENAME Returns a specified part of a given date, as a string value

DATEPART Returns a specified part of a given date, as an integer value

DAY Returns the day of the month (from 1 to 31) for a given date

GETDATE Returns the current date and time

GETUTCDATE Returns the current UTC date and time

MONTH Returns the month (from 1 to 12) for a given date

YEAR Returns the year (as a four-digit number) for a given date

SQL Server Conversion Functions

Function Description

CAST Converts an expression from one data type to another

CONVERT Converts an expression from one data type to another

SQL Server Advanced Functions

Function Description

COALESCE Returns the first non-null expression in a list


CURRENT_USER Returns the name of the current user in the SQL Server database

ISDATE Returns 1 if the expression is a valid date, otherwise 0

ISNULL Lets you return an alternative value when an expression is NULL

ISNUMERIC Returns 1 if the expression is a valid number, otherwise 0

NULLIF Compares two expressions

SESSION_USER Returns the user name of the current session in the SQL Server database

SESSIONPROPERTY Returns the setting for a specified option of a session

SYSTEM_USER Returns the login name information for the current user in the SQL Server database

USER_NAME Returns the user name in the SQL Server database

SQL NULL Functions

SQL ISNULL(),
We have the following SELECT statement:

SELECT ProductName,UnitPrice*(UnitsInStock+UnitsOnOrder)
FROM Products

In the example above, if any of the "UnitsOnOrder" values are NULL, the result is NULL.

Microsoft's ISNULL() function is used to specify how we want to treat NULL values.

In this case we want NULL values to be zero.

Below, if "UnitsOnOrder" is NULL it will not harm the calculation, because ISNULL() returns a zero if the value is
NULL:
SQL Server

SELECT ProductName, UnitPrice*(UnitsInStock+ISNULL(UnitsOnOrder,0))


FROM Products

SQL Operators

SQL Arithmetic Operators

Operator Description Example

+ Add Try it

- Subtract Try it

* Multiply Try it

/ Divide Try it

% Modulo Try it

SQL Bitwise Operators

Operator Description

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR
SQL Comparison Operators

Operator Description Example

= Equal to Try it

> Greater than Try it

< Less than Try it

>= Greater than or equal to Try it

<= Less than or equal to Try it

<> Not equal to Try it

SQL Compound Operators

Operator Description

+= Add equals

-= Subtract equals

*= Multiply equals

/= Divide equals

%= Modulo equals

&= Bitwise AND equals


^-= Bitwise exclusive equals

|*= Bitwise OR equals

SQL Logical Operators

Operator Description Example

ALL TRUE if all of the subquery values meet the condition Try it

AND TRUE if all the conditions separated by AND is TRUE Try it

ANY TRUE if any of the subquery values meet the condition Try it

BETWEEN TRUE if the operand is within the range of comparisons Try it

EXISTS TRUE if the subquery returns one or more records Try it

IN TRUE if the operand is equal to one of a list of expressions Try it

LIKE TRUE if the operand matches a pattern Try it

NOT Displays a record if the condition(s) is NOT TRUE Try it

OR TRUE if any of the conditions separated by OR is TRUE Try it

SOME TRUE if any of the subquery values meet the condition


SQL Server Data Types
String data types:

Data type Description Max size Storage

char(n) Fixed width character string 8,000 characters Defined width

varchar(n) Variable width character string 8,000 characters 2 bytes + number of chars

varchar(max) Variable width character string 1,073,741,824 characters 2 bytes + number of chars

Text Variable width character string 2GB of text data 4 bytes + number of chars

Nchar Fixed width Unicode string 4,000 characters Defined width x 2

Nvarchar Variable width Unicode string 4,000 characters

nvarchar(max) Variable width Unicode string 536,870,912 characters

Ntext Variable width Unicode string 2GB of text data

binary(n) Fixed width binary string 8,000 bytes

Varbinary Variable width binary string 8,000 bytes

varbinary(max) Variable width binary string 2GB

Image Variable width binary string 2GB


Number data types:

Data type Description Storage

Bit Integer that can be 0, 1, or NULL

Tinyint Allows whole numbers from 0 to 255 1 byte

Smallint Allows whole numbers between -32,768 and 32,767 2 bytes

Int Allows whole numbers between -2,147,483,648 and 2,147,483,647 4 bytes

Bigint Allows whole numbers between -9,223,372,036,854,775,808 and 8 bytes


9,223,372,036,854,775,807

5-17 bytes
decimal(p,s) Fixed precision and scale numbers.

Allows numbers from -10^38 +1 to 10^38 –1.

The p parameter indicates the maximum total number of digits that


can be stored (both to the left and to the right of the decimal point).
p must be a value from 1 to 38. Default is 18.

The s parameter indicates the maximum number of digits stored to


the right of the decimal point. s must be a value from 0 to p.
Default value is 0
numeric(p,s) Fixed precision and scale numbers. 5-17 bytes

Allows numbers from -10^38 +1 to 10^38 –1.

The p parameter indicates the maximum total number of digits that


can be stored (both to the left and to the right of the decimal point).
p must be a value from 1 to 38. Default is 18.

The s parameter indicates the maximum number of digits stored to


the right of the decimal point. s must be a value from 0 to p.
Default value is 0
Smallmoney Monetary data from -214,748.3648 to 214,748.3647 4 bytes
Money Monetary data from -922,337,203,685,477.5808 to 8 bytes
922,337,203,685,477.5807

float(n) Floating precision number data from -1.79E + 308 to 1.79E + 308. 4 or 8 bytes

The n parameter indicates whether the field should hold 4 or 8


bytes. float(24) holds a 4-byte field and float(53) holds an 8-byte
field. Default value of n is 53.
Real Floating precision number data from -3.40E + 38 to 3.40E + 38 4 bytes

Date data types:

Data type Description Storage

Datetime From January 1, 1753 to December 31, 9999 with an accuracy of 3.33 8 bytes
milliseconds

datetime2 From January 1, 0001 to December 31, 9999 with an accuracy of 100 6-8 bytes
nanoseconds

Smalldatetime From January 1, 1900 to June 6, 2079 with an accuracy of 1 minute 4 bytes

Date Store a date only. From January 1, 0001 to December 31, 9999 3 bytes

Time Store a time only to an accuracy of 100 nanoseconds 3-5 bytes

Datetimeoffset The same as datetime2 with the addition of a time zone offset 8-10 bytes

Timestamp Stores a unique number that gets updated every time a row gets created
or modified. The timestamp value is based upon an internal clock and
does not correspond to real time. Each table may have only one
timestamp variable

Other data types:

Data type Description


sql_variant Stores up to 8,000 bytes of data of various data types, except text, ntext, and timestamp

Uniqueidentifier Stores a globally unique identifier (GUID)

Xml Stores XML formatted data. Maximum 2GB

Cursor Stores a reference to a cursor used for database operations

Table Stores a result-set for later processing

SQL Quick Reference


SQL Statement Syntax

AND / OR SELECT column_name(s)


FROM table_name
WHERE condition
AND|OR condition

ALTER TABLE ALTER TABLE table_name


ADD column_name datatype

or

ALTER TABLE table_name


DROP COLUMN column_name
AS (alias) SELECT column_name AS column_alias
FROM table_name
or

SELECT column_name
FROM table_name AStable_alias
BETWEEN SELECT column_name(s)
FROM table_name
WHERE column_name
BETWEEN value1 AND value2
CREATE DATABASE CREATE DATABASE database_name
CREATE TABLE CREATE TABLE table_name
(
column_name1 data_type,
column_name2 data_type,
column_name3 data_type,
...
)
CREATE INDEX CREATE INDEX index_name
ON table_name (column_name)

or

CREATE UNIQUE INDEX index_name


ON table_name (column_name)
CREATE VIEW CREATE VIEW view_name AS
SELECT column_name(s)
FROM table_name
WHERE condition
DELETE DELETE FROM table_name
WHERE some_column=some_value

or

DELETE FROM table_name


(Note: Deletes the entire table!!)

DELETE * FROM table_name


(Note: Deletes the entire table!!)
DROP DATABASE DROP DATABASE database_name
DROP INDEX DROP INDEX table_name.index_name (SQL Server)
DROP INDEX index_name ON table_name (MS Access)
DROP INDEX index_name (DB2/Oracle)
ALTER TABLE table_name
DROP INDEX index_name (MySQL)
DROP TABLE DROP TABLE table_name
EXISTS IF EXISTS (SELECT * FROM table_name WHERE id = ?)
BEGIN
--do what needs to be done if exists
END
ELSE
BEGIN
--do what needs to be done if not
END
GROUP BY SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value
IN SELECT column_name(s)
FROM table_name
WHERE column_name
IN (value1,value2,..)
INSERT INTO INSERT INTO table_name
VALUES (value1, value2, value3,....)

or

INSERT INTO table_name


(column1, column2, column3,...)
VALUES (value1, value2, value3,....)
INNER JOIN SELECT column_name(s)
FROM table_name1
INNER JOIN table_name2
ON table_name1.column_name=table_name2.column_name
LEFT JOIN SELECT column_name(s)
FROM table_name1
LEFT JOIN table_name2
ON table_name1.column_name=table_name2.column_name
RIGHT JOIN SELECT column_name(s)
FROM table_name1
RIGHT JOIN table_name2
ON table_name1.column_name=table_name2.column_name
FULL JOIN SELECT column_name(s)
FROM table_name1
FULL JOIN table_name2
ON table_name1.column_name=table_name2.column_name
LIKE SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern
ORDER BY SELECT column_name(s)
FROM table_name
ORDER BY column_name [ASC|DESC]
SELECT SELECT column_name(s)
FROM table_name
SELECT * SELECT *
FROM table_name
SELECT DISTINCT SELECT DISTINCT column_name(s)
FROM table_name
SELECT INTO SELECT *
INTO new_table_name [IN externaldatabase]
FROM old_table_name

or

SELECT column_name(s)
INTO new_table_name [IN externaldatabase]
FROM old_table_name
SELECT TOP SELECT TOP number|percentcolumn_name(s)
FROM table_name
TRUNCATE TABLE TRUNCATE TABLE table_name
UNION SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2
UNION ALL SELECT column_name(s) FROM table_name1
UNION ALL
SELECT column_name(s) FROM table_name2
UPDATE UPDATE table_name
SET column1=value, column2=value,...
WHERE some_column=some_value
WHERE SELECT column_name(s)
FROM table_name
WHERE column_name operator value
Different Types of SQL Server Functions
Function is a database object in Sql Server. Basically, it is a set of sql statements
that accepts only input parameters, perform actions and return the result.
Function can return only single value or a table. We can’t use function to Insert,
Update, Delete records in the database table(s).

Types of Function
1. System Defined Function
These functions are defined by Sql Server for different purpose. We have two types of system defined function in Sql
Server

1. Scalar Function
Scalar functions operate on a single value and returns a single value. Below is the list of some useful Sql Server Scalar
functions.

System Scalar Function

Scalar Function

Description

abs(-10.67)

This returns absolute number of the given number means 10.67.

rand(10)

This will generate random number of 10 characters.

round(17.56719,3)

This will round off the given number to 3 places of decimal means 17.567
upper('dotnet')

This will returns upper case of given string means 'DOTNET'

lower('DOTNET')

This will returns lower case of given string means 'dotnet'

ltrim(' dotnet')

This will remove the spaces from left hand side of 'dotnet' string.

convert(int, 15.56)

This will convert the given float value to integer means 15.

2. Aggregate Function
Aggregate functions operate on a collection of values and returns a single value. Below is the list of some useful Sql
Server Aggregate functions.

System Aggregate Function

Aggregate Function

Description

max()

This returns maximum value from a collection of values.

min()

This returns minimum value from a collection of values.

avg()

This returns average of all values in a collection.

count()

This returns no of counts from a collection of values.

2. User Defined Function


These functions are created by user in system database or in user defined database. We create three types of user
defined functions.

1. Scalar Function
User defined scalar function also returns single value as a result of actions perform by function. We return any
datatype value from function.
1.
1. --Create a table
2. CREATETABLE Employee
3. (
4. EmpID int PRIMARYKEY,
5. FirstName varchar(50)NULL,
6. LastNamevarchar(50)NULL,
7. Salary int NULL,
8. Address varchar(100)NULL,
9. )
10. --Insert Data
11. InsertintoEmployee(EmpID,FirstName,LastName,Salary,Address)Values(1,'Mohan','Chauah
n',22000,'Delhi');
12. InsertintoEmployee(EmpID,FirstName,LastName,Salary,Address)Values(2,'Asif','Khan',1
5000,'Delhi');
13. InsertintoEmployee(EmpID,FirstName,LastName,Salary,Address)Values(3,'Bhuvnesh','Sha
kya',19000,'Noida');
14. InsertintoEmployee(EmpID,FirstName,LastName,Salary,Address)Values(4,'Deepak','Kumar
',19000,'Noida');
15. --See created table
16. Select*from Employee

2.
1. --Create function to get emp full name
2. CreatefunctionfnGetEmpFullName
3. (
4. @FirstName varchar(50),
5. @LastName varchar(50)
6. )
7. returns varchar(101)
8. As
9. Beginreturn(Select@FirstName +' '+@LastName);
10. end

3.
1. --Calling the above created function
2. Selectdbo.fnGetEmpFullName(FirstName,LastName)as Name, Salary from Employee

2. Inline Table-Valued Function


User defined inline table-valued function returns a table variable as a result of actions perform by function. The value
of table variable should be derived from a single SELECT statement.
1.
1. --Create function to get employees
2. CreatefunctionfnGetEmployee()
3. returns Table
4. As
5. return(Select*from Employee)
2.
1. --Now call the above created function
2. Select*fromfnGetEmployee()

3. Multi-Statement Table-Valued Function


User defined multi-statement table-valued function returns a table variable as a result of actions perform by function.
In this a table variable must be explicitly declared and defined whose value can be derived from a multiple sql
statement.
1.
1. --Create function for EmpID,FirstName and Salary of Employee
2. CreatefunctionfnGetMulEmployee()
3. returns @Emp Table
4. (
5. EmpID int,
6. FirstName varchar(50),
7. Salary int
8. )
9. As
10. begin
11. Insertinto@Emp Selecte.EmpID,e.FirstName,e.Salaryfrom Employee e;
12. --Now update salary of first employee
13. update@Emp set Salary=25000whereEmpID=1;
14. --It will update only in @Emp table not in Original Employee table
15. return
16. end

2.
1. --Now call the above created function
2. Select*fromfnGetMulEmployee()

3.
1. --Now see the original table. This is not affected by above function update command
2. Select*from Employee
Note
1. Unlike Stored Procedure, Function returns only single value.
2. Unlike Stored Procedure, Function accepts only input parameters.
3. Unlike Stored Procedure, Function is not used to Insert, Update, Delete data in database table(s).
4. Like Stored Procedure, Function can be nested up to 32 level.
5. User Defined Function can have upto 1023 input parameters while a Stored Procedure can have upto 2100 input
parameters.
6. User Defined Function can't returns XML Data Type.
7. User Defined Function doesn't support Exception handling.
8. User Defined Function can call only Extended Stored Procedure.
9. User Defined Function doesn't support set options like set ROWCOUNT etc.
Sql Server - Stored Procedure
Stored Procedure: Stored Procedure in SQL Server can be defined as the set of logical groups of SQL statements
which are grouped to perform a specific task. There are many benefits of using a stored procedure. The main benefit of
using a stored procedure is that it increases the performance of the database.The other benefits of using the Stored
Procedure are given below.

Benefits of Using the Stored Procedure


1. One of the main benefits of using the Stored procedure is that it reduces the amount of information sent to the
database server. It can become
2. is created. Then after it does not require recompilation before executing unless it is modified and reutilizes the same
execution plan whereas the SQL statements need to be compiled every time whenever it is sent for execution even if
we send the same SQL statement every time.
3. It helps in re usability of the SQL code because it can be used by multiple users and by multiple clients since we need
to just call the stored procedure instead of writing the same SQL statement every time. It helps in reducing the
development time.
4. Stored procedure is helpful in enhancing the security since we can grant permission to the user for executing the
Stored procedure instead of giving permission on the tables a more important benefit when the bandwidth of the
network is less. Since if we send the SQL query (statement) which is executing in a loop to the server through network
and the network gets disconnected, then the execution of the SQL statement doesn't return the expected results, if
the SQL query is not used between Transaction statement and rollback statement is not used.
5. Compilation step is required only once when the stored procedure used in the Stored procedure.
6. Sometimes, it is useful to use the database for storing the business logic in the form of stored procedure since it makes
it secure and if any change is needed in the business logic, then we may only need to make changes in the stored
procedure and not in the files contained on the web server.

How to Write a Stored Procedure in SQL Server


Now, while writing a Stored Procedure, the first step will be to write the Create Procedure statement as the
first statement:

Hide Copy Code

CreateProcedure Procedure-name
(
Input parameters,
Output Parameters (If required)
)
As
Begin
Sql statement used in the stored procedure
End

Now, suppose we need to create a Stored Procedure which will return a student name whose studentid is
given as the input parameter to the stored procedure. Then, the Stored Procedure will be:

Hide Copy Code

/* Getstudentname is the name of the stored procedure*/

CreatePROCEDUREGetstudentname(
@studentidINT--Input parameter ,Studentid of the student

)
AS
BEGIN
SELECTFirstname+' '+LastnameFROMtbl_StudentsWHEREstudentid=@studentid
END

We can also collect the student name in the output parameter of the Stored Procedure. For example:

Hide Copy Code

/*
GetstudentnameInOutputVariable is the name of the stored procedure which
uses output variable @Studentname to collect the student name returns by the
stored procedure
*/

CreatePROCEDUREGetstudentnameInOutputVariable
(

@studentidINT, --Input parameter , Studentid of the student


@studentnameVARCHAR(200) OUT -- Out parameter declared with the help of OUT
keyword
)
AS
BEGIN
SELECT @studentname= Firstname+'
'+LastnameFROMtbl_StudentsWHEREstudentid=@studentid
END

How to Alter a Stored Procedure in a SQL Server


Alter keyword. Now if we want to
In SQL Server, a stored procedure can be modified with the help of the
get student email address through the same procedure GetstudentnameInOutputVariable. So
we need to modify it by adding one more output parameter " @StudentEmail " which is shown below:
Hide Copy Code

/*
Stored Procedure GetstudentnameInOutputVariable is modified to collect the
email address of the student with the help of the Alert Keyword
*/

AlterPROCEDUREGetstudentnameInOutputVariable
(

@studentidINT, --Input parameter , Studentid of the student


@studentnameVARCHAR (200) OUT, -- Output parameter to collect the student name
@StudentEmailVARCHAR (200)OUT-- Output Parameter to collect the student email
)
AS
BEGIN
SELECT @studentname= Firstname+' '+Lastname,
@StudentEmail=email FROMtbl_StudentsWHEREstudentid=@studentid
END
Note: It is not necessary that a stored procedure will have to return. There can be a case when a stored procedure
doesn't returns anything. For example, a stored procedure can be used to Insert, delete or update a SQL
statement. For example, the below stored procedure is used to insert value into the table tbl_students.
Hide Copy Code

/*
This Stored procedure is used to Insert value into the table tbl_students.
*/
CreateProcedureInsertStudentrecord
(
@StudentFirstNameVarchar(200),
@StudentLastNameVarchar(200),
@StudentEmailVarchar(50)
)
As
Begin
Insertintotbl_Students (Firstname, lastname, Email)
Values(@StudentFirstName, @StudentLastName,@StudentEmail)
End

Execution of the Stored Procedure in SQL Server


Execution of the Stored Procedure which doesn't have an Output Parameter
A stored procedure is used in the SQL Server with the help of the " Execute" or "Exec" Keyword. For example, if
we want to execute the stored procedure "Getstudentname", then we will use the following statement.
Hide Copy Code

ExecuteGetstudentname1
ExecGetstudentname1

Execution of the Stored Procedure using the Output Parameter


If we want to execute the Stored procedure "GetstudentnameInOutputVariable" , then we first need
to declare the variable to collect the output values. For example:
Hide Copy Code

Declare@Studentnameasnvarchar(200) -- Declaring the variable to collect the


Studentname
Declare@Studentemailasnvarchar(50) -- Declaring the variable to collect the
Studentemail
ExecuteGetstudentnameInOutputVariable1 ,@Studentname output, @Studentemail output
select@Studentname,@Studentemail-- "Select" Statement is used to show the output
from Procedure

SQL Server Insert, Retrieve, Update, Delete Operations


using Stored Procedures
In database, you need to do Insert, Update and Delete. If we want to make a reliable and high-performance system
then these four operations must be implemented by stored procedures. Stored procedure also prevents Sql Injection
attacks and reduce network traffic.

Insert Operation
We can insert records into the table(s) using stored procedure by passing data in input parameters. Below code is used
to insert record in the table "Employee" using stored procedure

1.
1. CREATETABLE Employee
2. (
3. EmpID int primarykey, Name varchar(50),
4. Salary int,
5. Address varchar(100)
6. )
1.
1. InsertintoEmployee(EmpID,Name,Salary,Address)Values(1,'Mohan',16000,'Delhi')
2. InsertintoEmployee(EmpID,Name,Salary,Address)Values(2,'Asif',15000,'Delhi')
3. InsertintoEmployee(EmpID,Name,Salary,Address)Values(3,'Bhuvnesh',19000,'Noida')
4. --See table
5. SELECT*FROM Employee

1.
1. CREATEPROCEDUREusp_InsertEmployee
2. @flag bit output,-- return 0 for fail,1 for success
3. @EmpID int,
4. @Name varchar(50),
5. @Salary int,
6. @Address varchar(100)
7. AS
8. BEGIN
9. BEGINTRANSACTION
10. BEGIN TRY
11. InsertintoEmployee(EmpID,Name,Salary,Address)Values(@EmpID,@Name,@Salary,@Address)
12. set@flag=1;
13. IF@@TRANCOUNT >0
14. BEGINcommitTRANSACTION;
15. END
16. END TRY
17. BEGIN CATCH
18. IF@@TRANCOUNT >0
19. BEGINrollbackTRANSACTION;
20. END
21. set@flag=0;
22. END CATCH
23. END

1.
1. --Execute above created procedure to insert rows into table
2. Declare@flag bit
3. EXECusp_InsertEmployee@flag output,1,'Deepak',14000,'Noida'
4. if@flag=1
5. print'Successfully inserted'
6. else
7. print'There is some error'

1.
1. --Execute above created procedure to insert rows into table
2. Declare@flag bit
3. EXECusp_InsertEmployee@flag output,4,'Deepak',14000,'Noida'
4. if@flag=1
5. print'Successfully inserted'
6. else
7. print'There is some error'
1.
1. --now see modified table
2. Select*from Employee

Retrieve Operation
We can retrieve data from one or more tables/views with the help of join, using stored procedure. We can put multiple
sql statements with in a single stored procedure. Below code is used to fetch data from a table "Employee" using
stored procedure

1.
1. -- first we Insert data in the table
2. InsertintoEmployee(EmpID,Name,Salary,Address)Values(1,'Mohan',16000,'Delhi')
3. InsertintoEmployee(EmpID,Name,Salary,Address)Values(2,'Asif',15000,'Delhi')
4. InsertintoEmployee(EmpID,Name,Salary,Address)Values(3,'Bhuvnesh',19000,'Noida')
5. go
6. --Now we create a procedure to fetch data
7. CREATEPROCEDUREusp_SelectEmployee
8. As
9. Select*from Employee ORDERByEmpID

1.
1. --Execute above created procedure to fetch data
2. execusp_SelectEmployee

Update Operation
We can update records of the table(s) using stored procedure by passing data in input parameters. Below code is used
to update a table "Employee" using stored procedure

1.
1. CREATEPROCEDUREusp_UpdateEmployee
2. @flag bit output,-- return 0 for fail,1 for success
3. @EmpID int,
4. @Salary int,
5. @Address varchar(100)
6. AS
7. BEGIN
8. BEGINTRANSACTION
9. BEGIN TRY
10. Update Employee set Salary=@Salary, Address=@Address
11. WhereEmpID=@EmpID
12. set@flag=1;
13. IF@@TRANCOUNT >0
14. BEGINcommitTRANSACTION;
15. END
16. END TRY
17. BEGIN CATCH
18. IF@@TRANCOUNT >0
19. BEGINrollbackTRANSACTION;
20. END
21. set@flag=0;
22. END CATCH
23. END

1.
1. --Execute above created procedure to update table
2. Declare@flag bit
3. EXECusp_UpdateEmployee@flag output,1,22000,'Noida'
4. if@flag=1print'Successfully updated'
5. else
6. print'There is some error'

1.
1. --now see updated table
2. Select*from Employee

Delete Operation
We can delete records of the table(s) using stored procedure by passing data in input parameters. Below code is used
to update a table "Employee" using stored procedure

1.
1. CREATEPROCEDUREusp_DeleteEmployee
2. @flag bit output,-- return 0 for fail,1 for success
3. @EmpID int
4. AS
5. BEGIN
6. BEGINTRANSACTION
7. BEGIN TRY
8. Deletefrom Employee WhereEmpID=@EmpID set@flag=1;
9. IF@@TRANCOUNT >0
10. BEGINcommitTRANSACTION;
11. END
12. END TRY
13. BEGIN CATCH
14. IF@@TRANCOUNT >0
15. BEGINrollbackTRANSACTION;
16. END
17. set@flag=0;
18. END CATCH
19. END

1.
1. --Execute above created procedure to delete rows from table
2. Declare@flag bit
3. EXECusp_DeleteEmployee@flag output,4
4. if@flag=1
5. print'Successfully deleted'
6. else
7. print'There is some error'

1.
1. --now see modified table
2. Select*from Employee

Note
1. In stored procedure we use output parameter to return multiple values.
2. Generally we use output parameter in stored procedure to get status of the operation as I used above "@flag" output
parameter to get operations status whether these are successfully executed or not.
Temporary Table in SQL Server
Introduction

A temporary table is one of the best features of SQL Server. If you want to perform a large amount of operations in SQL or work on a
large query of SQL then you need to store some data or maybe a table of data for the operation. To store a large amount of data we
can create a temporary table and store the table with for some period of time.

You can perform any type of operation like insert, update, delete, selection, join and so on. One of the best features of a temporary
table is you can store temporary data inside it and the temporary table will be automatically deleted when the current client session is
terminated.

Types of Temporary table

The following are the 2 kinds of temporary tables available:

1. Local Temporary Table: These are only available for the current instance; it will be automatically deleted when the user is
disconnected from the instance. To create a local temporary table, we use the table name with a # (hash) prefix.
2. Global Temporary Table: This table is the same as a permanent table but the difference is only that when all the
connections are closed or all the instances are deleted then the table will be deleted. To create a globaltemporary table, we
use a table name with a ## (double hash) prefix.

How to create temporary tables

As we know, there are two types of temporary tables, global and local.

Local Temporary Table

To create a local temporary table as I described we will use "# symbol" so the syntax of the local temporary table is:

create table #<Table_Name> (


<Column_Name> [datatype](size),
<Column_Name> [datatype](size), ........
)

For Example

create table #Example_Table (


id int,
Name varchar (20)
)
Now after creating this table you can see your table is available inside "System Databases >tempdb> Temporary Tables" so go to the
Object Explorer and check it there.

Perform any operation inside it like insert, update, delete. like:

insert into #Example_Table values(1,'Sourabh Somani')


insert into #Example_Table values(2,'Shaili Dashora')
insert into #Example_Table values(3,'Divya Sharma')
insert into #Example_Table values(4,'Swati Soni')

After performing all the operations, to see the data write:

select * from #Example_Table


Note: between all the operations the table is not deleted, but when you close this tab or instance the table will not be there.

For Example

After closing it refresh the object browser and your table will be deleted.
Global Temporary Table

To create a global temporary table as I said we use "## symbol" so the syntax of the local temporary table is:

create table ##<Table_Name>(


<Column_Name> [datatype](size),
<Column_Name> [datatype](size), ........
)

For Example

create table ##Example_Table(


id int,
Name varchar (20)
)

Note: This table is a global temporary table so it will be deleted when all the instances or the session that was created are closed.

The need for temporary tables are:

1. When Many operations are performed in a single or multiple table.


2. When many manipulations are done on a row in a Stored Procedure.
3. When we have a complex join operation.

Key Points

1. Temporary Tables exist at Databases > System Databases >tempdb> Temporary Tables
2. Temporary tables are automatically deleted; there is no need to delete them explicitly when you are working.
Understanding Case Expression in SQL Server with
Example
Sometimes, you required to fetch or modify the records based on some conditions. In this case, you may
use cursor or loop for modify your records. In this situation Case expression is best alternative for
Cursor/looping and also provides better performance.
You can use CASE expressions anywhere in the SQL Query like CASE expressions can be used with in
SELECT statement, WHERE clauses, Order by clause, HAVING clauses, Insert, UPDATE and DLETE
statements.

Format of CASE expression


The CASE expression has following two formats:

1. Simple CASE expression


This compares an expression to a set of simple expressions to find the result. This expression
compares an expression to the expression in each WHEN clause for equivalency. If the expression
with in the WHEN clause is matched, the expression in the THEN clause will be returned.

Syntax
1. CASE expression
2. WHEN expression1 THEN Result1
3. WHEN expression2 THEN Result2
4. ELSE ResultN
5. END

2. Searched CASE expressions


This expression evaluates a set of Boolean expressions to find the result. This expression allows
comparison operators, and logical operators AND/OR with in each Boolean expression.

Syntax
1. CASE
2. WHEN Boolean_expression1 THEN Result1
3. WHEN Boolean_expression2 THEN Result2
4. ELSE ResultN
5. END

CASE Expression Example


1. CREATE TABLE dbo.Customer
2. (
3. CustID INT IDENTITY PRIMARY KEY,
4. FirstNameVARCHAR(40) NOT NULL,
5. LastNameVARCHAR(40) NOT NULL,
6. StateCodeVARCHAR(20) NOT NULL,
7. PayRate money NOT NULL DEFAULT 0.00,
8. GenderVARCHAR(1) NOT NULL,
9. )
10. GO
11.
12. INSERT INTO dbo.Customer(FirstName,LastName,StateCode,PayRate,Gender)
13. VALUES('Tejendra','Kumar','UP',150.00,'M')
14.
15. INSERT INTO dbo.Customer(FirstName,LastName,StateCode,PayRate,Gender)
16. VALUES('Jolly','Kapoor','MP',50.00,'F')
17.
18. INSERT INTO dbo.Customer(FirstName,LastName,StateCode,PayRate,Gender)
19. VALUES('Pavan','Kumar','MP',200.00,'M')
20.
21. INSERT INTO dbo.Customer(FirstName,LastName,StateCode,PayRate,Gender)
22. VALUES('Boby','Sharma','DL',180.00,'F')
23.
24. INSERT INTO dbo.Customer(FirstName,LastName,StateCode,PayRate,Gender)
25. VALUES('Asif','Khan','DL',210.00,'M')
26. GO
27.
28. SELECT *fromCustomer

SELECT statement with CASE expressions


1. --Simple CASE expression:
2. SELECT FirstName,State=(CASE StateCode
3. WHEN 'MP' THEN 'Madhya Pradesh'
4. WHEN 'UP' THEN 'Uttar Pradesh'
5. WHEN 'DL' THEN 'Delhi'
6. ELSE NULL
7. END),PayRate
8. FROM dbo.Customer
9.
10. --Searched CASE expression:
11. SELECT FirstName,State=(CASE
12. WHEN StateCode='MP' THEN 'Madhya Pradesh'
13. WHEN StateCode='UP' THEN 'Uttar Pradesh'
14. WHEN StateCode='DL' THEN 'Delhi'
15. ELSE NULL
16. END),PayRate
17. FROM dbo.Customer

Update statement with CASE expression


1. --Simple CASE expression:
2. UPDATE Customer
3. SET StateCode= CASE StateCode
4. WHEN 'MP' THEN 'Madhya Pradesh'
5. WHEN 'UP' THEN 'Uttar Pradesh'
6. WHEN 'DL' THEN 'Delhi'
7. ELSE NULL
8. END
9.
10. --Simple CASE expression:
11. UPDATE Customer
12. SET StateCode= CASE
13. WHEN StateCode='MP' THEN 'Madhya Pradesh'
14. WHEN StateCode='UP' THEN 'Uttar Pradesh'
15. WHEN StateCode='DL' THEN 'Delhi'
16. ELSE NULL
17. END
ORDER BY clause with CASE expressions
1. --Simple CASE expression:
2. SELECT * FROM dbo.Customer
3. ORDER BY
4. CASE Gender WHEN 'M' THEN FirstNameENDDesc,
5. CASE Gender WHEN 'F' THEN LastNameEND ASC
6.
7. --Searched CASE expression:
8. SELECT * FROM dbo.Customer
9. ORDER BY
10. CASE WHEN Gender='M' THEN FirstNameENDDesc,
11. CASE WHEN Gender='F' THEN LastNameEND ASC

Having Clause with CASE expression


1. --Simple CASE expression:
2. SELECT FirstName, StateCode,Gender,Total=MAX(PayRate)
3. FROM dbo.Customer
4. GROUP BY StateCode,Gender,FirstName
5. HAVING (MAX(CASE Gender WHEN 'M'
6. THEN PayRate
7. ELSE NULL END)>180.00
8. OR MAX(CASE Gender WHEN 'F'
9. THEN PayRate
10. ELSE NULL END)>170.00)
11.
12. --Searched CASE expression:
13. SELECT FirstName,StateCode,Gender,Total=MAX(PayRate)
14. FROM dbo.Customer
15. GROUP BY StateCode,Gender,FirstName
16. HAVING (MAX(CASE WHEN Gender='M'
17. THEN PayRate
18. ELSE NULL END)>180.00
19. OR MAX(CASE WHEN Gender='F'
20. THEN PayRate
21. ELSE NULL END)>170.00)
Pivot and Unpivot In SQL Server
PIVOT and UNPIVOT are two relational operators that are used to convert a table expression into another. PIVOT is used when we
want to transfer data from row level to column level and UNPIVOT is used when we want to convert data from column level to row level.
PIVOT and UNPIVOT relational operators are used to generate a multidimensional reporting. Today we will discuss both the operators.
PIVOT and UNPIVOT relational operators are used to generate an interactive table that quickly combines and compares large amount
of data.

Firstly, we will create a table and insert some data into the table.

Firstly, create an Employee Table

1. CREATE TABLE Employee


2. (
3. Name [nvarchar](max),
4. [Year] [int],
5. Sales [int]
6. )

Insert the following data into the table

1. INSERT INTO Employee


2. SELECT 'Pankaj',2010,72500 UNION ALL
3. SELECT 'Rahul',2010,60500 UNION ALL
4. SELECT 'Sandeep',2010,52000 UNION ALL
5. SELECT 'Pankaj',2011,45000 UNION ALL
6. SELECT 'Sandeep',2011,82500 UNION ALL
7. SELECT 'Rahul',2011,35600 UNION ALL
8. SELECT 'Pankaj',2012,32500 UNION ALL
9. SELECT 'Pankaj',2010,20500 UNION ALL
10. SELECT 'Rahul',2011,200500 UNION ALL
11. SELECT 'Sandeep',2010,32000

Now we check data of Employee table.

1. SELECT * FROM Employee;

Output

We use above Employee table for PIVOT and UNPIVOT relational operator examples. First we read about PIVOT realational operator.

PIVOT

PIVOT relational operator convert data from row level to column level. PIVOT rotates a table-valued expression by turning the unique
values from one column in the expression into multiple columns in the output. Using PIVOT operator we can perform aggregate
operation where we required.

Syntax

1. SELECT <non-pivoted column>,


2. <list of pivoted column>
3. FROM
4. (<SELECT query to produces the data>)
5. AS <alias name>
6. PIVOT
7. (
8. <aggregation function>(<column name>)
9. FOR
10. [<column name that become column headers>]
11. IN ( [list of pivoted columns])
12.
13. ) AS <alias name for pivot table>

Let us take some examples.

Example 1

1. SELECT [Year], Pankaj,Rahul,Sandeep FROM


2. (SELECT Name, [Year] , Sales FROM Employee )Tab1
3. PIVOT
4. (
5. SUM(Sales) FOR Name IN (Pankaj,Rahul,Sandeep)) AS Tab2
6. ORDER BY [Tab2].[Year]

Output:

In above query we calculate the sum of sales for Pankaj, Rahul and Sandeep employee corresponding to year value.

Example 2

1. SELECT Name, 2010,2011,2012 FROM


2. (SELECT Name, [Year] , Sales FROM Employee )Tab1
3. PIVOT
4. (
5. SUM(Sales) FOR [Year] IN (2010,2011,2012)) AS Tab2
6. ORDER BY Tab2.Name

Output:

When we execute above query, SQL Server throws an error because we can’t provide integer value as a column name directly. To
remove this error use the brackets before each integer value as in the following code snippet:

1. SELECT Name, [2010],[2011],[2012] FROM


2. (SELECT Name, [Year] , Sales FROM Employee )Tab1
3. PIVOT
4. (
5. SUM(Sales) FOR [Year] IN ([2010],[2011],[2012])) AS Tab2
6. ORDER BY Tab2.Name

Output
Example 3

In previous examples we wrote the name of pivot column. This approach is useful if we know all possible values for pivot column. But it
is not fix that column always remain same, pivot column may be increased or decreased in future.

Let us take previous example. In previous example we wrote 2010,2011 and 2012 as pivot column. But it is not fix that these column will
not change in future , so what should we do if there is a possibility that column number may change in future.

In such a condition we should use dynamic query. Firstly, retrieve all unique values from pivot column and after that write a dynamic
query to execute it with pivot query at run time.

Now we execute example 2, but using dynamic query.

1. /*Declare Variable*/
2. DECLARE @Pivot_Column [nvarchar](max);
3. DECLARE @Query [nvarchar](max);
4.
5. /*Select Pivot Column*/
6. SELECT @Pivot_Column= COALESCE(@Pivot_Column+',','')+ QUOTENAME(Year) FROM
7. (SELECT DISTINCT [Year] FROM Employee)Tab
8.
9. /*Create Dynamic Query*/
10. SELECT @Query='SELECT Name, '+@Pivot_Column+'FROM
11. (SELECT Name, [Year] , Sales FROM Employee )Tab1
12. PIVOT
13. (
14. SUM(Sales) FOR [Year] IN ('+@Pivot_Column+')) AS Tab2
15. ORDER BY Tab2.Name'
16.
17. /*Execute Query*/
18. EXEC sp_executesql @Query

Output

UNPIVOT

UNPIVOT relational operator is reverse process of PIVOT relational operator. UNPIVOT relational operator convert data from column
level to row level.

Example 4:

Suppose that output of example 2 is stored in Temp Variable. Now we want to rotate column identifiers Pankaj, Sandeep, Rahul into
row values. For this we use the UNPIVOT relational operator.

Declare Temp Variable

1. DECLARE @Tab TABLE


2. (
3. [Year] int,
4. Pankaj int,
5. Rahul int,
6. Sandeep int
7. )

Insert Value in Temp Variable


1. INSERT INTO @Tab
2. SELECT [Year], Pankaj,Rahul,Sandeep FROM
3. (SELECT Name, [Year] , Sales FROM Employee )Tab1
4. PIVOT
5. (
6. SUM(Sales) FOR Name IN (Pankaj,Rahul,Sandeep)) AS Tab2
7. ORDER BY [Tab2].[Year]

Perform UNPIVOT Operation

1. SELECT Name,[Year] , Sales FROM @Tab t


2. UNPIVOT
3. (
4. Sales FOR Name IN (Pankaj,Rahul,Sandeep)
5. ) AS TAb2

Output

We can perform first PIVOT operation and after that UNPIVOT operation on same table in single query as in the following code snippet.

1. SELECT Name,[Year] , Sales FROM


2. (
3. SELECT [Year], Pankaj,Rahul,Sandeep FROM
4. (SELECT Name, [Year] , Sales FROM Employee )Tab1
5. PIVOT
6. (
7. SUM(Sales) FOR Name IN (Pankaj,Rahul,Sandeep)) AS Tab2
8. )Tab
9. UNPIVOT
10. (
11. Sales FOR Name IN (Pankaj,Rahul,Sandeep)
12. ) AS TAb2

Output

Note

UNPIVOT operation is a reverse process of PIVOT operation, but UNPIVOT is not the exact reverse of PIVOT. If PIVOT performs an
aggregation and merges multiple rows into a single row in the output, then UNPIVOT can’t reproduce the original table-valued
expression result because rows have been merged. So conclusion is that if PIVOT operation merges multiple row in a single row, then
UNPIVOT operation can’t retrieve original table from the output of PIVOT operation. But if PIVOT operation doesn’t merge multiple row
in a single row, then UNPIVOT operation can retrieve original table from the output of PIVOT operation.

Let us take an example

Case 1(PIVOT Merger Multiple Row) :


Now we perform PIVOT and UNPIVOT operation for this table and compare the resultant table from this table.

1. SELECT Name,[Year] , Sales FROM


2. (
3. SELECT [Year], Pankaj,Rahul,Sandeep FROM
4. (SELECT Name, [Year] , Sales FROM Employee )Tab1
5. PIVOT
6. (
7. SUM(Sales) FOR Name IN (Pankaj,Rahul,Sandeep)) AS Tab2
8. )Tab
9. UNPIVOT
10. (
11. Sales FOR Name IN (Pankaj,Rahul,Sandeep)
12. ) AS TAb2

Output

We can see that both the tables are not same. First table contain 10 rows but the above table contains only 7 rows. This difference
occur due to the PIVOT operation. PIVOT operation merge the (4,7,8) row in a single row and merge the (3,5) row in a single row. So
UNPIVOT operation can’t retrieve original table.

Case 2(PIVOT doesn’t Merger Multiple Row)

Now we perform PIVOT and UNPIVOT operation for this table and compare the resultant table from this table.

1. SELECT Name,[Year] , Sales FROM


2. (
3. SELECT [Year], Pankaj,Rahul,Sandeep FROM
4. (SELECT Name, [Year] , Sales FROM Employee )Tab1
5. PIVOT
6. (
7. SUM(Sales) FOR Name IN (Pankaj,Rahul,Sandeep)) AS Tab2
8. )Tab
9. UNPIVOT
10. (
11. Sales FOR Name IN (Pankaj,Rahul,Sandeep)
12. ) AS TAb2

Output

We can see that both the tables are same.


Difference between CTE and Temp
Table and Table Variable
Temp Table or Table variable or CTE are commonly used for storing data
temporarily in SQL Server. In this article, you will learn the differences
among these three.

CTE
CTE stands for Common Table expressions. It was introduced with SQL
Server 2005. It is a temporary result set and typically it may be a result of
complex sub-query. Unlike temporary table its life is limited to the current
query. It is defined by using WITH statement. CTE improves readability
and ease in maintenance of complex queries and sub-queries. Always
begin CTE with semicolon.

A sub query without CTE is given below


:
1. SELECT * FROM (
2. SELECT Addr.Address,Emp.Name,Emp.AgeFromAddressAddr
3. InnerjoinEmployeeEmp on Emp.EID=Addr.EID)Temp
4. WHERE Temp.Age>50
5. ORDER BY Temp.NAME

By using CTE above query can be re-


written as follows :
1. ;With CTE1(Address,Name,Age)--Column names for CTE, which are optional
2. AS
3. (
4. SELECT Addr.Address,Emp.Name,Emp.AgefromAddressAddr
5. INNER JOIN EMP Emp ON Emp.EID=Addr.EID
6. )
7. SELECT * FROM CTE1 --Using CTE
8. WHERE CTE1.Age>50
9. ORDER BY CTE1.NAME

When to use CTE


1. This is used to store result of a complex sub query for further use.
2. This is also used to create a recursive query.

Temporary Tables
In SQL Server, temporary tables are created at run-time and you can do
all the operations which you can do on a normal table. These tables are
created inside Tempdb database. Based on the scope and behavior
temporary tables are of two types as given below-

1. Local Temp Table

Local temp tables are only available to the SQL Server session or
connection (means single user) that created the tables. These are
automatically deleted when the session that created the tables has
been closed. Local temporary table name is stared with single hash
("#") sign.
1. CREATE TABLE #LocalTemp
2. (
3. UserIDint,
4. Namevarchar(50),
5. Addressvarchar(150)
6. )
7. GO
8. insert into#LocalTemp values ( 1, 'Shailendra','Noida');
9. GO
10. Select*from#LocalTemp

The scope of Local temp table exist to the current session of current
user means to the current query window. If you will close the current
query window or open a new query window and will try to find above
created temp table, it will give you the error.

2. Global Temp Table

Global temp tables are available to all SQL Server sessions or


connections (means all the user). These can be created by any SQL
Server connection user and these are automatically deleted when all
the SQL Server connections have been closed. Global temporary table
name is stared with double hash ("##") sign.
1. CREATE TABLE ##GlobalTemp
2. (
3. UserIDint,
4. Namevarchar(50),
5. Addressvarchar(150)
6. )
7. GO
8. insert into##GlobalTemp values ( 1,
'Shailendra','Noida');
9. GO
10. Select*from##GlobalTemp
11.

Global temporary tables are visible to all SQL Server connections while
Local temporary tables are visible to only current SQL Server
connection.

Table Variable
This acts like a variable and exists for a particular batch of query
execution. It gets dropped once it comes out of batch. This is also created
in the Tempdb database but not the memory. This also allows you to
create primary key, identity at the time of Table variable declaration but
not non-clustered index.
1. GO
2. DECLARE @TProduct TABLE
3. (
4. SNo INT IDENTITY(1,1),
5. ProductID INT,
6. Qty INT
7. )
8. --Insert data to Table variable @Product
9. INSERT INTO @TProduct(ProductID,Qty)
10. SELECT DISTINCT ProductID,Qty FROM ProductsSales ORDER BY ProductID
ASC
11. --Select data
12. Select*from@TProduct
13.
14. --Next batch
15. GO
16. Select*from@TProduct--gives error innext batch
17.

Note
1. Temp Tables are physically created in the Tempdb database. These tables act as the
normal table and also can have constraints, index like normal tables.
2. CTE is a named temporary result set which is used to manipulate the complex sub-
queries data. This exists for the scope of statement. This is created in memory
rather than Tempdb database. You cannot create any index on CTE.
3. Table Variable acts like a variable and exists for a particular batch of query
execution. It gets dropped once it comes out of batch. This is also created in the
Tempdb database but not the memory.
How to insert values to identity column in SQL
Server
Identity field is usually used as a primary key. When you insert a new record into your table, this field
automatically assign an incremented value from the previous entry. Usually, you can't insert your own
value to this field.
In this article, I am going to expose the tips for inserting your own value to this field. It is simple and
easy. Consider you have the following Customer table.
1. CREATE TABLE Customer
2. (
3. ID int IDENTITY,
4. Namevarchar(100),
5. Addressvarchar(200)
6. )
Now, I am trying to insert a record into Customer table with identity field like as then I will get the error
message as shown below.
1. INSERT INTO Customer(ID,Name,Address) VALUES(1,'Shakham','Delhi')

Allow insert into identity field


You can alllow insert to the identity field by setting IDENTITY_INSERT ON for a particular table as shown:
1. SET IDENTITY_INSERT Customer ON

Disallow insert into identity field


You can also disalllow insert to the identity field by setting IDENTITY_INSERT OFF for a particular table as
shown:
1. SET IDENTITY_INSERT Customer OFF

Insert Value to Identity field


Now, lets see how to insert our own values to identity field ID with in the Customer table.
1. SET IDENTITY_INSERT Customer ON
2.
3. INSERT INTO Customer(ID,Name,Address) VALUES(3,'Rahul','Noida')
4. INSERT INTO Customer(ID,Name,Address) VALUES(4,'Rahul','Noida')
5.
6. SET IDENTITY_INSERT Customer OFF
7.
8. INSERT INTO Customer(Name,Address) VALUES('Rita','Noida')
After Inserting your own value to identity field don't forget to set IDENTITY_INSERT OFF.

Note
1. Usually, we use this trick when we have deleted some rows from the table and we want the data in a sequence.
2. After Inserting your own value to identity field don't forget to set IDENTITY_INSERT OFF
Reseed the Identity field
You can also reseed the identity field value. By doing so identity field values will start with a new defined
value.
Suppose you want to reseed the Customer table ID field from 3 then the new record s will be inserted
with ID 4,5,6..and so on.
1. --Reseeding the identity
2. DBCC checkident(Customer, RESEED,3)
3.
4. INSERT INTO Customer(Name,Address) VALUES('Geeta','Noida')
Calculate Running Total, Total of a Column and Row
Many times, you required to show information of each transaction and also keep a Running Total and
Final Total like GridView in Asp.Net. In this article, I am going to explain, how can you achieve this using
SQL Query in simple and easy way.
Suppose you have the below CustomerOrders table and has the data as shown below:
1. CREATE TABLE CustomerOrders
2. (
3. OrderIDint identity,
4. AmountDecimal(8,2),
5. OrderDateSmallDatetimedefaultgetdate()
6. )
7.
8. Go
9.
10. INSERT INTO CustomerOrders(Amount)Values(120.12)
11. INSERT INTO CustomerOrders(Amount)Values(20.12)
12. INSERT INTO CustomerOrders(Amount)Values(10.12)
13. INSERT INTO CustomerOrders(Amount)Values(30.12)
14. INSERT INTO CustomerOrders(Amount)Values(40)
15.
16. GO
17.
18. SELECT * FROM CustomerOrders

Calculating Running Total


Let's see how to calculate the running total using SQL Query as given below:
1. selectOrderID,OrderDate,CO.Amount
2. ,(select sum(Amount)fromCustomerOrders
3. whereOrderID<=CO.OrderID)
4. 'Running Total'
5. fromCustomerOrders CO

Calculating Final Total


Let's see how to calculate the final total using ROLLUP with in SQL Query as given below:
1. SELECT OrderID, SUM(Amount) AS Amount
2. FROM CustomerOrders
3. GROUP BY OrderID WITH ROLLUP
Calculating Total of All Numeric columns in a row
Let's see how to calculate the total of all numeric fields with in a row using SQL Query as given below:
1. SELECT OrderID,Amount, SUM(OrderID+Amount) AS RowNumericColSum
2. FROM CustomerOrders
3. GROUP BY OrderID,Amount
4. ORDER BY OrderID
Different Types of SQL Keys
A key is a single or combination of multiple fields in a table. Its is used to fetch or retrieve records/data-
rows from data table according to the condition/requirement. Keys are also used to create relationship
among different database tables or views.

Types of SQL Keys


We have following types of keys in SQL which are used to fetch records from tables and to make
relationship among tables or views.

1. Super Key
Super key is a set of one or more than one keys that can be used to identify a record uniquely in a
table.Example : Primary key, Unique key, Alternate key are subset of Super Keys.

2. Candidate Key
A Candidate Key is a set of one or more fields/columns that can identify a record uniquely in a table.
There can be multiple Candidate Keys in one table. Each Candidate Key can work as Primary Key.
Example: In below diagram ID, RollNo and EnrollNo are Candidate Keys since all these three fields
can be work as Primary Key.

3. Primary Key
Primary key is a set of one or more fields/columns of a table that uniquely identify a record in
database table. It can not accept null, duplicate values. Only one Candidate Key can be Primary Key.

4. Alternate key
A Alternate key is a key that can be work as a primary key. Basically, it is a candidate key that
currently is not primary key.
Example: In below diagram RollNo and EnrollNo becomes Alternate Keys when we define ID as
Primary Key.

5. Composite/Compound Key
Composite Key is a combination of more than one fields/columns of a table. It can be a Candidate
key, Primary key.

6. Unique Key
Uniquekey is a set of one or more fields/columns of a table that uniquely identify a record in
database table. It is like Primary key but it can accept only one null value and it cannot have
duplicate values. For more help refer the article Difference between primary key and unique key.
7. Foreign Key
Foreign Key is a field in database table that is Primary key in another table. It can accept multiple
null, duplicate values. For more help refer the article Difference between primary key and foreign
key.
Example : We can have a DeptID column in the Employee table which is pointing to DeptID column
in a department table where it a primary key.

Defining Keys in SQL Server


1. --DepartmentTable
2. CREATE TABLE Department
3. (
4. DeptIDint PRIMARY KEY,--primary key
5. Name varchar (50) NOT NULL,
6. Address varchar (200) NOT NULL
7. )
8. --StudentTable
9. CREATE TABLE Student
10. (
11. ID int PRIMARY KEY,--primary key
12. RollNovarchar(10) NOT NULL,
13. Namevarchar(50) NOT NULL,
14. EnrollNovarchar(50) UNIQUE,--unique key
15. Addressvarchar(200) NOT NULL,
16. DeptIDint FOREIGN KEY REFERENCES Department(DeptID)--foreign key
17. )

Note
1. Practically in database, we have only three types of keys Primary Key, Unique Key and Foreign Key. Other types of
keys are only concepts of RDBMS which you should know.
Different Types of SQL Server Views
Views are virtual tables that are compiled at run time. The data associated with views are not physically
stored in the view, but it is stored in the base tables of the view. A view can be made over one or more
database tables. Generally we put those columns in view that we need to retrieve/query again and again.
Once you have created the view, you can query view like as table. We can make index, trigger on view.
In Sql Server we make views for security purpose since it restricts the user to view some columns/fields
of the table(s). Views show only those columns that are present in the query which is used to make
view.One more advantage of Views is, data abstraction since the end user is not aware of all the data
present in database table.
Syntax for View
1. CREATE VIEW view_name
2. AS
3. select_statement[]

Types of Views
In Sql Server we have two types of views.

1. System Defined Views


System defined Views are predefined Views that already exist in the Master database of Sql Server.
These are also used as template Views for all newly created databases. These system Views will be
automatically attached to any user defined database.

We have following types of system defined views.

1. Information Schema View


In Sql Server we have twenty different schema views. These are used to display information of a
database, like as tables and columns. This type of view starts with INFORMATION_SCHEMA and
after this view name.
1. --Create a table
2. create table Employee_Test
3. (
4. Emp_IDint identity,
5. Emp_Namevarchar(55),
6. Emp_Technologyvarchar(55),
7. Emp_Saldecimal(10,2),
8. Emp_Designationvarchar(20)
9. )
10. --To view detailed information of the columns of table Employee_Test
11. SELECT * FROM INFORMATION_SCHEMA.COLUMNS
12. where TABLE_NAME='Employee_Test'

2. Catalog View
Catalog Views were introduced with SQL Server 2005. These are used to show database self
describing information.
1. select*fromsys.tables

3. Dynamic Management View


Dynamic Management Views were introduced in SQL Server 2005. These Views give the
administrator information of the database about the current state of the SQL Server machine.
These values help the administrator to analyze problems and tune the server for optimal
performance. These are of two types

1. Server-scoped Dynamic Management View


These are stored only in the Master database.

2. Database-scoped Dynamic Management View


These are stored in each database.
3. --To see all SQL Server connections
4. SELECT connection_id,session_id,client_net_address,auth_scheme
5. FROM sys.dm_exec_connections
2. User Defined Views
These types of view are defined by users. We have two types of user defined views.

1. Simple View
When we create a view on a single table, it is called simple view.
1. --NowInsert data to table Employee_Test
2. InsertintoEmployee_Test values ('Amit','PHP',12000,'SE');
3. InsertintoEmployee_Test values ('Mohan','ASP.NET',15000,'TL');
4. InsertintoEmployee_Test values ('Avin','C#',14000,'SE');
5. InsertintoEmployee_Test values ('Manoj','JAVA',22000,'SSE');
6. InsertintoEmployee_Test values ('Riyaz','VB',18000,'TH');
7. --Now create view on single table Employee_Test
8. create VIEW vw_Employee_Test
9. AS
10. SelectEmp_ID,Emp_Name,Emp_Designation
11. FromEmployee_Test

12. --Query view like as table


13. Select*fromvw_Employee_Test

In simple view we can insert, update, delete data. We can only insert data in simple view if
we have primary key and all not null fields in the view.
14. --Insert data to view vw_Employee_Test
15. insert intovw_Employee_Test(Emp_Name,Emp_Designation) values ('Shailu','SSE')
16. --Now see the affected view
17. Select*fromvw_Employee_Test

18. --Update data to view vw_Employee_Test


19. Updatevw_Employee_TestsetEmp_Name='Pawan'whereEmp_ID=6
20. --Now see the affected view
21. Select*fromvw_Employee_Test
22. --Delete data from view vw_Employee_Test
23. deletefromvw_Employee_TestwhereEmp_ID=6
24. --Now see the affected view
25. Select*fromvw_Employee_Test

2. Complex View
When we create a view on more than one table, it is called complex view.
1. --Create another table
2. create table Personal_Info
3. (
4. Emp_Namevarchar(55),
5. FNamevarchar(55),
6. DOB varchar(55),
7. Addressvarchar(55),
8. Mobileint,
9. Statevarchar(55)
10. )
11. --NowInsert data
12. InsertintoPersonal_Info values ('G.Chaudary','22-10-
1985','Ghaziabad',96548922,'UP');
13. InsertintoPersonal_Info values ('B.S.Chauhan','02-07-
1986','Haridwar',96548200,'UK');
14. InsertintoPersonal_Info values ('A.Panwar','30-04-1987','Noida',97437821,'UP');
15. InsertintoPersonal_Info values ('H.C.Patak','20-07-
1986','Rampur',80109747,'UP');
16. InsertintoPersonal_Info values ('M.Shekh','21-10-
1985','Delhi',96547954,'Delhi');
17. --Now create view on two tables Employee_TestandPersonal_Info
18. Create VIEW vw_Employee_Personal_Info
19. As
20. Selecte.Emp_ID,e.Emp_Name,e.Emp_Designation,p.DOB,p.Mobile
21. FromEmployee_Test e INNER JOIN Personal_Info p
22. One.Emp_Name= p.Emp_Name

23. --NowQuery view like as table


24. Select*fromvw_Employee_Personal_Info
We can only update data in complex view. We can't insert data in complex view.
25. --Update view
26. update vw_Employee_Personal_InfosetEmp_Designation='SSE'whereEmp_ID=3
27. --See affected view
28. Select*fromvw_Employee_Personal_Info

Note
1. We make views for security purpose since it restricts the user to view some columns/fields of the table(s).
2. One more advantage of Views is, data abstraction since the end user is not aware of all the data present in database
table
SQL Server Exceptions Working
SQL Server has an exception model to handle exceptions and errors that occurs in T-SQL statements.
Exception handling in Sql Server is like as exception handling in other programming language. To
understand exception handling, first we need to know how many types of exception we have in Sql
Server.

Types of Exceptions
1. Statement-Level Exception
This type of exception aborts only the current running statement within a batch of T-SQL statements.
The rest of the T-SQL statements will execute successfully if they have no exceptions. Let us see the
below example.
1. --Batch
2. SELECT POWER(4,28)
3. PRINT 'This statement will execute'
4. GO

2. Batch-Level Exception
This type of exception aborts only the batch in which exception occurs. The rest of the batches will
execute successfully if they have no exceptions. The statement in which exception occurs will be
aborted and the remaining T-SQL statements within the batch will also stopped.
1. --FirstBatch
2. DECLARE @var DECIMAL;
3. set@var=CONVERT(DECIMAL,'xyz')
4. PRINT @var
5. PRINT 'This statement will not execute'
6. GO
7. --SecondBatch
8. DECLARE @var DECIMAL;
9. set@var=CONVERT(DECIMAL,'12.35')
10. PRINT @var
11. PRINT 'This statement will execute'
12. GO
3. Parsing and Scope-Resolution Exception
This type of exception occurs during the parsing and during the scope-resolution phase of
compilation. This exception appears to behave just like batch-level exceptions. However, this has a
little different behavior.
If the exception occurs in the same scope of the batch, it behaves just like a batch-level exception.If
the exception occurs in a lower level of scope of the batch, it behaves just like statement-level
exception.
Parsing Exception
1. --ParsingError
2. SELECTEmpID,Name FROM Employee
3. PRINT 'This statement will execute'
4. GO

5. --ForSuccessfully execution we need to executed select statement asdynamic SQL


using the EXEC function
6. EXEC('SELECTEmpID,Name FROM Employee')
7. PRINT 'This statement will execute'
8. GO

Scope Resolution Exception


9. --FirstCreate a procedure
10. CREATE PROCEDURE usp_print
11. AS
12. BEGIN
13. Select*fromtbl
14. END
15. GO

16. --Now execute above created procedure in batch


17. EXEC usp_print
18. PRINT 'This statement will execute'
19. GO
20. --Since the stored procedure creates a new scope.Hence rest statement will be
executed
SQL Server Exception Handling by TRY…CATCH
Like C#, SQL Server also has an exception model to handle exceptions and errors that occurs in T-SQL
statements. To handle exception in Sql Server we have TRY..CATCH blocks. We put T-SQL statements in
TRY block and to handle exception we write code in CATCH block. If there is an error in code within TRY
block then the control will automatically jump to the corresponding CATCH blocks. In Sql Server, against
a Try block we can have only one CATCH block.
TRY…CATCH Syntax
1. BEGIN TRY
2. --T-SQL statements
3. --or T-SQL statement blocks
4. END TRY
5. BEGIN CATCH
6. --T-SQL statements
7. --or T-SQL statement blocks
8. END CATCH

Error Functions used within CATCH block


1. ERROR_NUMBER ()
This returns the error number and its value is same as for @@ERROR function.

2. ERROR_LINE ()
This returns the line number of T-SQL statement that caused error.

3. ERROR_SEVERITY()
This returns the severity level of the error.

4. ERROR_STATE ()
This returns the state number of the error.

5. ERROR_PROCEDURE ()
This returns the name of the stored procedure or trigger where the error occurred.

6. ERROR_MESSAGE ()
This returns the full text of error message. The text includes the values supplied for any substitutable
parameters, such as lengths, object names, or times.
Exception handling example
1. BEGIN TRY
2. DECLARE @num INT,@msgvarchar(200)
3. ----Divideby zero to generate Error
4. SET @num=5/0
5. PRINT 'This will not execute'
6. END TRY
7. BEGIN CATCH
8. PRINT 'Error occured that is'
9. set@msg=(SELECT ERROR_MESSAGE())
10. print@msg;
11. END CATCH
12. GO

1. BEGIN TRY
2. DECLARE @num INT
3. ----Divideby zero to generate Error
4. SET @num=5/0
5. PRINT 'This will not execute'
6. END TRY
7. BEGIN CATCH
8. SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_SEVERITY() AS ErrorSeverity, ERROR_STATE() AS ErrorState,
ERROR_PROCEDURE() AS ErrorProcedure, ERROR_LINE() AS ErrorLine, ERROR_MESSAGE() AS ErrorMessage;
9. END CATCH;
10. GO

Note
1. A TRY..CATCH block combination catches all the errors that have a severity between 11 and 19.
2. The CATCH block is executed only if there is an error occurs in T-SQL statements within TRY block otherwise the
CATCH block is ignored.
3. Each TRY block is associated with only one CATCH block and vice versa
4. TRY and CATCH blocks can’t be separated with the GO statement. We need to put both TRY and CATCH blocks within
the same batch.
5. TRY..CATCH blocks can be used with transactions. We check the number of open transactions by using
@@TRANCOUNT function in Sql Server.
6. XACT_STATE function within the TRY..CATCH block can be used to check whether a open transaction is committed or
not. It will return -1 if transaction is not committed else returns 1.
SQL Server Transactions Management
A transaction is a set of T-SQL statements that are executed together as a unit like as a single T-SQL
statement. If all of these T-SQL statements executed successfully, then a transaction is committed and
the changes made by T-SQL statements permanently saved to database. If any of these T-SQL
statements within a transaction fail, then the complete transaction is cancelled/ rolled back.
We use transaction in that case, when we try to modify more than one tables/views that are related to
one another. Transactions affect SQL Server performance greatly. Since When a transaction is initiated
then it locks all the tables data that are used in the transaction. Hence during transaction life cycle no
one can modify these tables’ data that are used by the transaction. The reason behind the locking of the
data is to maintain Data Integrity.

Types of Transactions
1. Implicit Transaction
Implicit transactions are maintained by SQL Server for each and every DDL (CREATE, ALTER, DROP,
TRUNCATE), DML (INSERT, UPDATE, DELETE) statements. All these T-SQL statements runs under the
implicit transaction. If there is an error occurs within these statements individually, SQL Server will
roll back the complete statement.

2. Explicit Transaction
Explicit transactions are defined by programmers. In Explicit transaction we include the DML
statements that need to be executed as a unit.

Transactions Example
1. CREATE TABLE Department
2. (
3. DeptIDint PRIMARY KEY,
4. DeptNamevarchar(50) NULL,
5. Locationvarchar(100) NULL,
6. )
7. GO
8. CREATE TABLE Employee
9. (
10. EmpIDint PRIMARY KEY,
11. Namevarchar(50) NULL,
12. Salaryint NULL,
13. Addressvarchar(100) NULL,
14. DeptIDint foreign Key references Department(DeptID)
15. )

1. --NowInsert data
2. INSERT INTO Department(DeptID,DeptName,Location)VALUES(1,'IT','Delhi')
3. GO
4. INSERT INTO Employee(EmpID,Name,Salary,Address,DeptID)VALUES(1,'Mohan',15000,'Delhi',1)
5. SELECT * FROM Department
6. SELECT * FROM Employee

1. BEGIN TRANSACTION trans


2. BEGIN TRY
3. INSERT INTO Department(DeptID,DeptName,Location)VALUES(2,'HR','Delhi')
4. INSERT INTO Employee(EmpID,Name,Salary,Address,DeptID)VALUES(1,'Mohan',18000,'Delhi',1)
5. IF @@TRANCOUNT>0
6. BEGIN COMMIT TRANSACTION trans
7. END
8. END TRY
9. BEGIN CATCH
10. print'Error Occured'
11. IF @@TRANCOUNT>0
12. BEGIN ROLLBACK TRANSACTION trans
13. END
14. END CATCH

1. --NowSelect data to see transaction affects


2. SELECT * FROM Employee
3. SELECT * FROM Department

1. --TransactionwithSavePointBEGIN TRANSACTION trans


2. BEGIN TRY
3. INSERT INTO Department(DeptID,DeptName,Location)VALUES(2,'HR','Delhi')
4. IF @@TRANCOUNT>0
5. BEGIN SAVE TRANSACTION trans;
6. END
7. INSERT INTO Department(DeptID,DeptName,Location)VALUES(3,'Admin','Delhi')
8. INSERT INTO Employee(EmpID,Name,Salary,Address,DeptID)VALUES(1,'Mohan',18000,'Delhi',1)
9. IF @@TRANCOUNT>0
10. BEGIN COMMIT TRANSACTION trans
11. END
12. END TRY
13. BEGIN CATCH
14. print'Error Occured'
15. IF @@TRANCOUNT>0
16. BEGIN ROLLBACK TRANSACTION trans
17. END
18. END CATCH

1. --NowSelect data to see transaction affects


2. SELECT * FROM Employee
3. SELECT * FROM Department
Different Types of SQL Server Triggers
Triggers are database object. Basically, these are special type of stored procedure that are automatically
fired/executed when a DDL or DML command statement related with the trigger is executed. Triggers are
used to assess/evaluate data before or after data modification using DDL and DML statements. These are
also used to preserve data integrity, to control server operations, to audit a server and to implement
business logic or business rule.

Types of Triggers
In Sql Server we can create four types of triggers Data Definition Language (DDL) triggers, Data
Manipulation Language (DML) triggers, CLR triggers and Logon triggers.

1. DDL Triggers
In SQL Server we can create triggers on DDL statements (like CREATE, ALTER, and DROP) and certain
system defined stored procedures that perform DDL-like operations.
Example : If you are going to execute the CREATE LOGIN statement or the sp_addlogin stored
procedure to create login user, then both these can execute/fire a DDL trigger that you can create on
CREATE_LOGIN event of Sql Server.
We can use only FOR/AFTER clause in DDL triggers not INSTEAD OF clause means we can
make only After Trigger on DDL statements.
DDL trigger can be used to observe and control actions performed on the server, and to audit these
operations. DDL triggers can be used to manage administrator tasks such as auditing and regulating
database operations.

2. DML Triggers
In SQL Server we can create triggers on DML statements (like INSERT, UPDATE, and DELETE) and
stored procedures that perform DML-like operations. DML Triggers are of two types

1. After Trigger (using FOR/AFTER CLAUSE)


This type of trigger fires after SQL Server finish the execution of the action successfully that fired
it.
Example : If you insert record/row in a table then the trigger related/associated with the insert
event on this table will fire only after the row passes all the constraints, like as primary key
constraint, and some rules. If the record/row insertion fails, SQL Server will not fire the After
Trigger.

2. Instead of Trigger (using INSTEAD OF CLAUSE)


This type of trigger fires before SQL Server starts the execution of the action that fired it. This is
differ from the AFTER trigger, which fires after the action that caused it to fire. We can have an
INSTEAD OF insert/update/delete trigger on a table that successfully executed but does not
include the actual insert/update/delete to the table.
Example : If you insert record/row in a table then the trigger related/associated with the insert
event on this table will fire before the row passes all the constraints, such as primary key
constraint and some rules. If the record/row insertion fails, SQL Server will fire the Instead of
Trigger.

3. CLR Triggers
CLR triggers are special type of triggers that based on the CLR (Common Language Runtime) in .net
framework. CLR integration of triggers has been introduced with SQL Server 2008 and allows for
triggers to be coded in one of .NET languages like C#, Visual Basic and F#.
We coded the objects(like trigger) in the CLR that have heavy computations or need references to
objects outside the SQL Server. We can write code for both DDL and DML triggers, using a supported
CLR language like C#, Visual basic and F#. I will discuss CLR trigger later.

4. Logon Triggers
Logon triggers are special type of trigger that fire when LOGON event of Sql Server is raised. This
event is raised when a user session is being established with Sql Server that is made after the
authentication phase finishes, but before the user session is actually established. Hence, all
messages that we define in the trigger such as error messages, will be redirected to the SQL Server
error log. Logon triggers do not fire if authentication fails. We can use these triggers to audit and
control server sessions, such as to track login activity or limit the number of sessions for a specific
login.
Synatx for Logon Trigger
1. CREATE TRIGGER trigger_name
2. ON ALL SERVER
3. [WITH ENCRYPTION]
4. {FOR|AFTER} LOGON
5. AS
6. sql_statement[1...n ]

Syntax for Trigger


1. CREATE TRIGGER trigger_name
2. ON {table|view}
3. [WITH ENCRYPTION|EXECUTE AS]
4. {FOR|AFTER|INSTEAD OF}{[CREATE|ALTER|DROP|INSERT|UPDATE|DELETE ]}
5. [NOT FOR REPLICATION]
6. AS
7. sql_statement[1...n ]

1. trigger_name
This is the name of the trigger. It should conform to the rules for identifiers in Sql Server.

2. table|view
This is the table/view on which the trigger is to be created.

3. ENCRYPTION
This option is optional. If this option is specified, original text of the CREATE TRIGGER statement will
be encrypted.

4. EXECUTE AS
This option is optional. This option specifies, the security context under which the trigger is executed.

5. FOR/AFTER
FOR/AFTER specifies that the trigger is After Trigger. AFTER is the default, if FOR is the only keyword
specified.AFTER triggers cannot be defined on views.
6. INSTEAD OF
INSTEAD OF specifies that the trigger is Instead Of Trigger.

7. CREATE|ALTER|DROP|INSERT|UPDATE|DELETE
These keywords specify on which action the trigger should be fired. One of these keywords or any
combination of these keywords in any order can be used.

8. NOT FOR REPLICATION


Indicates that the trigger should not be executed when a replication process modifies the table
involved in the trigger.

9. AS
After this we specifies the actions and condition that the trigger perform.

10. sql_statement
These are the trigger conditions and actions. The trigger actions specified in the T-SQL statements.

Note
1. The name of a trigger should follow the rules for identifiers.
2. DML trigger can be composed by any T-SQL statements, except CREATE DATABASE, ALTER DATABASE, DROP
DATABASE, LOAD DATABASE, LOAD LOG, RECONFIGURE, RESTORE DATABASE, and RESTORE LOG statements.
3. You cannot create triggers against system tables or dynamic management views. Moreover, the TRUNCATE TABLE
statement does not fire a trigger because this operation does not log individual row deletions.
4. If you use the DATABASE option, the scope of your DDL trigger will be the current database. If you use the ALL SERVER
option, the scope of your DDL triggers to the current server.
5. AFTER triggers cannot be defined on views.
6. AFTER is the default, if FOR is the only keyword specified.

After Trigger, Instead of Trigger Example


Triggers are special type of stored procedure that automatically execute when a DDL or DML statement
associated with the trigger is executed. DML Triggers are used to evaluate data after data manipulation
using DML statements. We have two types of DML triggers.

Types of DML Triggers


1. After Trigger (using FOR/AFTER CLAUSE)
This trigger fires after SQL Server completes the execution of the action successfully that fired it.
Example :If you insert record/row in a table then the trigger associated with the insert event on this
table will fire only after the row passes all the checks, such as primary key, rules, and constraints. If
the record/row insertion fails, SQL Server will not fire the After Trigger.

2. Instead of Trigger (using INSTEAD OF CLAUSE)


This trigger fires before SQL Server starts the execution of the action that fired it. This is much more
different from the AFTER trigger, which fires after the action that caused it to fire. We can have an
INSTEAD OF insert/update/delete trigger on a table that successfully executed but does not include
the actual insert/update/delet to the table.
Example :If you insert record/row in a table then the trigger associated with the insert event on this
table will fire before the row passes all the checks, such as primary key, rules, and constraints. If the
record/row insertion fails, SQL Server will fire the Instead of Trigger.

Example
1. --First create table Employee_Demo
2. CREATE TABLE Employee_Demo
3. (
4. Emp_IDint identity,
5. Emp_Namevarchar(55),
6. Emp_Saldecimal(10,2)
7. )
8. --NowInsert records
9. InsertintoEmployee_Demo values ('Amit',1000);
10. InsertintoEmployee_Demo values ('Mohan',1200);
11. InsertintoEmployee_Demo values ('Avin',1100);
12. InsertintoEmployee_Demo values ('Manoj',1300);
13. InsertintoEmployee_Demo values ('Riyaz',1400);
14. --Now create table Employee_Demo_Auditfor logging/backup purpose of table Employee_Demo create table
Employee_Demo_Audit
15. (
16. Emp_IDint,
17. Emp_Namevarchar(55),
18. Emp_Saldecimal(10,2),
19. Audit_Actionvarchar(100),
20. Audit_Timestamp datetime
21. )
Now I am going to explain the use of After Trigger using Insert, Update, Delete statement with example

1. After Insert Trigger


1. --Create trigger on table Employee_DemoforInsert statement
2. CREATE TRIGGER trgAfterInsert on Employee_Demo
3. FOR INSERT
4. AS declare @empidint,@empnamevarchar(55),@empsaldecimal(10,2),@audit_action
varchar(100);
5. select@empid=i.Emp_IDfrom inserted i;
6. select@empname=i.Emp_Namefrom inserted i;
7. select@empsal=i.Emp_Salfrom inserted i;
8. set@audit_action='Inserted Record -- After Insert Trigger.'; insert
intoEmployee_Demo_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp)
9. values (@empid,@empname,@empsal,@audit_action,getdate());
10. PRINT 'AFTER INSERT trigger fired.'
11. --Output will be

12. --Nowtry to insert data inEmployee_Demo table


13. insert intoEmployee_Demo(Emp_Name,Emp_Sal)values ('Shailu',1000);
14. --Output will be

15. --now select data from both the tables to see trigger action
16. select*fromEmployee_Demo
17. select*fromEmployee_Demo_Audit
18. --Output will be
Trigger have inserted the new record to Employee_Demo_Audit table for insert statement. In this
way we can trace a insert activity on a table using trigger.

2. After Update Trigger


1. --Create trigger on table Employee_DemoforUpdate statement
2. CREATE TRIGGER trgAfterUpdate ON dbo.Employee_Demo
3. FOR UPDATE
4. AS
5. declare @empidint,@empnamevarchar(55),@empsaldecimal(10,2),@audit_action
varchar(100);
6. select@empid=i.Emp_IDfrom inserted i;
7. select@empname=i.Emp_Namefrom inserted i;
8. select@empsal=i.Emp_Salfrom inserted i;if update(Emp_Name)
9. set@audit_action='Update Record --- After Update Trigger.';
10. if update (Emp_Sal)
11. set@audit_action='Update Record --- After Update Trigger.';
12. insert
intoEmployee_Demo_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp)
13. values (@empid,@empname,@empsal,@audit_action,getdate());
14. PRINT 'AFTER UPDATE trigger fired.'
15. --Output will be

16. --Nowtry to upadte data inEmployee_Demo table


17. update Employee_DemosetEmp_Name='Pawan'WhereEmp_ID=6;
18. --Output will be

19. --now select data from both the tables to see trigger action
20. select*fromEmployee_Demo
21. select*fromEmployee_Demo_Audit
22. --Output will be
Trigger have inserted the new record to Employee_Demo_Audit table for update statement. In this
way we can trace a update activity on a table using trigger.

3. After Delete Trigger


1. --Create trigger on table Employee_DemoforDelete statement
2. CREATE TRIGGER trgAfterDelete ON dbo.Employee_Demo
3. FOR DELETE
4. AS
5. declare @empidint,@empnamevarchar(55),@empsaldecimal(10,2),@audit_action
varchar(100);select@empid=d.Emp_ID FROM deleted d;
6. select@empname=d.Emp_Namefrom deleted d;
7. select@empsal=d.Emp_Salfrom deleted d;
8. select@audit_action='Deleted -- After Delete Trigger.';
9. insert
intoEmployee_Demo_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp)
10. values (@empid,@empname,@empsal,@audit_action,getdate());
11. PRINT 'AFTER DELETE TRIGGER fired.'
12. --Output will be

13. --Nowtry to delete data inEmployee_Demo table


14. DELETE FROM Employee_Demowhereemp_id=5
15. --Output will be

16. --now select data from both the tables to see trigger action
17. select*fromEmployee_Demo
18. select*fromEmployee_Demo_Audit
19. --Output will be
Trigger have inserted the new record to Employee_Demo_Audit table for delete statement. In this
way we can trace a delete activity on a table using trigger.
Now I am going to explain the use of Instead of Trigger using Insert, Update, Delete statement with
example

1. Instead of Insert Trigger


1. --Create trigger on table Employee_DemoforInsert statement
2. CREATE TRIGGER trgInsteadOfInsert ON dbo.Employee_Demo
3. INSTEAD OF Insert
4. AS
5. declare @emp_idint,@emp_namevarchar(55),@emp_saldecimal(10,2),@audit_action
varchar(100);
6. select@emp_id=i.Emp_IDfrom inserted i;
7. select@emp_name=i.Emp_Namefrom inserted i;
8. select@emp_sal=i.Emp_Salfrom inserted i;
9. SET @audit_action='Inserted Record -- Instead Of Insert Trigger.';
10. BEGIN
11. BEGIN TRAN
12. SET NOCOUNT ON
13. if(@emp_sal>=1000)
14. begin
15. RAISERROR('Cannot Insert where salary < 1000',16,1); ROLLBACK;end
16. elsebeginInsertintoEmployee_Demo(Emp_Name,Emp_Sal) values
(@emp_name,@emp_sal);InsertintoEmployee_Demo_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Ac
tion,Audit_Timestamp)
values(@@identity,@emp_name,@emp_sal,@audit_action,getdate());
17. COMMIT;
18. PRINT 'Record Inserted -- Instead Of Insert Trigger.'
19. END
20. END
21. --Output will be

22. --Nowtry to insert data inEmployee_Demo table


23. insert intoEmployee_Demo values ('Shailu',1300)
24. insert intoEmployee_Demo values ('Shailu',900)--It will raise error since we are
checking salary >=1000
25. --Outputs will be
26. --now select data from both the tables to see trigger action
27. select*fromEmployee_Demo
28. select*fromEmployee_Demo_Audit
29. --Output will be

Trigger have inserted the new record to Employee_Demo_Audit table for insert statement. In this
way we can apply business validation on the data to be inserted using Instead of trigger and can also
trace a insert activity on a table.

2. Instead of Update Trigger


1. --Create trigger on table Employee_DemoforUpdate statement
2. CREATE TRIGGER trgInsteadOfUpdate ON dbo.Employee_Demo
3. INSTEAD OF Update
4. AS
5. declare @emp_idint,@emp_namevarchar(55),@emp_saldecimal(10,2),@audit_action
varchar(100);
6. select@emp_id=i.Emp_IDfrom inserted i;
7. select@emp_name=i.Emp_Namefrom inserted i;
8. select@emp_sal=i.Emp_Salfrom inserted i;
9. BEGIN
10. BEGIN TRAN
11. if(@emp_sal>=1000)
12. begin
13. RAISERROR('Cannot Insert where salary < 1000',16,1); ROLLBACK;end
14. elsebegin
15. insert
intoEmployee_Demo_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp)
values(@emp_id,@emp_name,@emp_sal,@audit_action,getdate());
16. COMMIT;
17. PRINT 'Record Updated -- Instead Of Update Trigger.';END
18. --Output will be

19. --Nowtry to upadte data inEmployee_Demo table


20. update Employee_DemosetEmp_Sal='1400'whereemp_id=6
21. update Employee_DemosetEmp_Sal='900'whereemp_id=6
22. --Output will be

23. --now select data from both the tables to see trigger action
24. select*fromEmployee_Demo
25. select*fromEmployee_Demo_Audit
26. --Output will be
Trigger have inserted the updated record to Employee_Demo_Audit table for update statement. In
this way we can apply business validation on the data to be updated using Instead of trigger and can
also trace a update activity on a table.

3. Instead of Delete Trigger


1. --Create trigger on table Employee_DemoforDelete statement
2. CREATE TRIGGER trgAfterDelete ON dbo.Employee_Demo
3. INSTEAD OF DELETE
4. AS
5. declare @empidint,@empnamevarchar(55),@empsaldecimal(10,2),@audit_action
varchar(100);select@empid=d.Emp_ID FROM deleted d;
6. select@empname=d.Emp_Namefrom deleted d;
7. select@empsal=d.Emp_Salfrom deleted d;
8. BEGIN TRAN if(@empsal>1200)begin
9. RAISERROR('Cannot delete where salary > 1200',16,1);
10. ROLLBACK;
11. end
12. elsebegin
13. deletefromEmployee_DemowhereEmp_ID=@empid;
14. COMMIT;
15. insert
intoEmployee_Demo_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp)
16. values(@empid,@empname,@empsal,'Deleted -- Instead Of Delete Trigger.',getdate());
17. PRINT 'Record Deleted -- Instead Of Delete Trigger.'endEND
18. --Output will be

19. --Nowtry to delete data inEmployee_Demo table


20. DELETE FROM Employee_Demowhereemp_id=1
21. DELETE FROM Employee_Demowhereemp_id=3
22. --Output will be

23. --now select data from both the tables to see trigger action
24. select*fromEmployee_Demo
25. select*fromEmployee_Demo_Audit
26. --Output will be
Trigger have inserted the deleted record to Employee_Demo_Audit table for delete statement. In this
way we can apply business validation on the data to be deleted using Instead of trigger and can also
trace a delete activity on a table.

SQL Server Basics of Cursors


Cursor is a database object to retrieve data from a result set one row at a time, instead of the T-SQL
commands that operate on all the rows in the result set at one time. We use cursor when we need to
update records in a database table in singleton fashion means row by row.

Life Cycle of Cursor


1. Declare Cursor
A cursor is declared by defining the SQL statement that returns a result set.

2. Open
A Cursor is opened and populated by executing the SQL statement defined by the cursor.

3. Fetch
When cursor is opened, rows can be fetched from the cursor one by one or in a block to do data
manipulation.

4. Close
After data manipulation, we should close the cursor explicitly.

5. Deallocate
Finally, we need to delete the cursor definition and released all the system resources associated with
the cursor.
Syntax to Declare Cursor
Declare Cursor SQL Command is used to define the cursor with many options that impact the scalability
and loading behavior of the cursor. The basic syntax is given below
1. DECLARE cursor_name CURSOR
2. [LOCAL | GLOBAL]--define cursor scope
3. [FORWARD_ONLY | SCROLL]--define cursor movements (forward/backward)
4. [STATIC | KEYSET | DYNAMIC | FAST_FORWARD]--basic type of cursor
5. [READ_ONLY | SCROLL_LOCKS | OPTIMISTIC]--define locks
6. FOR select_statement--define SQL Select statement
7. FOR UPDATE [col1,col2,...coln]--define columns that need to be updated

Syntax to Open Cursor


A Cursor can be opened locally or globally. By default it is opened locally. The basic syntax to open
cursor is given below:
1. OPEN [GLOBAL]cursor_name--bydefault it islocal

Syntax to Fetch Cursor


Fetch statement provides the many options to retrieve the rows from the cursor. NEXT is the default
option. The basic syntax to fetch cursor is given below:
1. FETCH [NEXT|PRIOR|FIRST|LAST|ABSOLUTE n|RELATIVE n]
2. FROM [GLOBAL]cursor_name
3. INTO @Variable_name[1,2,..n]

Syntax to Close Cursor


Close statement closed the cursor explicitly. The basic syntax to close cursor is given below:
1. CLOSE cursor_name--after closing it can be reopen

Syntax to Deallocate Cursor


Deallocate statement delete the cursor definition and free all the system resources associated with the
cursor. The basic syntax to close cursor is given below:
1. DEALLOCATE cursor_name--after deallocation it can't be reopen

SQL SERVER – Simple Examples of Cursors


1. CREATE TABLE Employee
2. (
3. EmpIDint PRIMARY KEY,
4. EmpName varchar (50) NOT NULL,
5. Salaryint NOT NULL,
6. Address varchar (200) NOT NULL,
7. )
8. GO
9. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(1,'Mohan',12000,'Noida')
10. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(2,'Pavan',25000,'Delhi')
11. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(3,'Amit',22000,'Dehradun')
12. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(4,'Sonu',22000,'Noida')
13. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(5,'Deepak',28000,'Gurgaon')
14. GO
15. SELECT * FROM Employee

1. SET NOCOUNT ON
2. DECLARE @Idint
3. DECLARE @namevarchar(50)
4. DECLARE @salaryint
5. DECLARE cur_emp CURSOR
6. STATIC FOR
7. SELECT EmpID,EmpName,SalaryfromEmployee
8. OPEN cur_emp
9. IF @@CURSOR_ROWS>0
10. BEGIN
11. FETCH NEXT FROM cur_emp INTO @Id,@name,@salary
12. WHILE @@Fetch_status=0
13. BEGIN
14. PRINT 'ID : '+ convert(varchar(20),@Id)+', Name : '+@name+', Salary : '+convert(varchar(20),@salary)
15. FETCH NEXT FROM cur_emp INTO @Id,@name,@salary
16. END
17. END
18. CLOSE cur_emp
19. DEALLOCATE cur_emp
20. SET NOCOUNT OFF

SQL Server Different Types of Cursors


A Cursor allow us to retrieve data from a result set in singleton fashion means row by row. Cursor are
required when we need to update records in a database table one row at a time. I have already
explained the basic of cursor.
A Cursor impacts the performance of the SQL Server since it uses the SQL Server instances' memory,
reduce concurrency, decrease network bandwidth and lock resources. Hence it is mandatory to
understand the cursor types and its functions so that you can use suitable cursor according to your
needs.
You should avoid the use of cursor. Basically you should use cursor alternatives like as WHILE loop, sub
queries, Temporary tables and Table variables. We should use cursor in that case when there is no option
except cursor.

Types of Cursors
1. Static Cursors
A static cursor populates the result set at the time of cursor creation and query result is cached for
the lifetime of the cursor. A static cursor can move forward and backward direction. A static cursor is
slower and use more memory in comparison to other cursor. Hence you should use it only if scrolling
is required and other types of cursors are not suitable.
No UPDATE, INSERT, or DELETE operations are reflected in a static cursor (unless the cursor is closed
and reopened). By default static cursors are scrollable. SQL Server static cursors are always read-
only.

2. Dynamic Cursors
A dynamic cursor allows you to see the data updation, deletion and insertion in the data source while
the cursor is open. Hence a dynamic cursor is sensitive to any changes to the data source and
supports update, delete operations. By default dynamic cursors are scrollable.
3. Forward Only Cursors
A forward only cursor is the fastest cursor among the all cursors but it doesn't support backward
scrolling. You can update, delete data using Forward Only cursor. It is sensitive to any changes to the
original data source.
There are three more types of Forward Only Cursors.Forward_Only KEYSET, FORWARD_ONLY STATIC
and FAST_FORWARD.
A FORWARD_ONLY STATIC Cursor is populated at the time of creation and cached the data to the
cursor lifetime. It is not sensitive to any changes to the data source.
A FAST_FORWARD Cursor is the fastest cursor and it is not sensitive to any changes to the data
source.

4. Keyset Driven Cursors


A keyset driven cursor is controlled by a set of unique identifiers as the keys in the keyset. The
keyset depends on all the rows that qualified the SELECT statement at the time of cursor was
opened. A keyset driven cursor is sensitive to any changes to the data source and supports update,
delete operations. By default keyset driven cursors are scrollable.

SQL SERVER – Examples of Cursors


1. CREATE TABLE Employee
2. (
3. EmpIDint PRIMARY KEY,
4. EmpName varchar (50) NOT NULL,
5. Salaryint NOT NULL,
6. Address varchar (200) NOT NULL,
7. )
8. GO
9. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(1,'Mohan',12000,'Noida')
10. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(2,'Pavan',25000,'Delhi')
11. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(3,'Amit',22000,'Dehradun')
12. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(4,'Sonu',22000,'Noida')
13. INSERT INTO Employee(EmpID,EmpName,Salary,Address) VALUES(5,'Deepak',28000,'Gurgaon')
14. GO
15. SELECT * FROM Employee

Static Cursor - Example


1. SET NOCOUNT ON
2. DECLARE @Idint
3. DECLARE @namevarchar(50)
4. DECLARE @salaryint
5. DECLARE cur_emp CURSOR
6. STATIC FOR
7. SELECT EmpID,EmpName,SalaryfromEmployee
8. OPEN cur_emp
9. IF @@CURSOR_ROWS>0
10. BEGIN
11. FETCH NEXT FROM cur_emp INTO @Id,@name,@salary
12. WHILE @@Fetch_status=0
13. BEGIN
14. PRINT 'ID : '+ convert(varchar(20),@Id)+', Name : '+@name+', Salary : '+convert(varchar(20),@salary)
15. FETCH NEXT FROM cur_emp INTO @Id,@name,@salary
16. END
17. END
18. CLOSE cur_emp
19. DEALLOCATE cur_emp
20. SET NOCOUNT OFF
Dynamic Cursor - Example
1. --DynamicCursorforUpdate
2. SET NOCOUNT ON
3. DECLARE @Idint
4. DECLARE @namevarchar(50)
5. DECLARE Dynamic_cur_empupdate CURSOR
6. DYNAMIC
7. FOR
8. SELECT EmpID,EmpNamefromEmployee ORDER BY EmpName
9. OPEN Dynamic_cur_empupdate
10. IF @@CURSOR_ROWS>0
11. BEGIN
12. FETCH NEXT FROM Dynamic_cur_empupdate INTO @Id,@name
13. WHILE @@Fetch_status=0
14. BEGIN
15. IF @name='Mohan'
16. UpdateEmployee SET Salary=15000 WHERE CURRENT OF Dynamic_cur_empupdate
17. FETCH NEXT FROM Dynamic_cur_empupdate INTO @Id,@name
18. END
19. END
20. CLOSE Dynamic_cur_empupdate
21. DEALLOCATE Dynamic_cur_empupdate
22. SET NOCOUNT OFF
23. Go
24. Select*fromEmployee

1. --DynamicCursorfor DELETE
2. SET NOCOUNT ON
3. DECLARE @Idint
4. DECLARE @namevarchar(50)
5. DECLARE Dynamic_cur_empdelete CURSOR
6. DYNAMIC
7. FOR
8. SELECT EmpID,EmpNamefromEmployee ORDER BY EmpName
9. OPEN Dynamic_cur_empdelete
10. IF @@CURSOR_ROWS>0
11. BEGIN
12. FETCH NEXT FROM Dynamic_cur_empdelete INTO @Id,@name
13. WHILE @@Fetch_status=0
14. BEGIN
15. IF @name='Deepak'
16. DELETE Employee WHERE CURRENT OF Dynamic_cur_empdelete
17. FETCH NEXT FROM Dynamic_cur_empdelete INTO @Id,@name
18. END
19. END
20. CLOSE Dynamic_cur_empdelete
21. DEALLOCATE Dynamic_cur_empdelete
22. SET NOCOUNT OFF
23. Go
24. Select*fromEmployee
Forward Only Cursor - Example
1. --ForwardOnlyCursorforUpdate
2. SET NOCOUNT ON
3. DECLARE @Idint
4. DECLARE @namevarchar(50)
5. DECLARE Forward_cur_empupdate CURSOR
6. FORWARD_ONLY
7. FOR
8. SELECT EmpID,EmpNamefromEmployee ORDER BY EmpName
9. OPEN Forward_cur_empupdate
10. IF @@CURSOR_ROWS>0
11. BEGIN
12. FETCH NEXT FROM Forward_cur_empupdate INTO @Id,@name
13. WHILE @@Fetch_status=0
14. BEGIN
15. IF @name='Amit'
16. UpdateEmployee SET Salary=24000 WHERE CURRENT OF Forward_cur_empupdate
17. FETCH NEXT FROM Forward_cur_empupdate INTO @Id,@name
18. END
19. END
20. CLOSE Forward_cur_empupdate
21. DEALLOCATE Forward_cur_empupdate
22. SET NOCOUNT OFF
23. Go
24. Select*fromEmployee

1. --ForwardOnlyCursorforDelete
2. SET NOCOUNT ON
3. DECLARE @Idint
4. DECLARE @namevarchar(50)
5. DECLARE Forward_cur_empdelete CURSOR
6. FORWARD_ONLY
7. FOR
8. SELECT EmpID,EmpNamefromEmployee ORDER BY EmpName
9. OPEN Forward_cur_empdelete
10. IF @@CURSOR_ROWS>0
11. BEGIN
12. FETCH NEXT FROM Forward_cur_empdelete INTO @Id,@name
13. WHILE @@Fetch_status=0
14. BEGIN
15. IF @name='Sonu'
16. DELETE Employee WHERE CURRENT OF Forward_cur_empdelete
17. FETCH NEXT FROM Forward_cur_empdelete INTO @Id,@name
18. END
19. END
20. CLOSE Forward_cur_empdelete
21. DEALLOCATE Forward_cur_empdelete
22. SET NOCOUNT OFF
23. Go
24. Select*fromEmployee
Keyset Driven Cursor - Example
1. --Keyset driven CursorforUpdate
2. SET NOCOUNT ON
3. DECLARE @Idint
4. DECLARE @namevarchar(50)
5. DECLARE Keyset_cur_empupdate CURSOR
6. KEYSET
7. FOR
8. SELECT EmpID,EmpNamefromEmployee ORDER BY EmpName
9. OPEN Keyset_cur_empupdate
10. IF @@CURSOR_ROWS>0
11. BEGIN
12. FETCH NEXT FROM Keyset_cur_empupdate INTO @Id,@name
13. WHILE @@Fetch_status=0
14. BEGIN
15. IF @name='Pavan'
16. UpdateEmployee SET Salary=27000 WHERE CURRENT OF Keyset_cur_empupdate
17. FETCH NEXT FROM Keyset_cur_empupdate INTO @Id,@name
18. END
19. END
20. CLOSE Keyset_cur_empupdate
21. DEALLOCATE Keyset_cur_empupdate
22. SET NOCOUNT OFF
23. Go
24. Select*fromEmployee

1. --KeyseDrivenCursorforDelete
2. SET NOCOUNT ON
3. DECLARE @Idint
4. DECLARE @namevarchar(50)
5. DECLARE Keyset_cur_empdelete CURSOR
6. KEYSET
7. FOR
8. SELECT EmpID,EmpNamefromEmployee ORDER BY EmpName
9. OPEN Keyset_cur_empdelete
10. IF @@CURSOR_ROWS>0
11. BEGIN
12. FETCH NEXT FROM Keyset_cur_empdelete INTO @Id,@name
13. WHILE @@Fetch_status=0
14. BEGIN
15. IF @name='Amit'
16. DELETE Employee WHERE CURRENT OF Keyset_cur_empdelete
17. FETCH NEXT FROM Keyset_cur_empdelete INTO @Id,@name
18. END
19. END
20. CLOSE Keyset_cur_empdelete
21. DEALLOCATE Keyset_cur_empdelete
22. SET NOCOUNT OFF
23. GoSelect*fromEmployee
Database Normalization Basics
Normalization or data normalization is a process to organize the data into tabular format (database
tables). A good database design includes the normalization, without normalization a database system
may slow, inefficient and might not produce the expected result. Normalization reduces the data
redundancy and inconsistent data dependency.

Normal Forms
We organize the data into database tables by using normal forms rules or conditions. Normal forms help
us to make a good database design. Generally we organize the data up to third normal form. We rarely
use the fourth and fifth normal form.
To understand normal forms consider the folowing unnormalized database table. Now we will normalize
the data of below table using normal forms.
1. First Normal Form (1NF)
A database table is said to be in 1NF if it contains no repeating fields/columns. The process of
converting the UNF table into 1NF is as follows:
1. Separate the repeating fields into new database tables along with the key from unnormalized
database table.
2. The primary key of new database tables may be a composite key
1NF of above UNF table is as follows:

2. Second Normal Form (2NF)


A database table is said to be in 2NF if it is in 1NF and contains only those fields/columns that are
functionally dependent(means the value of field is determined by the value of another field(s)) on the
primary key. In 2NF we remove the partial dependencies of any non-key field.
The process of converting the database table into 2NF is as follows:

1. Remove the partial dependencies(A type of functional dependency where a field is only functionally
dependent on the part of primary key) of any non-key field.
2. If field B depends on field A and vice versa. Also for a given value of B, we have only one possible
value of A and vice versa, Then we put the field B in to new database table where B will be primary
key and also marked as foreign key in parent table.
2NF of above 1NF tables is as follows:

3. Third Normal Form (3NF)


A database table is said to be in 3NF if it is in 2NF and all non keys fields should be dependent on
primary key or We can also said a table to be in 3NF if it is in 2NF and no fields of the table is
transitively functionally dependent on the primary key.The process of converting the table into 3NF
is as follows:
1. Remove the transitive dependecies(A type of functional dependency where a field is functionally
dependent on the Field that is not the primary key.Hence its value is determined, indirectly by the
primary key )
2. Make separate table for transitive dependent Field.
3NF of above 2NF tables is as follows:

4. Boyce Code Normal Form (BCNF)


A database table is said to be in BCNF if it is in 3NF and contains each and every determinant as a
candidate key.The process of converting the table into BCNF is as follows:
1. Remove the non trival functional dependency.
2. Make separate table for the determinants.
BCNF of below table is as follows:

5. Fourth Normal Form (4NF)


A database table is said to be in 4NF if it is in BCNF and primary key has one-to-one relationship to all
non keys fields or We can also said a table to be in 4NF if it is in BCNF and contains no multi-valued
dependencies.The process of converting the table into 4NF is as follows:
1. Remove the multivalued dependency.
2. Make separate table for multivalued Fields.
4NF of below table is as follows:
6. Fifth Normal Form (5NF)
A database table is said to be in 5NF if it is in 4NF and contains no redundant values or We can also
said a table to be in 5NF if it is in 4NF and contains no join dependencies.The process of converting
the table into 5NF is as follows:
1. Remove the join dependency.
2. Break the database table into smaller and smaller tables to remove all data redundancy.
5NF of below table is as follows:
Create a comma separated list from column using
select statement
Sometimes we required to generate a comma separated list of columns values like a list of EmailIDs to
send mail. In SQL Server, we can make a comma separated list by using COALESCE as shown in below.
Use of COALESCE to create comma separated list
Suppose we have following data in Employee table and we need to make a semicolon separated list of
EmailIDs to send mail, then we can use COALESCE as shown in below fig.

Here I am creating a semicolon(;) separated list. You can use comma(,) in place of semicolon to make
comma separated list.

Tips to improve SQL Server database design and


performance
Best performance is the main concern to develop a successful application. Like a coin database is the tail
side (back-end) of an application. A good database design provides best performance during data
manipulation which results into the best performance of an application.
During database designing and data manipulation we should consider the following key points:
1. Choose Appropriate Data Type
Choose appropriate SQL Data Type to store your data since it also helps in to improve the query
performance. Example: To store strings use varchar in place of text data type since varchar performs
better than text. Use text data type, whenever you required storing of large text data (more than
8000 characters). Up to 8000 characters data you can store in varchar.

2. Avoid nchar and nvarchar


Practice to avoid nchar and nvarchar data type since both the data types takes just double memory
as char and varchar. Use nchar and nvarchar when you required to store Unicode (16-bit characters)
data like as Hindi, Chinese characters etc.

3. Avoid NULL in fixed-length field


Practice to avoid the insertion of NULL values in the fixed-length (char) field. Since, NULL takes the
same space as desired input value for that field. In case of requirement of NULL, use variable-length
(varchar) field that takes less space for NULL.

4. Avoid * in SELECT statement


Practice to avoid * in Select statement since SQL Server converts the * to columns name before
query execution. One more thing, instead of querying all columns by using * in select statement,
give the name of columns which you required.
1. --Avoid
2. SELECT * FROM tblName
3. --Best practice
4. SELECT col1,col2,col3 FROM tblName

5. Use EXISTS instead of IN


Practice to use EXISTS to check existence instead of IN since EXISTS is faster than IN.
1. --Avoid
2. SELECT Name,Price FROM tblProduct
3. whereProductID IN (Select distinct ProductIDfromtblOrder)
4. --Best practice
5. SELECT Name,Price FROM tblProduct
6. whereProductID EXISTS (Select distinct ProductIDfromtblOrder)

6. Avoid Having Clause


Practice to avoid Having Clause since it acts as filter over selected rows. Having clause is required if
you further wish to filter the result of an aggregations. Don't use HAVING clause for any other
purpose.

7. Create Clustered and Non-Clustered Indexes


Practice to create clustered and non clustered index since indexes helps in to access data fastly. But
be careful, more indexes on a tables will slow the INSERT,UPDATE,DELETE operations. Hence try to
keep small no of indexes on a table.

8. Keep clustered index small


Practice to keep clustered index as much as possible since the fields used in clustered index may
also used in nonclustered index and data in the database is also stored in the order of clustered
index. Hence a large clustered index on a table with a large number of rows increase the size
significantly. Please refer the article Effective Clustered Indexes

9. Avoid Cursors
Practice to avoid cursor since cursor are very slow in performance. Always try to use SQL Server
cursor alternative. Please refer the article Cursor Alternative.

10. Use Table variable inplace of Temp table


Practice to use Table varible in place of Temp table since Temp table resides in the TempDb
database. Hence use of Temp tables required interaction with TempDb database that is a little bit
time taking task.

11. Use UNION ALL inplace of UNION


Practice to use UNION ALL in place of UNION since it is faster than UNION as it doesn't sort the result
set for distinguished values.

12. Use Schema name before SQL objects name


Practice to use schema name before SQL object name followed by "." since it helps the SQL Server
for finding that object in a specific schema. As a result performance is best.
1. --Heredbois schema name
2. SELECT col1,col2 fromdbo.tblName
3. --Avoid
4. SELECT col1,col2 fromtblName

13. Keep Transaction small


Practice to keep transaction as small as possible since transaction lock the processing tables data
during its life. Some times long transaction may results into deadlocks. Please refer the article SQL
Server Transactions Management

14. SET NOCOUNT ON


Practice to set NOCOUNT ON since SQL Server returns number of rows effected by
SELECT,INSERT,UPDATE and DELETE statement. We can stop this by setting NOCOUNT ON like as:
1. CREATE PROCEDURE dbo.MyTestProc
2. AS
3. SET NOCOUNT ON
4. BEGIN
5. .
6. .
7. END

15. Use TRY-Catch


Practice to use TRY-CATCH for handling errors in T-SQL statements. Sometimes an error in a running
transaction may cause deadlock if you have no handle error by using TRY-CATCH. Please refer the
article Exception Handling by TRY…CATCH

16. Use Stored Procedure for frequently used data and more
complex queries
Practice to create stored procedure for quaery that is required to access data frequently. We also
created stored procedure for resolving more complex task.

17. Avoid prefix "sp_" with user defined stored procedure name
Practice to avoid prefix "sp_" with user defined stored procedure name since system defined stored
procedure name starts with prefix "sp_". Hence SQL server first search the user defined procedure in
the master database and after that in the current session database. This is time consuming and may
give unexcepted result if system defined stored procedure have the same name as your defined
procedure.
Get nth highest and lowest salary of an employee
One student of me asked "how can we get nth highest and lowest salary on an employee ?". In this
article I am going to expose, how can we achieve this in SQL Server.
Suppose we have employee name and salary as shown in below fig.
Query to get nth(3rd) Highest Salary
1. Select TOP 1Salaryas'3rd Highest Salary'
2. from(SELECT DISTINCT TOP 3SalaryfromEmployee ORDER BY Salary DESC)
3. a ORDER BY Salary ASC

Query to get nth(3rd) Lowest Salary


1. Select TOP 1Salaryas'3rd Lowest Salary'
2. from(SELECT DISTINCT TOP 3SalaryfromEmployee ORDER BY Salary ASC)
3. a ORDER BY Salary DESC

Difference between Stored Procedure and Function


in SQL Server
Stored Procedures are pre-compile objects which are compiled for first time and its compiled format is
saved which executes (compiled code) whenever it is called. But Function is compiled and executed
every time when it is called. For more about stored procedure and function refer the articles Different
types of Stored Procedure and Different types of Function.
Basic Difference
1. Function must return a value but in Stored Procedure it is optional( Procedure can return zero or n
values).
2. Functions can have only input parameters for it whereas Procedures can have input/output
parameters .
3. Functions can be called from Procedure whereas Procedures cannot be called from Function.

Advance Difference
1. Procedure allows SELECT as well as DML(INSERT/UPDATE/DELETE) statement in it whereas Function
allows only SELECT statement in it.
2. Procedures can not be utilized in a SELECT statement whereas Function can be embedded in a
SELECT statement.
3. Stored Procedures cannot be used in the SQL statements anywhere in the WHERE/HAVING/SELECT
section whereas Function can be.
4. Functions that return tables can be treated as another rowset. This can be used in JOINs with other
tables.
5. Inline Function can be though of as views that take parameters and can be used in JOINs and other
Rowset operations.
6. Exception can be handled by try-catch block in a Procedure whereas try-catch block cannot be used
in a Function.
7. We can go for Transaction Management in Procedure whereas we can't go in Function.

Difference between Primary Key and Unique Key


In SQL Server, we have two keys which distinctively or uniquely identify a record in the database. Both
the keys seems identical, but actually both are different in features and behaviours. In this article, I
would like to share the key difference between primary key and unique key. For more help about keys in
SQL Server refer the article Different Types of SQL Keys.
Difference between Primary Key & Unique Key
Primary Key

Unique Key

Primary Key can't accept null values.

Unique key can accept only one null value.

By default, Primary key is clustered index and data in the database table is physically organized in the
sequence of clustered index.

By default, Unique key is a unique non-clustered index.

We can have only one Primary key in a table.

We can have more than one unique key in a table.

Primary key can be made foreign key into another table.

In SQL Server, Unique key can be made foreign key into another table.

Define Primary key and Unique key


1. CREATE TABLE Employee
2. (
3. EmpIDint PRIMARY KEY,--define primary key
4. Name varchar (50) NOT NULL,
5. MobileNoint UNIQUE,--define unique key
6. Salaryint NULL
7. )

Difference between Primary Key and Foreign Key


In SQL Server, there are two keys - primary key and foreign key which seems identical, but actually both
are different in features and behaviours. In this article, I would like to share the key difference between
primary key and foreign key. For more help about keys in SQL Server refer the article Different Types of
SQL Keys.
Difference between Primary Key & Foreign Key

Primary Key

Foreign Key

Primary key uniquely identify a record in the table.

Foreign key is a field in the table that is primary key in another table.

Primary Key can't accept null values.

Foreign key can accept multiple null value.

By default, Primary key is clustered index and data in the database table is physically organized in the
sequence of clustered index.

Foreign key do not automatically create an index, clustered or non-clustered. You can manually create
an index on foreign key.

We can have only one Primary key in a table.

We can have more than one foreign key in a table.


Define Primary key and Foreign key
1. --CreateParentTable
2. CREATE TABLE Department
3. (
4. DeptIDint PRIMARY KEY,--define primary key
5. Name varchar (50) NOT NULL,
6. Addressvarchar(100) NULL
7. )
8. GO
9. --CreateChildTable
10. CREATE TABLE Employee
11. (
12. EmpIDint PRIMARY KEY,--define primary key
13. Name varchar (50) NOT NULL,
14. Salaryint NULL,
15. --define foreign key
16. DeptIDint FOREIGN KEY REFERENCES Department(DeptID)
17. )

Note
As @Marc Jellinek suggested, I would like to add the below points about foreign key :
1. Foreign keys do not automatically create an index, clustered or non-clustered. You must manually create an index on
foreign keys.
2. There are actual advantages to having a foreign key be supported with a clustered index, but you get only one per
table. What's the advantage? If you are selecting the parent plus all child records, you want the child records next to
each other. This is easy to accomplish using a clustered index.
3. Having a null foreign key is usually a bad idea. In the example below, the record in [dbo].[child] is what would be
referred to as an "orphan record". Think long and hard before doing this.
1. IF EXISTS (SELECT * FROM [sys].[schemas][sch] INNER JOIN [sys].[tables][tbl] ON [sch].[schema_id]=[tbl].
[schema_id] WHERE [sch].[name]='dbo' AND [tbl].[name]='child')
2. DROP TABLE [dbo].[child]
3. IF EXISTS (SELECT * FROM [sys].[schemas][sch] INNER JOIN [sys].[tables][tbl] ON [sch].[schema_id]=[tbl].
[schema_id] WHERE [sch].[name]='dbo' AND [tbl].[name]='parent') DROP TABLE [dbo].[parent]
4. CREATE TABLE [dbo].[parent]
5. (
6. [id][int] IDENTITY NOT NULL,
7. [name][varchar](250) NOT NULL,
8. CONSTRAINT [PK_dbo__parent] PRIMARY KEY NONCLUSTERED ([id])
9. )
10. CREATE TABLE [dbo].[child]
11. (
12. [id][int] IDENTITY NOT NULL,[parent_id][int] NULL,
13. [name][varchar](250) NOT NULL,
14. CONSTRAINT [PK_dbo__child] PRIMARY KEY NONCLUSTERED ([id]),
15. CONSTRAINT [FK_dbo__child__dbo__parent] FOREIGN KEY ([parent_id]) REFERENCES [dbo].[parent]([id])
16. )
17. --Insert data
18. INSERT INTO [dbo].[parent]([name]) VALUES ('parent1')
19. INSERT INTO [dbo].[child]([parent_id],[name])VALUES(1,'child 1')
20. INSERT INTO [dbo].[child]([parent_id],[name])VALUES(NULL,'child 2')
21. --Select data
22. SELECT * FROM [dbo].[child]

Drop all tables, stored procedure, views and triggers


Sometimes, there is a case, when we need to remove all tables, stored procedure, views and triggers
completely from the database. If you have around 100 tables, stored procedure and views in your
database, to remove these, completely from database became a tedious task. In this article, I would like
to share the script by which you can remove tables, stored procedure, views and triggers completely
from database.

Remove all Tables


1. -- drop all user defined tables
2. EXEC sp_MSforeachtable@command1="DROP TABLE ?"
Remove all User-defined Stored Procedures
1. -- drop all user defined stored procedures
2. Declare@procNamevarchar(500)
3. Declare cur CursorForSelect[name]Fromsys.objectswhere type ='p'
4. Open cur
5. FetchNextFromcurInto@procName
6. While@@fetch_status=0
7. Begin
8. Exec('drop procedure '+@procName)
9. FetchNextFromcurInto@procName
10. End
11. Close cur
12. Deallocate cur

Remove all Views


1. -- drop all user defined views
2. Declare@viewNamevarchar(500)
3. Declare cur CursorForSelect[name]Fromsys.objectswhere type ='v'
4. Open cur
5. FetchNextFromcurInto@viewName
6. While@@fetch_status=0
7. Begin
8. Exec('drop view '+@viewName)
9. FetchNextFromcurInto@viewName
10. End
11. Close cur
12. Deallocate cur

Remove all Triggers


1. -- drop all user defined triggers
2. Declare@trgNamevarchar(500)
3. Declare cur CursorForSelect[name]Fromsys.objectswhere type ='tr'
4. Open cur
5. FetchNextFromcurInto@trgName
6. While@@fetch_status=0
7. Begin
8. Exec('drop trigger '+@trgName)
9. FetchNextFromcurInto@trgName
10. End
11. Close cur
12. Deallocate cur

You might also like