COMPUTER ENGINEER

Jump to examples
Blog
SQL Server / T-SQL6 min study
40/ 65

Database programming

VIEW: naming a query

Create a consistent reading contract.

UnderstandStudy an examplePractise

Understand the concept

A view stores a SELECT definition; an ordinary view does not automatically materialise its results. It lets reports share the same revenue definition. State that one row in an order-total view represents one order. An internal ORDER BY does not guarantee an outer query’s ordering.

A view can expose a restricted contract, but permissions and ownership chains require deliberate design. Use explicit columns rather than SELECT *. Indexed views are a different mechanism with SET requirements and write overhead. A view is not inherently a performance improvement. CREATE OR ALTER VIEW must be first in its batch; separate it with GO in SSMS.

WHEN TO USE IT

Centralise repeated reporting logic.

COMMON PITFALL

Treating an ordinary view as a precomputed table.

01 / PRACTICE

One topic. Three levels of depth.

T-SQL / SQL Server 2019+
SELECT OrderId, CustomerId FROM lab.SalesOrder WHERE Status = 'Paid';

The reading contract to move into a view.

This page does not execute SQL. Practise in the downloadable SqlStudioLab using SSMS. Before rerunning temporary-table examples, remove only the relevant #table. Views, procedures and functions create persistent lab objects; never use a production connection.

02 / YOUR TURN

Try it yourself first.

Count orders per customer using PaidOrders.

Show the solution and explanation
Worked solution
SELECT CustomerId, COUNT(*) AS Orders FROM lab.PaidOrders GROUP BY CustomerId;

Create the intermediate example’s view first. The same nine paid orders are counted.