Recipe · SQL recipes

Views in SQL Server

In SQL Server, create a view with CREATE VIEW and query it in FROM. Define explicit columns and follow the rules on batches and ORDER BY.

Query

Run this example on a test database with SQL Server Management Studio. The table is fictional. GO separates batches in that tool; it is not a T-SQL statement to send from an application.

Test data
CREATE TABLE dbo.products_demo (
    id int NOT NULL PRIMARY KEY,
    name nvarchar(80) NOT NULL,
    price decimal(10,2) NOT NULL,
    stock int NOT NULL
);
INSERT INTO dbo.products_demo (id, name, price, stock)
VALUES (1, N'Keyboard', 39.90, 7),
       (2, N'Monitor', 179.00, 0),
       (3, N'Mouse', 18.50, 12);
GO
CREATE VIEW dbo.v_available_products AS
SELECT id, name, price
FROM dbo.products_demo
WHERE stock > 0;
GO
SELECT id, name, price
FROM dbo.v_available_products
ORDER BY price DESC, id;

The result contains Keyboard (39.90) and Mouse (18.50), in that order. Monitor is left out because its stock is zero. If the stock in the table changes, a later query on the view reflects the change.

CREATE VIEW must start its own batch. That is why there is a GO between loading the data and defining the view, and another one before the SELECT. From a driver or library, send those statements as separate executions rather than including GO in the SQL.

Cases that change the result

Changing or dropping the definition

In SQL Server 2016 SP1 and later, CREATE OR ALTER VIEW creates the view if it is missing or changes its definition if it already exists, so you can rerun a migration without first choosing between CREATE and ALTER. In earlier versions, use CREATE VIEW or ALTER VIEW depending on whether the object exists.

Updating the availability rule
CREATE OR ALTER VIEW dbo.v_available_products AS
SELECT id, name, price
FROM dbo.products_demo
WHERE stock >= 5;
GO
SELECT name, price
FROM dbo.v_available_products
ORDER BY name;

With the initial data, the result still includes Keyboard and Mouse. If you need to remove the view, DROP VIEW IF EXISTS dbo.v_available_products; removes the view's definition and its permissions, but keeps dbo.products_demo. Only use it when no queries depend on the view any more. The IF EXISTS variant requires SQL Server 2016 or later.

Permissions, schema and performance

A view can expose only the columns you need from the base tables. You can grant permissions on the view to simplify access, but also review the ownership chain and any permissions your environment needs. A view does not automatically turn a slow query into a fast one: check the filters, the indexes on the base tables and the execution plan if performance matters.

A normal view is virtual. An indexed view is a special case that stores results and has extra rules. Do not add indexes to an ordinary view out of habit. With WITH SCHEMABINDING, SQL Server blocks changes to the base tables that would break the definition; the view must refer to objects by schema and table name, such as dbo.products_demo. Choose this option when you need that guarantee and know what changing the schema will cost.

If you alter an indexed view, SQL Server drops its indexes, so plan to recreate them. For a normal view that only reuses columns and filters, start with the simple definition in the example.

Common mix-ups with views in SQL Server

  1. Relying on the view's order. SQL Server does not guarantee row order when reading a view. Add ORDER BY to the outer SELECT. Even if a definition allows ORDER BY alongside TOP u OFFSET, that does not sort the result of the outer query by itself.
  2. Use SELECT * and then changing the table. List the columns you need in the definition. If the view does not use SCHEMABINDING and the base objects change in a way that affects their metadata, review the definition and run EXEC sys.sp_refreshview N'dbo.v_available_products'; where appropriate.
  3. Creating the view in the middle of a batch. A CREATE VIEW after a INSERT in the same batch fails. Split the executions or, in tools that support it, use GO as in the example.