MSDN

SQL Server Views

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 functions and joins to a view to present the information in a particular way that is not directly available in individual tables.

What is a View?

A view is a saved SQL query that can be treated as a virtual table. It does not store data itself, but rather retrieves data from the underlying base tables when queried. Views offer several benefits:

  • Simplification: They can hide the complexity of underlying table structures and joins, presenting a simpler interface for users.
  • Security: You can grant permissions on a view to restrict access to specific rows or columns of a table.
  • Data Consistency: Ensures that the same derived data is presented consistently across different applications.
  • Logical Data Independence: The structure of the base tables can be changed without affecting the applications that use the views, as long as the view definition remains compatible.

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

Let's assume we have a table named `Employees` with columns `EmployeeID`, `FirstName`, `LastName`, `Department`, and `Salary`. We can create a view to show only employees from the 'Sales' department:

CREATE VIEW SalesEmployees AS
SELECT EmployeeID, FirstName, LastName, Department
FROM Employees
WHERE Department = 'Sales';

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

SELECT * FROM SalesEmployees;

Types of Views

  • Simple Views: Based on a single table.
  • Complex Views: Based on multiple tables using JOINs, aggregate functions, etc.
  • Indexed Views: Views that have an index created on them. They store the data physically and must adhere to specific rules to be indexed.
  • System Views: Built-in views provided by SQL Server to expose metadata about the database system.

Modifying and Dropping Views

You can modify an existing view using `ALTER VIEW` or drop it using `DROP VIEW`.

ALTER VIEW SalesEmployees AS
SELECT EmployeeID, FirstName, LastName
FROM Employees
WHERE Department = 'Sales' AND Salary > '50000';

DROP VIEW SalesEmployees;

Considerations for Views

  • Views are processed at runtime, so complex views can impact query performance.
  • Not all views are updatable (i.e., allow INSERT, UPDATE, DELETE operations). Generally, views based on single tables without aggregations or DISTINCT clauses are updatable.
  • Indexed views can significantly improve query performance but have overhead for data modifications on base tables.

Explore the linked topics for detailed information on specific view types, syntax, and best practices.