Slow distinct query in SQL Server over large dataset

前端 未结 10 2628
情深已故
情深已故 2021-02-14 00:27

We\'re using SQL Server 2005 to track a fair amount of constantly incoming data (5-15 updates per second). We noticed after it has been in production for a couple months that on

10条回答
  •  我寻月下人不归
    2021-02-14 00:58

    There is an isse with the SQL Server optimizer when using the DISTINCT keyword. The solution was to force it to keep the same query plan by breaking out the distinct query separately.

    So we too queries such as:

    SELECT DISTINCT [typeName] FROM [types] WITH (nolock);
    

    and break it up into the following

    SELECT typeName INTO #tempTable1 FROM types WITH (NOLOCK)
    SELECT DISTINCT typeName FROM #tempTable1
    

    Another way to get around it is to use a GROUP BY, which gets a different optimization plan.

提交回复
热议问题