Views, indexes, and query performance
Create and use views
Create and query a reusable projection inside a rolled-back teaching transaction.
Lesson 71 of 84
Reading: about 2 min
Lesson + practice: about 15 min
Difficulty: Advanced
On this page4 sections
This lesson uses DDI_SQL_Training dataset v1.0.0 on SQL Server 2019 or later. Create and query a reusable projection inside a rolled-back teaching transaction. Run changing examples only on a disposable training instance. The example uses a session-local object or rolls back its changes.
Run the example
BEGIN TRANSACTION;
EXEC(N'CREATE VIEW dbo.DDI_LessonCustomerView AS
SELECT CustomerID, FirstName, City FROM dbo.Customers');
SELECT CustomerID, FirstName, City
FROM dbo.DDI_LessonCustomerView WHERE CustomerID BETWEEN 1 AND 3
ORDER BY CustomerID;
ROLLBACK TRANSACTION;Read it step by step
- CREATE VIEW defines a named SELECT; EXEC makes the CREATE VIEW the first statement in its dynamic batch.
- The following SELECT queries the view like a table.
- ROLLBACK removes the practice view so the canonical database object set stays stable.
Check the result
| CustomerID | FirstName | City |
|---|---|---|
| 1 | Alex | London |
| 2 | Maya | Manchester |
| 3 | Leo | Birmingham |
The view stores the query definition, not a separate copy of these customer rows.
Practice
Create a disposable view of ProductID and ProductName inside a transaction, read Products 1–2, then roll back.
Check your answer and expected result
Reveal answer
BEGIN TRANSACTION;
EXEC(N'CREATE VIEW dbo.DDI_LessonProductView AS
SELECT ProductID, ProductName FROM dbo.Products');
SELECT ProductID, ProductName FROM dbo.DDI_LessonProductView
WHERE ProductID BETWEEN 1 AND 2 ORDER BY ProductID;
ROLLBACK TRANSACTION;| ProductID | ProductName |
|---|---|
| 1 | Laptop Stand |
| 2 | USB-C Dock |
The view returns two canonical products during the transaction and is removed by rollback.
Your progress
Reveal the check answer or reach the end to complete this lesson.