Module 1 · Writing Correct Queries · Lesson 1 of 14
How to Write SQL Queries in an Interview: Result Grain, Logical Order and Test Data
What this lesson teaches
SQL handles the parts of a SELECT in a fixed logical order. Knowing it helps you check row counts step by step and understand why a SELECT alias cannot be used in WHERE.
The usual interview answer is: FROM, ON, JOIN, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY, TOP. This is a logical order for reasoning about a query, not a promise about how the database executes it. Microsoft's logical processing order documentation lists these steps.
This first lesson builds a repeatable way to write and check SQL. You will learn to:
- Agree on what one result row represents.
- Build a query in small steps and check the row count.
- Explain where a column alias is available.
- Test awkward cases instead of trusting realistic-looking output.
We use standard SQL ideas. A SQL dialect is a database product's particular SQL syntax and behaviour. The example runs on SQLite through a .NET 10 console program. We identify differences in T-SQL, SQL Server's dialect, where they matter.
Before SQL, agree on the result
Suppose the interviewer asks: “Show open tickets per team.” That sounds clear, but it leaves several decisions unanswered.
Start by restating it: “You want one row per active team, with its number of open tickets, including teams with none. Is that right?”
Here, our result grain is one row per active team. For a monthly report, we might instead want “one row per team per month.” Write this down before choosing columns.
Then ask about the cases that could change the answer:
- Ties: If two teams have the same count, should both appear?
- NULLs: Should a ticket whose assigned team is
NULLappear separately? - Duplicates: Which repeated rows represent separate tickets, and which are accidental copies? Two tickets with the same title are not necessarily the same ticket.
- Unmatched rows: Should teams without tickets still appear?
- Time zone: If dates matter, which local clock defines a day or month?
- Size: Are we querying hundreds of tickets or millions? This affects which performance checks are worth discussing.
The driving table is the starting table whose required rows you want to preserve. For our agreed task, start with teams, not tickets. Starting with tickets would leave you without a row for a team that has none.
The mistake to avoid. Do not silently choose what “per team” means. A query can be valid SQL and still answer the wrong question.
In an interview, say: “First I confirm the result grain. Then I ask about ties, NULLs, duplicates, unmatched rows, time zones and data size. I choose the starting table based on which rows must appear.”
In what order is a SELECT processed?
SQL's written order starts with SELECT, but its logical processing starts with the input tables.
| Logical step | What it does |
|---|---|
FROM | Identifies the input tables. |
ON | Defines which rows match when tables are joined. |
JOIN | Combines matching rows and, for an outer join, preserves specified unmatched rows. |
WHERE | Keeps individual rows whose condition is true. |
GROUP BY | Collects rows into groups. |
HAVING | Keeps groups whose condition is true. |
SELECT | Chooses the output columns and expressions. |
DISTINCT | Removes duplicate output rows. |
ORDER BY | Sorts the result. |
TOP | Limits the returned rows in T-SQL. |
A join combines rows from tables according to a matching condition. An outer join also preserves unmatched rows from a specified side. In the example below, LEFT JOIN keeps the Billing team even though it has no open ticket. Its ticket columns in the joined result are NULL.
An aggregate function calculates a summary, such as a count, from several rows. GROUP BY determines which rows contribute to each summary. WHERE filters before grouping; HAVING filters after grouping.
For example, “count open tickets per team, but show only teams with at least two” needs two separate decisions. “Open” is a rule about rows, so it goes in WHERE. “At least two” is a rule about groups, so it goes in HAVING COUNT(t.TicketId) >= 2.
GROUP BY does not sort the result. Use ORDER BY when order matters. See Microsoft's GROUP BY documentation. Without DISTINCT, selecting columns does not automatically remove repeated output rows.
Microsoft's SELECT documentation also places WITH CUBE or WITH ROLLUP, grouping extensions for extra totals, after GROUP BY; this example does not need them.
The physical order is the real order of work the database chooses when it runs the query, for example which table it reads first.
The mistake to avoid. Do not treat logical order as a literal execution schedule. The database can choose a different physical order while preserving the query's required meaning.
In an interview, say: “The logical order is FROM, ON, JOIN, WHERE, GROUP BY, HAVING, SELECT, DISTINCT, ORDER BY, then TOP in SQL Server. WHERE comes before SELECT, which explains why a SELECT alias is unavailable there. Physical execution can differ.”
See it in code: open tickets per team
We will return one row per active team, including teams with zero open tickets. Equal counts stay in the result. Team ID breaks ties in the displayed order.
A column alias is a name assigned to an output column, such as OpenTickets. A table alias is a shorter name used to refer to a table, such as tm for Teams.
COUNT(t.TicketId) counts non-NULL ticket IDs. An unmatched team has a NULL ticket ID in the joined result, so its count is zero. By contrast, COUNT(*) counts joined rows, including the row preserved for that unmatched team. Microsoft's COUNT documentation explains the difference.
SQLite's :memory: database exists entirely in memory. Closing its connection deletes it, so we keep the connection open throughout. See Microsoft's in-memory database guidance.
Before running, predict three counts: rows after the join, rows after WHERE, and rows after grouping.
Dialect: SQLite. The reporting query's joins, grouping and ordering also use syntax accepted by T-SQL. The setup uses SQLite column types.
using Microsoft.Data.Sqlite;
using var connection = new SqliteConnection("Data Source=:memory:");
connection.Open();
using (var setup = connection.CreateCommand())
{
setup.CommandText = """
-- Include every active team, even with no open tickets.
-- Equal counts remain; TeamId breaks display ties.
DROP TABLE IF EXISTS Tickets;
DROP TABLE IF EXISTS Teams;
CREATE TABLE Teams (
TeamId INTEGER PRIMARY KEY,
Name TEXT NOT NULL,
IsActive INTEGER NOT NULL
);
CREATE TABLE Tickets (
TicketId INTEGER PRIMARY KEY,
TeamId INTEGER NOT NULL,
Title TEXT NULL,
Status TEXT NOT NULL
);
INSERT INTO Teams VALUES
(1, 'Support', 1), (2, 'Operations', 1),
(3, 'Billing', 1), (4, 'Retired', 0);
INSERT INTO Tickets VALUES
(101, 1, 'Printer', 'Open'),
(102, 1, 'Printer', 'Open'),
(103, 2, 'VPN', 'Open'),
(104, 2, NULL, 'Open');
INSERT INTO Tickets VALUES (105, 3, 'Invoice', 'Closed');
""";
setup.ExecuteNonQuery();
}
const string joined = """
FROM Teams AS tm
LEFT JOIN Tickets AS t
ON t.TeamId = tm.TeamId AND t.Status = 'Open'
""";
string filtered = joined + "\nWHERE tm.IsActive = 1";
string grouped = """
SELECT tm.TeamId, tm.Name, COUNT(t.TicketId) AS OpenTickets
""" + "\n" + filtered + "\nGROUP BY tm.TeamId, tm.Name";
PrintCount("After JOIN", "SELECT COUNT(*) " + joined);
PrintCount("After WHERE", "SELECT COUNT(*) " + filtered);
PrintCount("After GROUP BY", "SELECT COUNT(*) FROM (" + grouped + ") AS g");
using var command = connection.CreateCommand();
command.CommandText = grouped + "\nORDER BY OpenTickets DESC, tm.TeamId";
using var reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine($"{reader.GetString(1)}: {reader.GetInt64(2)}");
}
void PrintCount(string label, string sql)
{
using var count = connection.CreateCommand();
count.CommandText = sql;
Console.WriteLine($"{label}: {count.ExecuteScalar()}");
}After JOIN: 6 After WHERE: 5 After GROUP BY: 3 Support: 2 Operations: 2 Billing: 0
Needs the package Microsoft.Data.Sqlite 10.0.12. Built and run with it: the output above is what the program really printed.
First, build FROM and the join. Support and Operations each match two tickets. Billing and Retired each contribute one unmatched row. That gives six joined rows.
The open-status condition belongs in ON because we want to match only open tickets while still preserving teams with none.
Next, add WHERE. It removes the inactive Retired team. Five rows remain. Putting t.Status = 'Open' here instead would remove Billing's unmatched row: its right-hand columns are NULL, so that comparison is not true.
Then add GROUP BY. It collects the five rows into three team groups. Both TeamId and Name appear because both are selected without an aggregate. SQL Server requires these selected columns to be grouped.
flowchart TD
J["6 joined rows"] -->|WHERE keeps| W["5 active-team rows"]
W -->|GROUP BY produces| G["3 team groups"]
The diagram shows how the number of rows changes as the query reaches the required result grain.
Finally, SELECT returns the team and count. ORDER BY OpenTickets DESC, tm.TeamId sorts by decreasing count, then increasing team ID.
There is no HAVING because we are not excluding groups. Adding HAVING COUNT(t.TicketId) >= 2 would remove Billing and change the agreed task.
The mistake to avoid. Do not put every filtering condition in WHERE. A condition on the right-hand table can remove the unmatched rows that LEFT JOIN was meant to preserve.
In an interview, say: “I start with teams because empty teams must appear. I match only open tickets in ON, filter active teams in WHERE, and group by team. I count ticket IDs rather than joined rows so an unmatched team gets zero.”
Why can't I use a column alias in WHERE?
A name created by SELECT is unavailable to earlier logical steps. In SQL Server, you cannot use that output alias in WHERE, GROUP BY or HAVING. You can use it in ORDER BY on its own, as in ORDER BY DisplayId. SQL Server does not accept it inside a larger expression there: ORDER BY DisplayId + 1 fails. Repeat the expression in that case.
Repeat the expression when it is short:
Dialect: T-SQL (SQL Server), not run here. This query uses the Teams table from the example.
SELECT tm.TeamId + 100 AS DisplayId FROM Teams AS tm WHERE tm.TeamId + 100 > 101 ORDER BY DisplayId;
For a longer expression, wrap the calculation in another query. A common table expression, or CTE, gives a query result a name that a following query can use. An outer query can then filter the calculated column. This avoids repeating a long expression, at the cost of another query layer to read.
Dialect: T-SQL (SQL Server), not run here.
WITH x AS (
SELECT tm.TeamId, tm.TeamId + 100 AS DisplayId
FROM Teams AS tm
)
SELECT *
FROM x
WHERE DisplayId > 101
ORDER BY DisplayId;SQLite accepts some alias uses in WHERE and GROUP BY that SQL Server rejects, so keep the habit that works everywhere: use input columns or repeat expressions in earlier clauses.
The mistake to avoid. Do not learn alias visibility by trying only SQLite. Its extra accepted syntax can hide a query that fails in SQL Server.
In an interview, say: “WHERE is logically processed before SELECT, so it cannot use an alias created by SELECT. I repeat the expression or wrap the calculation in a CTE or another query. ORDER BY can use the alias.”
How do you know the query is right?
A small dataset is easier to reason about than hundreds of convincing-looking rows. Our nine input rows deliberately include:
- A NULL title, which must not stop its ticket being counted.
- Two identical titles on separate ticket IDs, which must count as two tickets.
- A tie between two team counts, which must preserve both teams.
- An active team with only a closed ticket, which must appear with zero open tickets.
- An inactive unmatched team, which must disappear at
WHERE.
State the expected result before running. Then compare the row count after each step with your prediction. These checks catch different mistakes: a growing join can reveal extra matches, while a missing group can reveal an overly restrictive filter.
Also test an active team with no tickets at all.
For a stronger check, write a second version independently. EXCEPT returns distinct rows present in the first query but absent from the second. See Microsoft's EXCEPT and INTERSECT documentation. Compare A EXCEPT B and B EXCEPT A. Both should return no rows.
This proves only that both queries return the same distinct rows, not how often each row repeats or their order. If duplicates matter, also compare how many times each complete row occurs.
The mistake to avoid. Do not treat “it returned three rows” as proof. The query could return three wrong rows, or correct rows with incorrect counts.
In an interview, say: “I predict results for tiny edge-case data and check row counts as I build. I compare an independent version using EXCEPT both ways. If repeated rows matter, I also compare their counts, because EXCEPT removes duplicates.”
Practice
SQL Server rejects an output alias used in WHERE. Why?
Show answer
Correct answer: B
WHERE cannot use a name created later by SELECT. Repeat the expression or calculate it in an inner query. ORDER BY can use the output alias.
Teams has 4 rows. After the LEFT JOIN to open tickets, the query has 6 rows. What does that tell you first?
Show answer
Correct answer: A
A LEFT JOIN keeps every team and adds a row for each extra match. Check that this is the grain you want before you group and count.
For more query-writing practice, use the SQL Server practice set.
Going deeper
In a live interview, think aloud in small steps. State the grain, show a few test rows, and explain each change in row count. You do not need to write the whole query in one pass.
For a take-home task, provide one re-runnable script: drop, create, insert, then query. Put assumptions and expected results in comments. Keep database-specific syntax clearly identified.
Add a short note on the indexes you would check for the expected workload; this tiny dataset cannot show a performance benefit.
The counts in our program are debugging queries, not a measurement of the database's internal work. For the physical work, read the execution plan: see Reading Actual Execution Plans.
For portability, remember these limits:
- T-SQL uses
TOPfor the row-limiting step discussed earlier. SQLite usesLIMIT, written afterORDER BY. Neither is the standard SQL spelling. The standard form isFETCH FIRST n ROWS ONLY, optionally afterOFFSET m ROWS. SQL Server acceptsOFFSET m ROWS FETCH NEXT n ROWS ONLYafterORDER BY, but only with theOFFSETpart; see Microsoft's ORDER BY documentation. - Do not select an ungrouped, unaggregated column merely because SQLite accepts it. SQL Server requires the appropriate grouping. See Microsoft's GROUP BY documentation.
- SQLite returning NULL for division by zero is not a portable SQL rule. Do not use that behaviour as error handling for a SQL Server query.
- Microsoft's SELECT page also mentions
QUALIFY, which filters on window-function results. It works only in Fabric Data Warehouse, not in SQL Server, so leave it out of the SQL Server order you give in an interview.
Sources
- SELECT (Transact-SQL) - SQL Server | Microsoft Learn: Logical SELECT processing order, alias visibility, logical versus physical execution, TOP, result comparison operators and the Fabric-only QUALIFY qualification.
- GROUP BY (Transact-SQL) - SQL Server | Microsoft Learn: WHERE before grouping, HAVING filtering groups, selected-column grouping requirements, GROUP BY not sorting and subtotal extensions.
- In-memory databases - Microsoft.Data.Sqlite | Microsoft Learn: The :memory: connection string, connection-specific databases and keeping the connection open until all queries finish.
- COUNT (Transact-SQL) | Microsoft Learn: Counting non-NULL expression values versus all rows.
- Set Operators - EXCEPT and INTERSECT (Transact-SQL) | Microsoft Learn: Comparing distinct rows from two queries.
- SELECT - ORDER BY clause (Transact-SQL) | Microsoft Learn: SQL Server's OFFSET and FETCH syntax.
Checked before publishing: links opened, reviewed while it was written and read in full. How lessons are checked
Updated 1 Dec 2026 ·