SQL Study Material - 6 (Views, Indexes and CTEs)
SQL Study Material - 6 (Views, Indexes and CTEs)
A view in SQL is a virtual table based on the result set of a SQL query. It does not store the actual
data; instead, it dynamically fetches the data from the underlying tables each time the view is
accessed. Views are used to simplify complex queries, encapsulate logic, and restrict access to
certain parts of the data
FROM table_name
WHERE condition;
Example:
FROM employees
Here, employee_view will return the employee_id, first_name, and department columns for
employees in the Sales department.
Materialized Views
A materialized view stores the result of a query physically on disk, unlike a standard view. It can be
refreshed periodically, and since the data is precomputed and stored, querying a materialized view is
faster. However, this comes at the cost of extra storage and maintenance.
FROM table_name
WHERE condition;
Example:
FROM sales
GROUP BY department;
This sales_summary materialized view stores the total sales for each department and can be queried
quickly.
Note - SQL Server does not support materialized views directly like some other databases.
However, SQL Server supports indexed views, which function similarly to materialized views by
storing data persistently.
Key Differences:
• View: Data is fetched dynamically each time.
• Materialized View: Data is stored and can be refreshed periodically, making it faster to query
but requiring storage.
o Practical Example: A view can combine multiple related tables (e.g., Orders,
Customers, Products) into a simple query for a report.
2. Restricting Data Access: Use views to expose only the necessary parts of your data to
different users or roles.
3. Enhancing Performance: Use indexed views (materialized views) in scenarios where read-
heavy queries benefit from precomputed data.
o Practical Example: An indexed view can store total sales per month, reducing the
need for recalculating it on each query.
4. Data Transformation: Views can be used to create transformations or format data for
specific use cases.
o Practical Example: A view might show product names in uppercase or combine first
name and last name for easier display.
Indexes
• Indexes are database objects that improve the speed of data retrieval. They function like the
index of a book, allowing quick lookups.
• Clustered Index: Sorts and stores the data rows in the table based on the index key.
Each table can have only one clustered index.
• Non-Clustered Index: Creates a separate structure that points to the data rows
based on the index key. A table can have multiple non-clustered indexes.
• Filtered Index: An optimized non-clustered index that only includes a subset of rows.
Example
• In SQL Server, materialized views are called Indexed Views because they use indexes to store
the results.
• To create an Indexed View, you need to follow specific rules, such as using WITH
SCHEMABINDING and creating a unique clustered index on the view.
Example
WITH SCHEMABINDING
AS
FROM Sales
GROUP BY ProductID;
• They are used to simplify complex queries, especially recursive ones, making code more
readable.
-- Simple CTE
WITH SalesCTE AS (
FROM Sales
GROUP BY ProductID
WITH EmployeeHierarchy AS (
FROM Employees
UNION ALL
FROM Employees e
Views vs CTE
• View: A View is a permanent database object that is stored as a named query in the
database. It can be queried repeatedly and behaves like a table.
2. Persistence
• CTE: Exists only for the duration of the query execution. Once the query is executed, the CTE
is gone.
• View: Remains stored in the database until explicitly dropped. It can be used across multiple
queries and sessions.
3. Usage Context
• CTE: Best suited for breaking down complex queries or performing recursive operations. It is
useful when you need a temporary table for a specific query.
• View: Ideal for creating reusable query logic that multiple users or applications can access.
4. Recursion
• CTE: Supports recursive queries, which are useful for hierarchical data (e.g., organizational
structures, tree structures).
5. Performance Considerations
• CTE: The database engine generates the result set at runtime. Performance is similar to
writing subqueries or temporary tables.
• View: If indexed (Indexed View), it can improve query performance significantly by storing
results physically. Otherwise, it behaves similarly to a regular query.
6. Modifiability
• CTE: Cannot be indexed or have any schema-related properties. It’s simply a temporary
name for a result set.
• View: Can have indexes (Indexed View), making them a form of materialized view, which can
improve performance by caching complex query results.