Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't indexed views have a MAX() aggregate?

I have been trying out a few index views and am impressed but I nearly always need a max or a min as well and can not understand why it doesn't work with these, can anyone explain why?

I KNOW they are not allowed, I just can't understand why!!! Count etc. is allowed why not MIN/MAX, I'm looking for explanation...

like image 783
alex Avatar asked Jan 25 '10 18:01

alex


People also ask

What is the restriction on indexed view?

It can't contain COUNT, MIN, MAX, TOP, outer joins, or a few other keywords or elements. You can't modify the underlying tables and columns. The view is created with the WITH SCHEMABINDING option.

Can we do indexing on views?

Indexes can only be created on views which have the same owner as the referenced table or tables. This is also called an intact ownership-chain between the view and the table(s). Typically, when table and view reside within the same schema, the same schema-owner applies to all objects within the schema.

Do indexes help aggregate?

There are at least three different ways indexes can improve aggregate query performance: INDEX FULL SCAN (MIN/MAX) , INDEX FAST FULL SCAN , and INDEX FULL SCAN / SORT GROUP BY NOSORT .

Can you index a view in SQL?

Introduction to SQL Server indexed viewTo create an indexed view, you use the following steps: First, create a view that uses the WITH SCHEMABINDING option which binds the view to the schema of the underlying tables. Second, create a unique clustered index on the view. This materializes the view.


1 Answers

These aggregates are not allowed because they cannot be recomputed solely based on the changed values.

Some aggregates, like COUNT_BIG() or SUM(), can be recomputed just by looking at the data that changed. These are allowed within an indexed view because, if an underlying value changes, the impact of that change can be directly calculated.

Other aggregates, like MIN() and MAX(), cannot be recomputed just by looking at the data that is being changed. If you delete the value that is currently the max or min, then the new max or min has to be searched for and found in the entire table.

The same principle applies to other aggregates, like AVG() or the standard variation aggregates. SQL cannot recompute them just from the values changed, but needs to re-scan the entire table to get the new value.

like image 131
Remus Rusanu Avatar answered Sep 18 '22 14:09

Remus Rusanu