Microsoft Learn

Documentation for SQL Relational Databases

Views in Relational Databases

Views are virtual tables based on the result-set of a SQL statement. A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database. You can add SQL statements and functions to a view and present the information as if the data were coming from a single table.

What is a View?

A view is a database object that provides a named query. You can think of a view as a stored query or a "virtual table" that doesn't store data itself but rather retrieves data from one or more underlying tables when it's queried.

Creating a View

The basic syntax for creating a view is:

CREATE VIEW view_name AS
    SELECT column1, column2, ...
    FROM table_name
    WHERE condition;

Example: Creating a Simple View

Consider a table named Customers with columns CustomerID, FirstName, LastName, and City.

CREATE VIEW LondonCustomers AS
    SELECT CustomerID, FirstName, LastName
    FROM Customers
    WHERE City = 'London';

Once created, you can query this view like a regular table:

SELECT * FROM LondonCustomers;

Types of Views

Most database systems support several types of views, including:

Key Concepts and Considerations

Overview
Creating Views
Modifying Views
Deleting Views

Key Features of Views

Views offer several advantages for database management and application development:

  • Data Presentation: Tailor the presentation of data for specific user roles or applications.
  • Logical Data Independence: Protect applications from changes in the underlying table structures.
  • Simplified Operations: Provide a simplified interface to complex data structures.

Advanced View Creation

Views can also incorporate functions, calculations, and aggregations:

CREATE VIEW CustomerOrderSummary AS
    SELECT
        c.CustomerID,
        c.FirstName,
        c.LastName,
        COUNT(o.OrderID) AS NumberOfOrders,
        SUM(o.TotalAmount) AS TotalSpent
    FROM Customers c
    LEFT JOIN Orders o
        ON c.CustomerID = o.CustomerID
    GROUP BY c.CustomerID, c.FirstName, c.LastName;

Modifying Existing Views

You can modify an existing view using the ALTER VIEW statement (syntax may vary slightly between database systems).

ALTER VIEW view_name AS
    new_select_statement;

For example, to update the LondonCustomers view to also include their email address:

ALTER VIEW LondonCustomers AS
    SELECT CustomerID, FirstName, LastName, Email
    FROM Customers
    WHERE City = 'London';

Deleting Views

To remove a view from the database, use the DROP VIEW statement.

DROP VIEW view_name;

Example:

DROP VIEW LondonCustomers;