Triggers
Triggers
INTRODUCTION
TRIGGERS IN SQL SERVER
BACKGROUND
This article gives a brief introduction about Triggers in Sql Server 2000/2005.
What is a Trigger
A trigger is a special kind of a store procedure that executes in response to certain action on the table like insertion, deletion or updation of
data. It is a database object which is bound to a table and is executed automatically. You cant explicitly invoke triggers. The only way to do
this is by performing the required action no the table that they are assigned to.
Types Of Triggers
There are three action query types that you use in SQL which are INSERT, UPDATE and DELETE. So, there are three types of triggers and
hybrids that come from mixing and matching the events and timings that fire them.
Basically, triggers are classified into two main types:-
(i) After Triggers (For Triggers)
(ii) Instead Of Triggers
(i) After Triggers
These triggers run after an insert, update or delete on a table. They are not supported for views.
AFTER TRIGGERS can be classified further into three types as:
(a) AFTER INSERT Trigger.
(b) AFTER UPDATE Trigger.
(c) AFTER DELETE Trigger.
Lets create After triggers. First of all, lets create a table and insert some sample data. Then, on this table, I will be attaching several
triggers.
CREATE TABLE Employee_Test
(
Emp_ID INT Identity,
Emp_name Varchar(100),
Emp_Sal Decimal (10,2)
)
INSERT INTO Employee_Test VALUES ('Anees',1000);
INSERT INTO Employee_Test VALUES ('Rick',1200);
INSERT INTO Employee_Test VALUES ('John',1100);
INSERT INTO Employee_Test VALUES ('Stephen',1300);
INSERT INTO Employee_Test VALUES ('Maria',1400);
I will be creating an AFTER INSERT TRIGGER which will insert the rows inserted into the table into another audit table. The main purpose of this
audit table is to record the changes in the main table. This can be thought of as a generic audit trigger.
Now, create the audit table as:-
CREATE TABLE Employee_Test_Audit
(
Emp_ID int,
Emp_name varchar(100),
Emp_Sal decimal (10,2),
Audit_Action varchar(100),
Audit_Timestamp datetime
)
(a) AFTRE INSERT Trigger
This trigger is fired after an INSERT on the table. Lets create the trigger as:-
CREATE TRIGGER trgAfterInsert ON [dbo].[Employee_Test]
FOR INSERT
AS
declare @empid int;
declare @empname varchar(100);
declare @empsal decimal(10,2);
declare @audit_action varchar(100);
select @empid=i.Emp_ID from inserted i;
select @empname=i.Emp_Name from inserted i;
select @empsal=i.Emp_Sal from inserted i;
set @audit_action='Inserted Record -- After Insert Trigger.';
insert into Employee_Test_Audit
(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp)
values(@empid,@empname,@empsal,@audit_action,getdate());
PRINT 'AFTER INSERT trigger fired.'
GO
The CREATE TRIGGER statement is used to create the trigger. THE ON clause specifies the table name on which the trigger is to be attached.
The FOR INSERT specifies that this is an AFTER INSERT trigger. In place of FOR INSERT, AFTER INSERT can be used. Both of them mean the
same.
In the trigger body, table named inserted has been used. This table is a logical table and contains the row that has been inserted. I have
selected the fields from the logical inserted table from the row that has been inserted into different variables, and finally inserted those values
into the Audit table.
To see the newly created trigger in action, lets insert a row into the main table as :
insert into Employee_Test values('Chris',1500);
Now, a record has been inserted into the Employee_Test table. The AFTER INSERT trigger attached to this table has inserted the record into the
Employee_Test_Audit as:-
6 Chris 1500.00 Inserted Record -- After Insert Trigger. 2008-04-26 12:00:55.700
(b) AFTER UPDATE Trigger
This trigger is fired after an update on the table. Lets create the trigger as:-
CREATE TRIGGER trgAfterUpdate ON [dbo].[Employee_Test]
FOR UPDATE
AS
declare @empid int;
declare @empname varchar(100);
declare @empsal decimal(10,2);
declare @audit_action varchar(100);
select @empid=i.Emp_ID from inserted i;
select @empname=i.Emp_Name from inserted i;
select @empsal=i.Emp_Sal from inserted i;
if update(Emp_Name)
set @audit_action='Updated Record -- After Update Trigger.';
if update(Emp_Sal)
set @audit_action='Updated Record -- After Update Trigger.';
insert into Employee_Test_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp)
values(@empid,@empname,@empsal,@audit_action,getdate());
PRINT 'AFTER UPDATE Trigger fired.'
GO
The AFTER UPDATE Trigger is created in which the updated record is inserted into the audit table. There is no logical table updated like the
logical table inserted. We can obtain the updated value of a field from the update(column_name) function. In our trigger, we have used, if
update(Emp_Name) to check if the column Emp_Name has been updated. We have similarly checked the column Emp_Sal for an update.
Lets update a record column and see what happens.
update Employee_Test set Emp_Sal=1550 where Emp_ID=6
This inserts the row into the audit table as:-
6 Chris 1550.00 Updated Record -- After Update Trigger. 2008-04-26 12:38:11.843
(c) AFTER DELETE Trigger
This trigger is fired after a delete on the table. Lets create the trigger as:-
CREATE TRIGGER trgAfterDelete ON [dbo].[Employee_Test]
AFTER DELETE
AS
declare @empid int;
declare @empname varchar(100);
declare @empsal decimal(10,2);
declare @audit_action varchar(100);
select @empid=d.Emp_ID from deleted d;
select @empname=d.Emp_Name from deleted d;
select @empsal=d.Emp_Sal from deleted d;
set @audit_action='Deleted -- After Delete Trigger.';
insert into Employee_Test_Audit
(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp)
values(@empid,@empname,@empsal,@audit_action,getdate());
PRINT 'AFTER DELETE TRIGGER fired.'
GO
In this trigger, the deleted records data is picked from the logical deleted table and inserted into the audit table.
Lets fire a delete on the main table.
A record has been inserted into the audit table as:-
6 Chris 1550.00 Deleted -- After Delete Trigger. 2008-04-26 12:52:13.867
All the triggers can be enabled/disabled on the table using the statement
ALTER TABLE Employee_Test {ENABLE|DISBALE} TRIGGER ALL
Specific Triggers can be enabled or disabled as :-
ALTER TABLE Employee_Test DISABLE TRIGGER trgAfterDelete
This disables the After Delete Trigger named trgAfterDelete on the specified table.
(ii) Instead Of Triggers
These can be used as an interceptor for anything that anyonr tried to do on our table or view. If you define an Instead Of trigger on a table for
the Delete operation, they try to delete rows, and they will not actually get deleted (unless you issue another delete instruction from within the
trigger)
INSTEAD OF TRIGGERS can be classified further into three types as:-
(a) INSTEAD OF INSERT Trigger.
(b) INSTEAD OF UPDATE Trigger.
(c) INSTEAD OF DELETE Trigger.
(a) Lets create an Instead Of Delete Trigger as:-
CREATE TRIGGER trgInsteadOfDelete ON [dbo].[Employee_Test]
INSTEAD OF DELETE
AS
declare @emp_id int;
declare @emp_name varchar(100);
declare @emp_sal int;
select @emp_id=d.Emp_ID from deleted d;
select @emp_name=d.Emp_Name from deleted d;
select @emp_sal=d.Emp_Sal from deleted d;
BEGIN
if(@emp_sal>1200)
begin
RAISERROR('Cannot delete where salary > 1200',16,1);
ROLLBACK;
end
else
begin
delete from Employee_Test where Emp_ID=@emp_id;
COMMIT;
insert into Employee_Test_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp)
values(@emp_id,@emp_name,@emp_sal,'Deleted -- Instead Of Delete Trigger.',getdate());
PRINT 'Record Deleted -- Instead Of Delete Trigger.'
end
END
GO
This trigger will prevent the deletion of records from the table where Emp_Sal > 1200. If such a record is deleted, the Instead Of Trigger will
rollback the transaction, otherwise the transaction will be committed.
Now, lets try to delete a record with the Emp_Sal >1200 as:-
delete from Employee_Test where Emp_ID=4
This will print an error message as defined in the RAISE ERROR statement as:-
Server: Msg 50000, Level 16, State 1, Procedure trgInsteadOfDelete, Line 15
Cannot delete where salary > 1200
And this record will not be deleted.
In a similar way, you can code Instead of Insert and Instead Of Update triggers on your tables.
/wEPDwUKMjExO
Introduction- TRY AND CATCH BLOCK
During development of any application, one of the most common things we need to take care of is Exception and Error handling. Similarly we
need to take care of handling error and exception while designing our database like inside stored procedure. In SQL Server 2005, there are
some beautiful features available using which we can handle the error.
When We Need To Handle Error in SQL Server
Generally a developer tries to handle all kinds of exception from the code itself. But sometimes we need to handle the same from the DB site
itself. There are some scenarios like, we are expecting some rows should come when we will execute the store procedure, but unfortunately SP
returns none of them. Below points can be some possible scenarios where we can use error handling:
While executing some DML Statement like INSERT, DELETE, UPDATE we can handle the error for checking proper output
If transaction fails, then we need to rollback - This can be done by error handling
While using Cursor in SQL Server
Error Handling Mechanism
The two most common mechanisms for error handling in SQL Server 2005 are:
@@ERROR
TRY-CATCH Block
Let's have a look at how we can implement both @@Error and Try-Catch block to handle the error in SQL Server 2005.
Using @@ERROR
We can consider @@ERROR as one of the basic error handling mechanisms in SQL Server. @@Error is a Global Variable in SQL Server. This
variable automatically populates the error message when a certain error occurred in any statement. But we have to trace it within just after the
next line where the actual error occurred, otherwise, it will reset to 0.
General Syntax
General syntax for @@ERROR is as follows:
Select @@ERROR
Return Type
int
It returns the Error Number.
Sample Example
I have a table named StudentDetails with columns, Roll (int), Name (varchar) and Address (varchar). Now I am intentionally trying to
insert a char in Roll field:
Collapse | Copy Code
insert into StudentDetails (roll,[Name],Address)
values ('a','Abhijit','India')
This will throw the following Error :
Collapse | Copy Code
Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the varchar value 'a' to data type int.
Check out the Message and number, it is 245. Now, I am executing the @@Error statement just after this statement and check out the output:
Collapse | Copy Code
Select @@Error
The output is:
So, @@Error returns the same error as return by insert command. As I have already said, @@Error returns the error number for the last
Transact-SQL statement executed, so if we execute any @@Error statement, we will get output 0.
When We Should Use @@Error
There are some scenarios where we should use @@ERROR:
With Insert, Delete, Update, Select Into Statement
While using Cursor in SQL Server (Open, Fetch Cursor)
While executing any Stored Procedure
Using Try...Catch Block
This is available from SQL Server 2005 Onwards. This is generally used where want to trap or catch error for multiple SQL statements like or a
SQL Block of statement. TRY...CATCH blocks are the standard approach to exception handling in modern programming languages. Use and
syntax are likely the same as normal programming language. Like Exception Handling in Programming Language, we can use nested Try-Catch
block in SQL Server also.
Try block will catch the error and will throw it in the Catch block. Catch block then handles the scenario.
General Syntax
-- SQL Statement
-- SQL Statement
BEGIN TRY
-- SQL Statement or Block
END TRY
BEGIN CATCH
-- SQL Statement or Block
END CATCH
-- SQL Statement
Whenever there are some errors in TRY Block, execution will moved to CATCH block.
Sample Example
As I have already discussed about the studentDetails table, I am now going to insert one record in the table with Roll='a'.
BEGIN TRY
INSERT INTO StudentDetails(Roll, [Name])
VALUES('a', 'Abhijit')
END TRY
BEGIN CATCH
SELECT 'There was an error while Inserting records in DB '
END CATCH
As Roll is an int type but I am trying to insert a char type data which will violate the type conversion rule, an error will be thrown. So the
execution pointer will jump to Catch block. And below is the output:
There was an error while Inserting records in DB
Now, to get the details of the error SQL Server provides the following System function that we can use inside our Catch-block for retrieving
the details of the error. Please check the below table:
Function Name Description
ERROR_MESSAGE() Returns the complete description of the error message
ERROR_NUMBER() Returns the number of the error
ERROR_SEVERITY() Returns the number of the Severity
ERROR_STATE() Returns the error state number
ERROR_PROCEDURE() Returns the name of the stored procedure where the error occurred
ERROR_LINE() Returns the line number that caused the error
Here is one simple example of using System Function:
BEGIN TRY
INSERT INTO StudentDetails(Roll, [Name])
VALUES('a', 'Abhijit')
END TRY
BEGIN CATCH
SELECT ' Error Message: ' + ERROR_MESSAGE() as ErrorDescription
END CATCH
I have executed the same code block here but rather than showing custom message, I am showing the internal Error message by Calling
ERROR_MESSAGE() System function. Below is the output:
Nested TRY-CATCH Block
Like other programming languages, we can use Nested Try catch block in SQL Server 2005.
Collapse | Copy Code
BEGIN TRY
print 'At Outer Try Block'
BEGIN TRY
print 'At Inner Try Block'
END TRY
BEGIN CATCH
print 'At Inner catch Block'
END CATCH
END TRY
BEGIN CATCH
print 'At Outer catch block'
END CATCH
If we execute this, the output will look like:
At Outer Try Block
At Inner Try Block
Now, Inner catch blocks throw an error:
BEGIN TRY
print 'At Outer Try Block'
BEGIN TRY
print 'At Inner Try Block'
INSERT INTO StudentDetails(Roll, [Name]) _
VALUES('a', 'Abhijit') -- Throwing Exception
END TRY
BEGIN CATCH
print 'At Inner catch Block'
END CATCH
END TRY
BEGIN CATCH
print 'At Outer catch block'
END CATCH
Which gives the following output:
At Outer Try Block
At Inner Try Block
At Inner catch Block
Try-Catch Block For Transaction Roll Back
Here I am going to explain one real life scenario of using TRY-CATCH block. One of the common scenarios is using Transaction. In a
Transaction, we can have multiple operations. If all operations executed successfully, then database will commit otherwise we need to
ROLLBACK.
/*
I want to delete a Particular Records from Both Student
Details and Library. Database will only commit, iff both
delete statement execute successfully, If fails it will Roll
back. Intentionally I have passed a wrong roll ( Which causes)
the exception and transaction will rollback.
*/
BEGIN TRY
-- Start A Transaction
BEGIN TRANSACTION
-- Delete Student From StudenDetails Table
DELETE FROM StudentDetails WHERE Roll = '1'
Print 'Delete Record from Student Details Table'
-- Delete The Same Student Records From Library Table also
DELETE FROM Library WHERE Roll = 'a'
Print 'Delete Record from Library Table'
-- Commit if Both Success
COMMIT
-- Update Log Details
Insert into LogDetails(ID,Details) values ('1','Transaction Successful');
END TRY
BEGIN CATCH
Print 'Transaction Failed - Will Rollback'
-- Any Error Occurred during Transaction. Rollback
IF @@TRANCOUNT > 0
ROLLBACK -- Roll back
END CATCH
Below is the output:
Collapse | Copy Code
Delete Record from Student Details Table
Transaction Failed - Will Rollback
Introduction- VIEWS
In this article I am going to describe about VIEW in SQL Server 2005. Though this is a simple topic, still I am writing This is not only about
view, I have made some plan to write a few article on SQL Server 2005. I hope this will also help you like my ASP.NET articles. Please give
me your valuable suggestion and feedback to improve my articles.
What is VIEW
A view is an "Virtual Table". It is not like a simple table, this is an virtual table which contains columns and data from different table ( may
be one or more tables) . View does not contain any data directly, it is a set of query that are applied to one or more tables that is stored within
the database as object. After creating a view from some Table, it just used as a reference of those table and when executed shows only those
data which are already mention in query during the creation of View
In the above diagram, we have created a View (View_Table1_Table2) from Table1 and Table2. So the View_Table1_Table2 will show only the
information of those columns. Let's checkout the basic syntax for creating a view:
Collapse | Copy Code
CREATE VIEW [View Name]
AS
[SELECT Statement]
Use of VIEW
Views are used as Security Mechanism of Database. Because it restricts user to view certain column and Rows. Views display only those data
which are mentioned in the query, so its shows only those data which returns by the query that is defined at the time of creation of view. So
rest data are totally abstract from the end user.
Along with Security the other advantages of view is Data abstraction. Because end user is not aware of all the data in Table.
General Syntax for View
In this section I have described how to create view, select data from view and deleting a view.
I have create on Database named, ViewDemo. It having on table called EmpInfo and below
diagram showing you the design of the table,
which contain following data
Here all the example I have descrived only from this database.
Creating a View
Below is the general syntax for creating a view
Collapse | Copy Code
CREATE VIEW [View_Name]
AS
[SELECT Statement]
As for example
Collapse | Copy Code
CREATE VIEW SampleView
As
SELECT EmpID, EmpName FROM EmpInfo
Which will create a view with name "SampleView", that will only contain EmpID, EMPName.
Get Result From View
This is as similar as select statement of a table
Collapse | Copy Code
select * from SampleView
Now have a look on the output of the SampleView
Drop a View
Collapse | Copy Code
DROP VIEW SampleView
Now if we want to select the data from the sampleview, we will get following error
Different Types of VIEW
There are two different types of VIEW
System View
Information Schema View
Catalog View
Dynamic Management View(DMV)
User Define View
Simple View
Complex View
Now just have a look on different types of View in SQL Server 2005.
System View
In SQL Server there are few System Database available, like Master, Temp, msdb, tempdb . Each and . Each and every data base having its
own responsibility, like master data is one of the template database for all the database which are created in SQL Server 2005. Similarly,
System Views are predefined Microsoft created views that are already existed in master DB. These are also used as template View for all new
database. These System Views will be automatically inserted into any user created database. There are around 230 System view available.
We can explore the System view from the SQL Server Management Studio. Expand any Database > View > System View
In SQL Server all system view are divided into different schema. These are used for the security container of SQL Server database. We can
categorized system view in following way,
Information Schema View
Catalog View
Dynamic Management View (DMV)
Now all above category are itself a huge topic, So I will not going to Details of It. Lets have a look into the over view of those view type
Information View
These are the one of the most important system grouped view. There are twenty different schema views in this group. This are used for
displaying most physical information of a database, such as table, columns. Naming Conation of this type of views are
INFORMATION_SCHEMA.[View Name] . From the System View Image we can get the few name of Information Schema View.
Lets see it with one Example,
I have create on Database named, ViewDemo. It having on table called EmpInfo and below diagram showing you the design of the table,
Now, if we want to know the details information columns of table Empinfo using View we have to run the following query,
Collapse | Copy Code
SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
Where TABLE_NAME='EmpInfo'
Following will be the output
Similarly we can use all other Schema View to read Database information.
Catalog View
This type of view are introduced in SQL Server 2005. catalog view are categorized in different group also. These are used to show the
database self describing information.
As for example,
Collapse | Copy Code
select * from sys.tables
and following is the sample output
Dynamic Management View
This is newly introduced in SQL Server 2005.This Views gives the database administrator information about the current state of the SQL
Server machine. These values will help the administrator to diagnose problems and tune the server for optimal performance. In SQL Server
2005, there are two types of DMV
1. Server-scoped DMV: Stored in Master Database
2. Database-scoped DMV: Specific to each database
As for example if we want to check the all SQL Server connection, we have to use following query,
Collapse | Copy Code
SELECT
connection_id,
session_id,client_net_address,
auth_scheme
FROM sys.dm_exec_connections
And following is the sample output
If you want to know details on DMV, Here is an Complete article on Code project , Dynamic Management Views [DMV] - A SQL Server 2005 Feature
[^]
Note: There are many things to learn on System View, I have just introduced them for beginners . If any one having more interest can have a
look into this article System Views in SQL Server 2005 [^]
User Define View
Still now I have described about System View, Now have a look into User Define View. This views are created by the user as per
requirement. There is no such classification of UDV and how to create the view, I have already explained the syntax. Now we can again have a
look into another view creation.
Collapse | Copy Code
CREATE VIEW DemoView
AS
SELECT EmpID, EmpName, Phone
FROM EmpInfFROM EmpInfo
When To Use A View
There are a number of scenarios where we will like to create our own view
1. To hide the complexity of the underlying database schema, or customize the data and schema for a set of users.
2. To control access to rows and columns of data.
View Creation Option
There are two different option for creating a view.
Schema Binding Option
Encryption
Schema BindSchema Binding Option :
If we Creates a view with the SCHEMABINDING option it will locks the tables being referred by the view and restrict any kinds of changes that
may change the table schema ( No Alter Command) . While creating schema binding view, we can't mention "Select * from tablename" with
the query. We have to mention all the column name for reference
As for example,
Collapse | Copy Code
CREATE VIEW DemoSampleView
With SCHEMABINDING
As
SELECT
EmpID,
EmpName,
FROM DBO.EmpInfo
And one more things that we need to remember, while specifying the Database name we have use Dbo.[DbName] .After creating the view, try
to alter the table EmpInfo , we cannot do it! This is the power of the SCHEMABINDING option.
If we want to change/Alter the defination of a table which refered by a schema binded view, we will get following error message.
Encryption :
This option encrypts the definitionThis option encrypts the definition of the view. Users will not be able to see the definition of the View after it
is created. This is the main adavatages of view where we can make it secure
Collapse | Copy Code
CREATE VIEW DemoView
With ENCRYPTION.EmpInfo
Note: Once view is encrypted, there is no way to decrypt it again.
Use SSMS for Create View
SQL Server MSQL Server Management studio provided handy GUI for creating and managing the View. In Object Explorer Tab, it listed all the
View with corresponding to its database. What is view, Syntax for creating view and all other stuff I have already covered. Now, In this section
we will just quickly check how SSMS used to create a maintain view.
First just expand da ViewDemoDB > Move to View . Right Click on View Folder.
When we will click on the New view , Following Screen will come . In the ViewDemoDB we are having two data tables. Now am going to create
View from EmpInfo Table
Select the EmpInfo, Click on Add. You will redirected to Create View Screen where you can configure the view creation. Check the following
image.
Above image showing three section, where we can select the table name or in below section, we can right query for view also. When its done.
Just click on Save button on toolbar. Give the name of View and click on Ok.
Now again go to ViewDemoDB > View > Expand View folder, Here along with system view you can see the view that we are created right now.
So, this is our user define View. If we right click on it, we will get the option of open the view and which will show the result of View.
We can also create a view from a view itself as similar way that we already done with table.
Summary
View is an "Virtual Table", which stored as an Object in a database. This can used as Security container of Database. We can Encrypt view
definition for making it secure. There are more than 230 System View available which having its own responsibility. We can create view
either writing T-SQL statement or using SQL Server Management Studio.
Overview of SQL Server 2005/2008 Table Indexing (Part-1)
1. Overview
Human needs have increased tremendously. Now people are doing much more composite tasks than ever before. The society has become very
complex, a person has to work with huge amount of information every day. In order to work with the enormous information, we must have a
system where we can store, manipulate and share the information all over the world. It is one of the core reasons for introducing Database
Management Systems (DBMS) as well as Relational Database Management Systems (RDBMS) now-a-days.
So, one thing is clear to us that we store and manipulate data / information into a database, where the database contains various types of
tables for storing various types of data / information.
Developers can create tables of a database; it would be possible to stop at this point and just start working with our data from here. However
this would not be one of our best choices, but why? Because it is not really a good idea for better performances, lets take an example:
A library has a huge collection of books, files, etc... A student requests the librarian for a book of Microsoft SQL Server 2008, if we
think without an index the librarian had to find this without any help s/he has to search one by one! Which must be time consuming;
so with a proper arrangement, that is with the help of an index, it very much easier and faster to find out the desired one.
There are many ways to create an index, but first of all we need to know what is an index is and how it is held within SQL Server.
2. What is an Index?
A SQL table explanation is not good enough for getting the desired data very quickly or sorting the data in a specific order. What we actually
need for doing this is some sort of cross reference facilities where for certain columns of information within a table, it should be possible to get
whole records of information quickly. But if we consider a huge amount of data in a table, we need some sort of cross reference to get to the
data very quickly. This is where an index within SQL Server comes in.
So an index can be defined as:
An index is an on-disk structure associated with a table or views that speed retrieval of rows from the table or view. An index
contains keys built from one or more columns in the table or view. These keys are stored in a structure (B-tree) that enables SQL
Server to find the row or rows associated with the key values quickly and efficiently.
An index is a database object created and maintained by DBMS. It is essentially a list of the contents of a column or group of
columns. Indexes are ordered so that extremely first search can be computed through them to find data.
3. Why Use an Index?
Use of SQL server indexes provide many facilities such as:
Rapid access of information
Efficient access of information
Enforcement of uniqueness constraints
Correct use of indexes can make the difference between a top performing database with high customer satisfaction and a non-performing
database with low customer satisfaction.
4. Types of Indexes
SQL Server has two major types of indexes:
1. Clustered
2. Non-Clustered
The index type refers to the way the index is stored internally by SQL Server. So a table or view can contain the two types of indexes.
4.1 Clustered
An index defined as being clustered, defines the physical order that the data in a table is stored. Only one cluster can be defined per table. So
it can be defined as:
Clustered indexes sort and store the data rows in the table or view based on their key values. These are the columns included in the
index definition. There can be only one clustered index per table, because the data rows themselves can be sorted in only one order.
The only time the data rows in a table are stored in sorted order is when the table contains a clustered index. When a table has a
clustered index, the table is called a clustered table. If a table has no clustered index, its data rows are stored in an unordered
structure called a heap.
4.2 Non-Clustered
As a non-clustered index is stored in a separate structure to the base table, it is possible to create the non-clustered index on a different file
group to the base table. So it can be defined as:
Non-Clustered indexes have a structure separate from the data rows. A non-clustered index contains the non-clustered index key
values and each key value entry has a pointer to the data row that contains the key value.
The pointer from an index row in a non-clustered index to a data row is called a row locator. The structure of the row locator depends
on whether the data pages are stored in a heap or a clustered table. For a heap, a row locator is a pointer to the row. For a clustered
table, the row locator is the clustered index key.
You can add nonkey columns to the leaf level of the Non-Clustered index to by-pass existing index key limits, 900 bytes and 16 key
columns, and execute fully covered, indexed, queries.
More information about indexes can be found at this link.
Both clustered and non-clustered indexes can be unique. This means no two rows can have the same value for the index key. Otherwise, the
index is not unique and multiple rows can share the same key value.
Note: Indexes are automatically maintained for a table or view whenever the table data is modified.
5. Uniqueness
An index can be defined either as unique or non-unique. A unique index ensures that the data contained within the unique index columns
appear only once within the table, including NULL. A unique index is commonly implemented to support the constraints.
SQL Server automatically enforces the uniqueness of the columns contained within a unique index. If an attempt is made to INSERT a
value/data that already exists in the table, then an error will be generated by the SQL Server and finally the attempt to INSERT the data will
fail.
A non-unique index is also applicable as there can be duplicate data; a non-unique index has more overhead than a unique index when
retrieving data.
6. Creating a Table
What is a table? The foundation of every Relational Database Management System is a database object called table. Every database consists of
one or more tables, which stores the databases data/information. Each table has its own unique name and consists of columns and rows.
Syntax of Creating Table
Collapse | Copy Code
CREATE TABLE
[ database_name.[ owner ] . | owner. ] table_name
( { < column_definition >
| column_name AS computed_column_expression
| < table_constraint > } [ ,...n ]
)
In this article, we will not discuss database tables. I hope that every one knows the basic concepts about database tables.
More information about database tables can be found at:
SQL Database Table
Create Table
7. Creating an Index
As we discuss what an index is, why we use an index, types of indexes, etc, we are going to discuss how to create an index. There are two
ways of creating an index they are as follows:
Creating an Index using SQL Server Table Designer
Creating an Index using Transact-SQL
7.1 Creating an Index using by SQL Server Table Designer
SQL Server Table designer is an excellent feature to manage various tables designing creation, modification, indexing and so much more.
Here you need to follow the step(s) below to create an index using the SQL Table designer.
Step(s)
1. Open your SQL Server Enterprise Management Studio and choose your database for creating a table index. Now select your desired
table and open the Table Design window. The following figure shows how to do this.
Figure 1 (How to open SQL Table Designer)
2. A window will appear where you will find all the available inputs for creating a Table. You just need to input the columns name, data
type length and also you may set the columns to allow null value or not. Note that you can set a default value of a column. The
following figure will show you how you can perform all of this:
Figure 2 (How to set table columns, data type, length, etc.)
3. Well, now you know how to create a table. Let's see how to set an index in a table. Select the column by clicking your mouse button,
a new popup menu will appear, select/click the Indexes/Keys for opening a new window where you can configure the columns for
indexing. The following figure will show how to set an index.
Figure 2.1 (A) (How to configure an Index)
Figure 2.1 (B) (How to Configure an Index)
4. Now you just select the column from the general properties as shown in figure 3, and add the specify column short order of the index.
Figure 4 (How to set a Clustered Index)
You can configure the index as clustered or non-clustered from the Create as clustered properties. Figure 4 shows the configuration of
clustered or non-clustered indexes by default.
So we discussed how to create an index by using SQL Server Table Designer. Lets try to create an index by using Transact-SQL.
7.2 Creating an Index Transact-SQL
If we want to create an index by using Transact SQL , we must know the columns detail for index creation. A sample syntax is given below.
Syntax
Collapse | Copy Code
CREATE INDEX <index_type> <index_name> ON <table_name> (
<column_name1> <index_order>,
<column_name2> <index_order>,
)
CREATE UNIQUE INDEX <index_type> <index_name> ON <table_name> (
<column_name1> <index_order>,
<column_name2> <index_order>,
)
7.3 Drop an Index
Removes one or more indexes from the current database.
The DROP INDEX statement does not apply to indexes created by defining PRIMARY KEY or UNIQUE constraints (created by using the PRIMARY
KEY or UNIQUE options of either the CREATE TABLE or ALTER TABLE statements, respectively). For more information about PRIMARY or UNIQUE
KEY constraints, see "CREATE TABLE" or "ALTER TABLE" in this volume.
Syntax
Collapse | Copy Code
DROP INDEX 'table.index | view.index' [ ,...n ]
More information about drop indexes can be found at this link.
8. Index and Statistics
When retrieving data, SQL Server obviously has to make some decisions as to the best way to get to data and return it to the query
requesting it. So SQL Server has some basic information to make sensible and accurate choices. This is where statistics comes in. SQL Server
keeps statistics on each column, which are updated over a period of time and over a number of inserts or modifications.
More information about indexes and statistics can be found at this link.
9. Summary
In this article, I tried to cover SQL table indexing. I discussed why we use indexes and how they are used to quick and efficiently retrieve the
data stored in the table. I also discussed various types of indexes, how to create / drop index, index uniqueness and index statistics as well.