Should be a pretty straight forward question. Can I add an INDEX to a Common Table Expression (CTE)?
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
.