0% found this document useful (0 votes)
19 views6 pages

SQL Study Material - 6 (Views, Indexes and CTEs)

The document explains SQL views and materialized views, highlighting their definitions, creation syntax, and key differences. It also covers the use of indexes, common table expressions (CTEs), and compares views with CTEs in terms of persistence, usage context, and performance. Additionally, it provides examples and practical applications for each concept.

Uploaded by

trisha86219
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views6 pages

SQL Study Material - 6 (Views, Indexes and CTEs)

The document explains SQL views and materialized views, highlighting their definitions, creation syntax, and key differences. It also covers the use of indexes, common table expressions (CTEs), and compares views with CTEs in terms of persistence, usage context, and performance. Additionally, it provides examples and practical applications for each concept.

Uploaded by

trisha86219
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Views

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

Syntax for Creating a View:

CREATE VIEW view_name AS

SELECT column1, column2, ...

FROM table_name

WHERE condition;

Example:

CREATE VIEW employee_view AS

SELECT employee_id, first_name, department

FROM employees

WHERE department = 'Sales';

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.

Syntax for Creating a Materialized View:

CREATE MATERIALIZED VIEW materialized_view_name AS

SELECT column1, column2, ...

FROM table_name

WHERE condition;

Example:

CREATE MATERIALIZED VIEW sales_summary AS


SELECT department, SUM(sales_amount) AS total_sales

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.

When to Use Views


1. Simplifying Complex Queries: When you have complex joins or aggregations that need to be
reused.

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.

o Practical Example: A view showing non-confidential employee details (without salary


info) to the HR team.

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.

• SQL Server supports several types of indexes:

• 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

-- Create a non-clustered index

CREATE NONCLUSTERED INDEX IX_ProductName ON Products(ProductName);

-- Create a filtered index

CREATE NONCLUSTERED INDEX IX_ActiveProducts ON Products(ProductName) WHERE IsActive = 1;

Drop the Index


-- Drop the non-clustered index IX_ProductName

DROP INDEX IX_ProductName ON Products;

-- Drop the filtered index IX_ActiveProducts

DROP INDEX IX_ActiveProducts ON Products;

Materialized view in SQL server

• 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

CREATE VIEW SalesSummary

WITH SCHEMABINDING

AS

SELECT ProductID, SUM(Quantity) AS TotalQuantity

FROM Sales

GROUP BY ProductID;

-- Create a unique clustered index to materialize the view

CREATE UNIQUE CLUSTERED INDEX IX_SalesSummary ON SalesSummary(ProductID);

Common Table Expressions (CTEs)


• CTEs are temporary result sets defined within the execution scope of a
single SELECT, INSERT, UPDATE, or DELETE statement.

• They are used to simplify complex queries, especially recursive ones, making code more
readable.

• CTEs can be recursive, allowing repeated execution of a query to produce hierarchical or


tree-like data structures.

-- Simple CTE

WITH SalesCTE AS (

SELECT ProductID, SUM(Quantity) AS TotalQuantity

FROM Sales

GROUP BY ProductID

SELECT * FROM SalesCTE WHERE TotalQuantity > 100;


-- Recursive CTE for hierarchical data

WITH EmployeeHierarchy AS (

SELECT EmployeeID, ManagerID, 0 AS Level

FROM Employees

WHERE ManagerID IS NULL

UNION ALL

SELECT e.EmployeeID, e.ManagerID, eh.Level + 1

FROM Employees e

INNER JOIN EmployeeHierarchy eh ON e.ManagerID = eh.EmployeeID

SELECT * FROM EmployeeHierarchy;

Uses of Recursive Query


• Organizational Hierarchies: Querying employee-manager relationships to build
reporting structures.
• Tree Structures: Navigating hierarchical data like product categories and
subcategories.
• Bill of Materials (BOM): Exploding product components into their subcomponents in
manufacturing.
• File Systems: Traversing directory structures with nested folders.
• Graph Traversals: Finding paths, shortest routes, or network connections in a graph
structure (e.g., social network or transportation networks).

Views vs CTE

1. Definition and Scope


• CTE: A CTE is a temporary result set defined within the execution of a single SELECT, INSERT,
UPDATE, or DELETE statement. It exists only during the execution of that query and is not
stored in the database.

• 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).

• View: Does not support recursion directly.

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.

You might also like