No, SQL Server never caches a view’s result set. A standard view is expanded into the calling query, and results are recomputed every time. Only execution plans and underlying data pages are cached. Indexed views are the only case where results are physically stored not cached.
In Microsoft
SQL Server, a non-indexed view stores ONLY metadata (the SELECT definition) and
it is expanded into the outer query with having no independent execution and
also do not have persisted rows due to that nothing to cache as a result set.
Let’s see the
demo
Non indexed
view
Creating a
table inserting few records and creating view
|
CREATE TABLE dbo.orderDemo ( OrderID
INT IDENTITY PRIMARY KEY,
CustomerID INT NOT NULL, Amount
MONEY NULL ); INSERT INTO dbo.orderDemo (CustomerID, Amount) VALUES (1, 100), (1, 200), (2, 300), (2, 400); create view vw_orderDemo as select orderId,CustomerID, Amount from dbo.orderDemo |
See the data in
view
When we are
running the view internally it run as
select orderId,CustomerID, Amount from
dbo.orderDemo
The view disappears during
optimization.
SQL Server caches the compiled
execution plan that applies to Ad-hoc queries and Stored procedures and Queries
referencing views. Keep in mind Plan cache ≠ data cache.View result set is NOT
cached because no persisted rows in view and No reuse of previously returned
results. Each execution logically recomputes the result.
Indexed View does cache data because
it is physically stored.
Creating an index view
|
CREATE VIEW dbo.orderSummary WITH SCHEMABINDING AS SELECT CustomerID, COUNT_BIG(*) AS TotalOrders FROM dbo.orderDemo GROUP BY CustomerID; GO CREATE UNIQUE CLUSTERED INDEX IX_OrderSummary ON dbo.orderSummary(CustomerID); |
See the data from this view.
Result is materialized on disk.
Maintained synchronously on base table changes and acts like a real table +
index. This is not caching this is storage.
Inserting view records.
|
INSERT INTO dbo.orderDemo (CustomerID, Amount) VALUES (3, 100), (3, 200), (3, 300), (4, 400); |
Running the view.
So, result is not catch in the
view. If it is cached then only, we can see the old result but we are getting
the update result.
SQL Server never caches view
results. What feels like caching is plan reuse, buffer-pool hits, or
operator-level spooling. Indexed views store data they don’t cache it. Anyone claiming
otherwise is confusing execution mechanics with storage.
No comments:
Post a Comment
If you have any doubt, please let me know.