Reading data with SELECT
Logical query processing order
Reason about which rows and names are available at each query stage.
Lesson 11 of 84
Reading: about 2 min
Lesson + practice: about 10 min
Difficulty: Beginner
On this page4 sections
This lesson uses DDI_SQL_Training dataset version 1.0.0 on SQL Server 2019 or later. The clauses are written SELECT, FROM, WHERE, ORDER BY, yet it helps to reason about them in a different order. That explains why some names are available in one clause but not another.
Run the example
SELECT CustomerID, City AS CustomerCity
FROM dbo.Customers
WHERE City = N'London'
ORDER BY CustomerCity, CustomerID;Read it step by step
- FROM dbo.Customers supplies the 20 source rows. WHERE City = N'London' then keeps only the five matching rows. N marks a Unicode string literal in SQL Server.
- SELECT CustomerID, City AS CustomerCity chooses two output columns and creates the CustomerCity heading.
- ORDER BY CustomerCity, CustomerID sorts the five output rows. CustomerID breaks ties between customers in the same city.
Check the result
| CustomerID | CustomerCity |
|---|---|
| 1 | London |
| 4 | London |
| 10 | London |
| 15 | London |
| 20 | London |
A useful logical sequence is FROM, WHERE, SELECT, ORDER BY, then OFFSET/FETCH. This is a reasoning model for the result, not a claim about the physical steps SQL Server chooses to execute. Because WHERE is logically earlier than SELECT, it uses City rather than the CustomerCity output alias.
Practice
Why can ORDER BY use CustomerCity here, while WHERE uses City? How many London customers are returned?
Check your answer and expected result
Reveal answer
SELECT COUNT(*) AS LondonCustomers
FROM dbo.Customers
WHERE City = N'London';| LondonCustomers |
|---|
| 5 |
ORDER BY sees the projected alias; WHERE logically runs before that alias exists. The unmodified v1.0.0 dataset returns five London customers.
COUNT(*) returns the number of rows that survive WHERE. Chapter 5 covers aggregate functions in full.
Your progress
Reveal the check answer or reach the end to complete this lesson.