- Choose the Appropriate Data Types
- Use Triggers Cautiously
- Use views and stored procedures instead of heavy queries.
- Use constraints instead of triggers
- Use UNION ALL statement instead of UNION, whenever possible.
- Try to avoid using the DISTINCT clause, whenever possible.
- Try to avoid the HAVING clause, whenever possible.
The HAVING clause is used to restrict the result set returned by the GROUP BY clause. When you use GROUP BY with the HAVING clause, the GROUP BY clause divides the rows into sets of grouped rows and aggregates their values, and then the HAVING clause eliminates undesired aggregated groups. In many cases, you can write your select statement so, that it will contain only WHERE and GROUP BY clauses without HAVING clause. This can improve the performance of your query. If you need to return the total table’s row count, you can use alternative way instead of SELECT COUNT(*) statement. There r 2 ways to do this
SELECT COUNT(*) statement makes a full table scan to return the total table’s row count, it can take very many time for the large table. There is another way to determine the total row count in a table. You can use sysindexes system table, in this case. There is ROWS column in the sysindexes table. This column contains the total row count for each table in your database.
SELECT rows FROM sysindexes WHERE id = OBJECT_ID('table_name')
So, you can improve the speed of such queries in several times.
- Use SET NOCOUNT ON statement into your stored procedures to stop the message indicating the number of rows affected by a T-SQL statement. This can reduce network traffic, because your client will not receive the message indicating the number of rows affected by a T-SQL statement.
- Use the WHERE clause.
- Use the select statements with TOP keyword or the SET ROWCOUNT statement if you need to return only the first n rows. This can improve the performance of your queries because smaller result set will be returned. This can also reduce the traffic between the server and the clients.
- Return only the particular columns from the table, not all columns/ Avoid using “Select *”
- Create Index where appropriate
- Avoid using Temp Tables inside stored procedures
- Use table variables instead of temporary tables.
- Avoid Using Cursors
SQL Server cursors can result in some performance degradation in comparison with select statements. Try to use correlated sub-query or derived tables, if you need to perform row-by-row operations
- Use Joins Appropriately
FROM names INNER JOIN departments ON names.employeeid = departments.employeeid
WHERE names.employeeid = departments.employeeid
SELECT * FROM Orders INNER JOIN [Order Details] ON Orders.OrderID = [Order Details].OrderID
FROM Orders INNER JOIN [Order Details] ON Orders.OrderID = [Order Details].OrderID