Adding an INDEX to a CTE

前端 未结 4 599
清歌不尽
清歌不尽 2020-12-05 04:13

Should be a pretty straight forward question. Can I add an INDEX to a Common Table Expression (CTE)?

相关标签:
4条回答
  • 2020-12-05 04:58

    I have had the same requirement. Indexes can not be added to a CTE. However, in the CTE select adding an ORDER BY clause on the joined fields reduced the execution time from 20 minutes or more to under 10 seconds.

    (You need to also ADD SELECT TOP 100 PERCENT to allow an ORDER BY in a CTE select.)

    [edit to add paraphrased quote from a comment below]:
    If you have DISTINCT in the CTE then TOP 100 PERCENT doesn't work. This cheater method is always available: without needing TOP at all in the select, alter the ORDER BY statement to read:
    ORDER BY [Blah] OFFSET 0 ROWS

    0 讨论(0)
  • 2020-12-05 05:08

    No.

    A CTE is a temporary, "inline" view - you cannot add an index to such a construct.

    If you need an index, create a regular view with the SELECT of your CTE, and make it an indexed view (by adding a clustered index to the view). You'll need to obey a set of rules outlined here: Creating an Indexed View.

    0 讨论(0)
  • 2020-12-05 05:08

    You cannot index a CTE, but the approach is that the CTE can make use of the underlying indexes.

    WITH cte AS (
        SELECT myname, SUM(Qty) FROM t GROUP BY myname
    )
    SELECT *
    FROM t a JOIN cte b ON a.myname=b.myname 
    

    In the above query, a JOIN b cannot make use of an index on t.myname because of the GROUP BY.

    On the other hand,

    WITH cte AS (
        SELECT myname, SUM(Qty) OVER (PARTITION BY myname) AS SumQty, 
                    ROW_NUMBER() OVER (PARTITION BY myname ORDER BY myname, Qty) AS n
    )
    SELECT * FROM t a JOIN cte b ON a.myname=b.myname AND b.n=1 
    

    In the latter query, a JOIN b can make use of an index on t.myname.

    0 讨论(0)
  • 2020-12-05 05:08

    @B H - To get around the DISTINCT problem with using TOP 100% or TOP 1000000, you could always use GROUP BY. Serves the same purpose and is sometimes faster than DISTINCT.

    0 讨论(0)
提交回复
热议问题