TSQL OPTIMIZATIONS
Microsoft SQL Server 2012
Tips and tricks toward making
queries perform better
Microsoft SQL Server 2012
OPTIMIZATION TECHNIQUES
Avoid subqueries
Avoid LEFT JOINS
Limit the number of Joins
Filter out unwanted records
Explicitly mention columns
Create and use proper indexes
Avoid Distinct, Union, Not In operators
Use SET NO COUNT ON
OPTIMIZATION TECHNIQUES
CONTD.
Use TABLE VARIABLES instead of Temp tables
Avoid dynamic sql
Avoid recompiles
Use IF EXIST instead of COUNT(*)
Use COUNT(1) instead of COUNT(*)
Avoid functions on columns in the Where clause
OPTIMIZATION TECHNIQUES
CONTD.
Avoid cursors
Favor set-based logic over procedural or cursor logic
Avoid query hints
Use correlated subqueries to improve performance
Avoid using a scalar user-defined function in the WHERE clause
Avoid unnecessary GROUP BY columns
Use CASE expressions to include variable logic in a query
Divide joins into temporary tables when you query very large tables
OPTIMIZATION TECHNIQUES
CONTD
Minimize transaction times
Optimize the SPs to reduce the lock duration
Combine updates
Always access server objects in same order for similar operations
Apply covering indexes when having multiple column filters
Reduce lookups
Execution Plans and
Operators
WHAT HAPPENS TO QUERY??
Parser: Validation for Syntactical errors.
Example (Select * from <table Name>,
syntax error)
Algebrizer:
Does Name resolution
Tables, Views, Columns
Object Not found is an error from
Algebrizer
Aggregations with Group By (Below
example parser validation is OK but not
algebrizer)
select LoginID, COUNT(EmployeeID) from
AdventureWorksDW.HumanResources.Employee
Group by Title
Algebrizer provides Query Processor
Tree for Optimizer
Optimizer generates query Execution
plan.
Execution Engine and Storage Engine
Execute query
WHAT DOES OPTIMIZER DO TO
PLAN
WHAT A QUERY PLAN SHOWS
QUERY PLAN
JOINS IN GRAPHICAL SHOWPLAN
JOINS
NESTED
LOOP JOIN
NESTED
LOOPJOIN
NESTED LOOP JOIN
MERGE
JOIN
MERGE
JOIN
MERGE JOIN
HASH
HASHJOIN
JOIN
HASH JOIN
AGGERIGATION
SUBOPTIMAL PLANS