Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an INDEX to a CTE

Can I add an INDEX to a Common Table Expression (CTE)?

like image 701
Neil Knight Avatar asked Oct 22 '10 10:10

Neil Knight


People also ask

Can I put an index on a CTE?

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.)

Can we create index on CTE in postgresql?

No you can not create an index on parts of a query, during the query. CTE (common table expressions), is also called Subquery Factoring.

Can you update a CTE table?

If your CTE is based on a single table then you can update using CTE, which in turn updates the underlying table.

Can you use DML on a CTE?

CTE can be used for both selects and DML (Insert, Update, and Delete) statements.


2 Answers

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

like image 72
Richard Vivian Avatar answered Sep 24 '22 23:09

Richard Vivian


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.

like image 44
marc_s Avatar answered Sep 25 '22 23:09

marc_s