Pages

Saturday, August 27, 2016

SQL Server Performance Tips

1. Data Type Precedence
The order of data type precedence of the given options from highest to lowest: DATETIME, FLOAT, NUMERIC, MONEY, INT and VARCHAR.
2. Operator Precedence
Below are the list of operators in their order of performance (with the most efficient first).
=
>, >=, <, <=
LIKE
3. Where Clause in SQL Statements
If we have a WHERE clause that includes expressions connected by two or more AND operators, SQL Server will evaluate them from left to right in the order they are written (assuming that there are no parenthesis used in the statement). Consider one of the following when using AND:
  • Locate the least likely true AND expression first. This way, if the AND expression is false, the clause will end immediately, saving time.
  • If both parts of an AND expression are equally likely being false, put the least complex AND expression first. This way, if it is false, less work will have to be done to evaluate the expression.
4. String Functions in SQL Statements
Avoid using of string functions in the statements as it is not a fast process in SQL Server.
5. Between Clause rather than IN Clause
Use the BETWEEN clause which is more efficient rather than using IN clause in the statements.
6. Functions used in Where Clause
If a function is used for a column in the WHERE clause ,the SQL statement will not be able to make use of any indexes applied to that column.
Example:
1
2
3
4
SELECT
   *
FROM Emp
WHERE CONVERT(VARCHAR, HireDate, 112) = CONVERT(VARCHAR, GETDATE(), 112)
7. Using IN and NOT IN clauses in Where Clause in SQL Statements
If we are using IN or NOT IN in a WHERE clause which contains a sub-query, re-write it by using either EXISTS, NOT EXISTS or use a LEFT OUTER JOIN, as NOT IN statement offers really poor performance.
8. Avoiding Network traffic when a Store Procedure is executed
By default, every time a stored procedure is executed, a message is sent from the server to the client indicating the number of rows that were affected by the stored procedure. We can reduce network traffic between the server and the client by adding SET NO COUNT ON at the beginning of the stored procedure.
9. Using of Transactions
If we are using SQL transactions, try to keep them as short as possible. This will help db performance by reducing the number of locks. Remove anything that doesn’t specifically need to be within the transaction like setting variables, select statements etc.
10. Using of Temporary Tables
Even though using temporary tables is sometime better, generally they are best recommended to be eliminated from the stored procedures. Consider using a sub-query or derived table instead of a temporary table . If we are using a temporary table consisting of JOINS in the SP and if it contains loads of data, it is recommended to add an index to your temporary table as this may also improve performance.
11. How to call a Store Procedure
Whenever a Store Procedure is called, it is recommended to call or execute the SP by using the SchemaName.StoreProcName. Example: EXEC dbo.USP_Test, as it will stop SQL Server from placing a COMPILE lock on the procedure while it determines if all objects referenced in the code have the same schema as the objects in the current cached procedure plan.
12. Naming Convention for Store Procedure at the time of creation
Whenever any SP is created in a database, it is recommended to create the SP starting with USP (User Defined Store Procedure) instead of creating the SP which starts with ‘SP_’. If any SP is created starting with ‘SP_’, then SQL Server will initially search for the procedure in the Master database and then it searches the database from which the proc was called. This will cause a time consuming in executing the store procedure.
13. Avoid using DISTINCT clause if unnecessary
A UNION statement is similar to the SELECT DISTINCT . If we know that all the records returned are unique from the union, then use UNION ALL instead, which is much faster. Do not use SELECT DISTINCT clause if it is not required as it may cause unnecessary performance.
14. Use of Where Clause
Retrieve the data from the statements only that is required. Use WHERE clause wherever required.
15. Usage of Cursors
Do not use Cursors as they slow down the SQL Server’s Performance. While in some cases they are unavoidable, we can avoind using of cursors by using any of below options which are faster than cursors.
Derived tables
Sub-queries
CASE statements
Multiple queries
Temporary tables

Assigning Values dynamically in SQL Server

If we want to assign a value to a variable in a Dynamic Query, then it throws an error. Below is an example:
1
2
3
DECLARE @V_SQL VARCHAR(MAX), @Row_Cnt_Stg INT
SET @V_SQL ='SELECT @ROW_CNT_STG= COUNT(*) FROM TEST.dbo.TEST_EMP'
EXEC(@V_SQL)
If we execute above query, then the below error is raised:
1
2
Msg 137, Level 15, State 1, Line 1
Must declare the scalar variable "@Row_Cnt_Stg".
Even though we have declared the variable @Row_Cnt_Stg as Integer datatype, still SQL will raise error as above. In order to overcome this error use the below statements. When we execute the below query it will assign the value to the variable :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
-- Declaring Variables
DECLARE @V_SQL VARCHAR(MAX), @Row_Cnt_Stg INT,  @TableName  VARCHAR(20), @DatabaseName  VARCHAR(20)
 
-- Assigning the values to the variables
SET @DatabaseName = DB_NAME(DB_ID())
SET @TableName = 'TEST_EMP'
 
-- Assigning the Dynamic Queries using the variables
SET @SQL = 'SELECT @Row_Cnt_Stg =COUNT(*) FROM ' + @DATABASENAME + '.dbo.' + @TableName
PRINT(@SQL)
 
-- Executing the Dynamic query
EXEC SP_EXECUTESQL @V_SQL, N'@Row_Cnt_Stg INT OUTPUT', @Row_Cnt_Stg OUTPUT
 
-- Selecting the values from the variable that is assigned in the Dynamic Query
SELECT @Row_Cnt_Stg