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
Does
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
Does
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
Does
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
Does
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. where
ProductID IN (Select distinct ProductID from tblOrder)
4. --Best
practice
5. SELECT
Name,Price FROM tblProduct
6. where
ProductID EXISTS (Select distinct ProductID from tblOrder)
6.
Avoid
Having Clause
Does
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
Does
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
Does
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.
9.
Avoid
Cursors
Does
practice to avoid cursor since cursor are very slow in performance. Always try
to use SQL Server cursor alternative.
10.
Use Table
variable inplace of Temp table
Does
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
Does
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
Does
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. --Here dbo is schema name
2. SELECT
col1,col2 from dbo.tblName
3. --
Avoid
4. SELECT
col1,col2 from tblName
13.
Keep
Transaction small
Does
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.
14.
SET
NOCOUNT ON
Does
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
Does
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.
16.
Use Stored
Procedure for frequently used data and more complex queries
Does
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
Does
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.
Different Types of SQL Server Stored Procedures
A stored procedure is a precompiled set of one or more SQL
statements that is stored on Sql Server. Benifit of Stored Procedures is that
they are executed on the server side and perform a set of actions, before
returning the results to the client side. This allows a set of actions to be
executed with minimum time and also reduce the network traffic. Hence stored
procedure improve performance to execute sql statements.
Stored procedure can accepts input and output parameters. Stored procedure
can returns multiple values using output parameters. Using stored procedure, we
can Select,Insert,Update,Delete data in database.
Types of Stored Procedure
1. System
Defined Stored Procedure
These stored procedure are already defined in Sql
Server. These are physically stored in hidden Sql Server Resource Database and
logically appear in the sys schema of each user defined and system defined
database. These procedure starts with the sp_ prefix. Hence we don't use this
prefix when naming user-defined procedures. Here is a list of some useful
system defined procedure.
System Defined Stored Pocedure
System Procedure
Description
sp_rename
It is used to rename an database object like stored
procedure,views,table etc.
sp_changeowner
It is used to change the owner of an database object.
sp_help
It provides details on any database object.
sp_helpdb
It provide the details of the databases defined in the Sql
Server.
sp_helptext
It provides the text of a stored procedure reside in Sql
Server
sp_depends
It provide the details of all database objects that depends
on the specific database object.
2. Extended
Procedure
Extended procedures provide an interface to
external programs for various maintenance activities. These extended procedures
starts with the xp_ prefix and stored in Master database. Basically these are
used to call programs that reside on the server automatically from a stored
procedure or a trigger run by the server.
Example Below statements are used to log an
event in the NT event log of the server without raising any error on the client
application.
1. declare @logmsg varchar(100)
2. set @logmsg = suser_sname() + ': Tried to access the dotnet system.'
3. exec xp_logevent 50005, @logmsg
4. print @logmsg
Example The below procedure will display
details about the BUILTIN\Administrators Windows group.
5. EXEC xp_logininfo 'BUILTIN\Administrators'
3. User
Defined Stored Procedure
These procedures are created by user for own
actions. These can be created in all system databases except the Resource
database or in a user-defined database.
4. CLR
Stored Procedure
CLR stored procedure are special type of procedure
that are based on the CLR (Common Language Runtime) in .net framework. CLR
integration of procedure was introduced with SQL Server 2008 and allow for
procedure to be coded in one of .NET languages like C#, Visual Basic and F#. I
will discuss CLR stored procedure later.
Note
1. We
can nest stored procedures and managed code references in Sql Server up to 32
levels only. This is also applicable for function, trigger and view.
2. The
current nesting level of a stored procedures execution is stored in the
@@NESTLEVEL function.
3. In
Sql Server stored procedure nesting limit is up to 32 levels, but there is no
limit on the number of stored procedures that can be invoked with in a stored
procedure