Azure sql query is slow when an indexed column use

2019-05-26 11:27发布

问题:

Instance: Azure SQL S2 instance We have a candidates table which has ~1.7Million records. candidates table is indexed on non-primary key AccountID. AccountID:646 has 80K rows and AccountID:10 has 365K rows.

When we fire select top(10) from table where non_pk_indexed_col=int

Select top(10) from candidates where accountid=10

the query completes with 00:00:00 time taken

Select top(10) from candidates where accountid=646

, the query completes with 01:45:00 time taken

Why would the same query take such a long time when the value is different

回答1:

Most likely you are getting very different query plans for these two parameters. As such one performs significantly better than the other. One way to check would be to get your actually execution plan and check it out.

You can do that by pushing the Include Actual Execution Plan button in SSMS (about seven to the left of the Execute button) https://msdn.microsoft.com/en-us/library/ms189562.aspx

As said by Neil though, you will traditionally fix a poor execution plan with updating stats. You will want to update with fullscan though to get the best possible results, you can do that by running this query:

DECLARE @sql nvarchar(MAX);
SELECT @sql = (SELECT 'UPDATE STATISTICS [' + DB_NAME() + '].[' + rtrim(sc.name) + '].[' + rtrim(so.name) + '] WITH FULLSCAN, ALL; '
from sys.sysobjects so
join sys.schemas sc
on so.uid = sc.schema_id
where so.xtype = 'U' 
               FOR XML PATH(''), TYPE).value('.', 'nvarchar(MAX)');
PRINT @sql
EXEC (@sql)

Hopefully that helps out!



回答2:

I had a similar issue that was fixed by running exec sp_updatestats. I had to run it on each table in the complex query. I guess the query index on one of the tables was corrupt.

In your case the command would be UPDATE STATISTICS candidates

Thomas LaRock's article covers this in more depth.