Sunday, August 4, 2024

Indexed views

 Indexed views in SQL Server are views that have a clustered index created on them. These views are sometimes referred to as materialized views because, unlike regular views that are virtual and do not store data, indexed views physically store the result set of the view on disk. This can improve performance for complex queries by precomputing and storing the results.

Here’s how you can work with indexed views:

Creating an Indexed View

To create an indexed view, follow these steps:

  1. Create the View: Define the view with the WITH SCHEMABINDING option. This ensures that the underlying tables cannot be modified in a way that would affect the view.

  2. Create the Clustered Index: After creating the view, you need to create a clustered index on it. This will physically store the view’s data.

Here’s an example:

-- Step 1: Create the view with SCHEMABINDING
CREATE VIEW dbo.SalesSummary
WITH SCHEMABINDING
AS
SELECT 
    SalesPersonID,
    SUM(SalesAmount) AS TotalSales
FROM 
    dbo.Sales
GROUP BY 
    SalesPersonID;

-- Step 2: Create a clustered index on the view
CREATE UNIQUE CLUSTERED INDEX IX_SalesSummary
ON dbo.SalesSummary (SalesPersonID);

Key Points:

  • Schema Binding: The WITH SCHEMABINDING clause ensures that the view cannot be created or modified unless the underlying tables remain unchanged in terms of schema.

  • Unique Clustered Index: An indexed view requires a unique clustered index. Without it, the view cannot be indexed.

  • Performance: Indexed views can greatly improve query performance, especially for complex aggregations and joins. However, they come with a cost of increased storage and maintenance overhead, as the data in the indexed view must be kept up-to-date with changes to the underlying tables.

  • Restrictions: There are some limitations and restrictions on indexed views. For example, certain operations (like using DISTINCT, TOP, or UNION in the view definition) are not allowed, and some features (like TEXT or IMAGE data types) cannot be used in indexed views.

Querying an Indexed View

Once the indexed view is created, you can query it just like a regular table:

SELECT * FROM dbo.SalesSummary
WHERE SalesPersonID = 1;

The query will use the indexed view to quickly retrieve precomputed results, improving performance compared to computing the results on the fly.

No comments:

Post a Comment