My query is picking a bad execution plan , how to fix it ?

 Outdated Statistics: If the statistics on a table or index are outdated, the optimizer may choose a bad execution plan. For example, if you have a table with a large number of rows, but the statistics haven't been updated in a while, the optimizer may underestimate the number of rows and choose a less efficient execution plan. You can update statistics using the following command:


UPDATE STATISTICS <table or index name>



Query Hints: Query hints can be used to force the optimizer to use a particular execution plan. For example, if you have a query that uses a join, but the optimizer is choosing a nested loop join instead of a hash join, you can add a query hint to force the optimizer to use a hash join:


SELECT *

FROM table1

JOIN table2

ON table1.column1 = table2.column2

OPTION (HASH JOIN)



Query Rewrite: Sometimes, rewriting a query can make it more efficient. For example, if you have a query that uses a subquery, but the optimizer is choosing to execute the subquery for every row in the outer query, you can rewrite the query to use a join instead:


-- Bad Execution Plan

SELECT *

FROM table1

WHERE column1 IN (SELECT column2 FROM table2)


-- Better Execution Plan

SELECT *

FROM table1

JOIN table2

ON table1.column1 = table2.column2



Adding Indexes: Adding appropriate indexes can help the optimizer choose a better execution plan. For example, if you have a query that searches for a specific value in a large table, but there is no index on the column being searched, the optimizer may choose to do a full table scan instead of using an index. You can use the Database Engine Tuning Advisor to suggest indexes:


EXEC sp_createindex 'table1', 'column1'



Plan Guides: Plan guides can be used to force the optimizer to use a particular execution plan for a query. For example, if you have a query that is running slowly and you know that a particular execution plan is more efficient, you can create a plan guide:


EXEC sp_create_plan_guide 

@name = N'PlanGuide1', 

@stmt = N'SELECT * FROM table1 WHERE column1 = @param1', 

@type = N'SQL',

@params = N'@param1 INT',

@hints = N'OPTION (HASH JOIN)'


Trace Flag: Trace flags can be used to turn on or off specific behaviors in SQL Server. For example, if you have a query that is running slowly and you suspect that the optimizer is choosing a bad execution plan because of parameter sniffing, you can turn on trace flag 4136:


DBCC TRACEON (4136, -1)


Comments

Popular posts from this blog

How to make CRS and ASM not to restart after server reboot

How to repair ASM disk header

Understanding Terraform