Skip to content
Advertisement

How to create indexed view of children count

I am trying to take a table with a parent child relationship and get the number of children. I would like to create an indexed view of the number of children by utilizing COUNT_BIG(*).

The problem is that in my index view I don’t want to eliminate the entities who have no children, instead I want the Count to be 0 for those.

Given

I want to create an indexed view that returns

Here is my SQL that works, but using a LEFT JOIN and a CTE (both are not allowed in an index view)

Advertisement

Answer

I don’t think you can achieve that using a CTE neither a LEFT JOIN because there are many restriction using the indexed views.

Workaround

I suggest splitting the query into two part:

  1. Create an indexed view instead of a common table expression (CTE)
  2. Create a non indexed view that perform the LEFT JOIN

Beside that, create a Non-Clustered index on Entity column in Table Example .

Then when you query the non-indexed view, it will use indexes

So when you perform the following query:

You can see that the view Clustered index and the Table Non-Clustered index are used in the execution plan:

enter image description here

Additional Information

I didn’t find additional workarounds to replace the use of LEFT JOIN or UNION or CTE in indexed views, you can check many similar Stackoverflow questions:


Update 1 – Splitting view vs. Cartesian join

To identify the better approach, i tried to compare both suggested approaches.

I created each indexed view on seperate databases and performed the following query:

Splitting view

enter image description here

Cartesian Join

enter image description here

Time Statistics

The time statistics shows that the Cartesian join approach execution time is higher than the Splitting view approach, as shown in the image below (cartesian join to the right):

enter image description here

Adding WITH(NOEXPAND)

Also i tried to add WITH(NOEXPAND) option the the cartesian join approach, to force the database engine to use the indexed view clustered index and the result was as following:

enter image description here

I cleared all caches and perform a comparison, the Time statistics comparison shows that the Splitting view approach is still faster than the cartesian join approach (WITH(NOEXPAND) approach to the right):

enter image description here

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement