سؤال

I created indexed view (clustered unique index on Table1_ID) view with such T-SQL:

Select Table1_ID, Count_BIG(*) as Table2TotalCount from Table2 inner join
Table1 inner join... where Table2_DeletedMark=0 AND ... Group BY Table1_ID

Also after creating the view, we set clustered unique index on column Table1_ID.
So View consists of two columns:

Table1_ID
Table2TotalCount

T-Sql for creating View is a heavy because of group by and several millions of rows in Table2.

But when I run a query to a view like

Select Total2TotalCount from MyView where Table1_ID = k

- it executes fast and without overhead for server.

Also in t-sql for creating view many conditions in where clause for Table2 columns. And If I changed Table2_DeletedMark to 1 and run a query

Select Total2TotalCount from MyView where Table1_ID = k

again - I'll get correct results. (Table2TotalCount decreased by 1).

So our questions are:
1. Why does query execution time decreased so much when we used Indexed View (compare to without view using (even we run DBCC DROPCLEANBUFFERS() before executing query to VIEW))
2. After changing

Table2_DeletedMark 

View immediately recalculated and we get correct results, but what is the process behind? we can't imagine that sql executes t-sql by what view was generated each time we changes any values of 10+ columns containing in the t-sql view generating, because it is too heavy.
We understand that it is enough to run a simple query to recalculate values, depends on columns values we changing.
But how does sql understand it?

هل كانت مفيدة؟

المحلول

An indexed view is materialized e.g. its rows that it contains (from the tables it depends on) are physically stored on disk - much like a "system-computed" table that's always kept up to date whenever its underlying tables change. This is done by adding the clustered index - the leaf pages of the clustered index on a SQL Server table (or view) are the data pages, really.

Columns in an indexed view can be indexed with non-clustered indexes, too, and thus you can improve query performance even more. The down side is: since the rows are stored, you need disk space (and some data is duplicated, obviously).

A normal view on the other hand is just a fragment of SQL that will be executed to compute the results - based on what you select from that view. There's no physical representation of that view, there are no rows stored for a regular view - they need to be joined together from the base tables as needed.

نصائح أخرى

Why do you think there are so many bizarre rules on what's allowed in indexed views, and what the base tables are allowed to do? It's so that the SQL engine can immediately know "If I'm touching this row, it potentially affects the result of this view - let's see, this row no longer fits the view criteria, but I insisted on having a COUNT_BIG(*), so I can just decrement that value by one"

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top