Database programming
VIEW: naming a query
Create a consistent reading contract.
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.
Centralise repeated reporting logic.
Treating an ordinary view as a precomputed table.
One topic. Three levels of depth.
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.
Try it yourself first.
Count orders per customer using PaidOrders.
Show the solution and explanation
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.