Indexed Views (also called Materialized Views) are a powerful but often overlooked feature in SQL Server. Unlike regular views, which run the underlying query every time they are accessed, an Indexed View stores the query results physically on disk with a clustered index. This precomputation significantly speeds up complex queries.
Key Benefits:
- Reduces CPU and I/O load for heavy queries (e.g., large aggregations or joins).
- Works transparently – applications require no code changes.
- Ideal for read-heavy scenarios like reporting or dashboards.
Create an Indexed View with SCHEMABINDING:
CREATE VIEW dbo.vw_SalesSummary
WITH SCHEMABINDING
AS
SELECT
ProductID,
COUNT_BIG(*) AS TotalOrders,
SUM(SalesAmount) AS TotalSales
FROM dbo.Sales
GROUP BY ProductID;
Create an Indexed View by adding a unique clustered index:
CREATE UNIQUE CLUSTERED INDEX IX_vw_SalesSummary
ON dbo.vw_SalesSummary (ProductID);
When to Use Indexed Views:
- For large aggregations (e.g., SUM, COUNT).
- For complex joins with relatively static data.
- When data is read more frequently than updated.
Limitations:
- Base tables must be in the same database.
- Restrictions apply (no OUTER JOIN or UNION).
- May add overhead to write operations (INSERT/UPDATE/DELETE).
Pro Tip:
Use the WITH (NOEXPAND) hint to ensure the optimizer uses the indexed view in critical queries:
SELECT * FROM dbo.vw_SalesSummary WITH (NOEXPAND)