SP
← SQL
MiddleSQL

SQL in depth: subqueries, window functions, indexes and transactions

At this level you know the syntax; now it is about how queries behave and where they surprise you.

Logical query processing order

A query is written as SELECT … FROM … WHERE …, but it is evaluated logically in this order:

  1. FROM (and JOINs)
  2. WHERE
  3. GROUP BY
  4. HAVING
  5. SELECT (aliases and window functions are computed here)
  6. ORDER BY

This explains several errors. A SELECT alias is not visible in WHERE (SQL Server reports Invalid column name), but it is visible in ORDER BY. Window functions cannot be used in WHERE or HAVING; compute them in a CTE or derived table and filter outside.

WITH ranked AS (
  SELECT id, customer_id,
         ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC) AS rn
  FROM orders
)
SELECT id, customer_id FROM ranked WHERE rn = 1;   -- latest order per customer

Subqueries, IN, EXISTS and JOIN

  • IN (subquery) and EXISTS are semi-joins: each outer row appears at most once, however many matches exist.
  • A JOIN returns one row per matching pair, so a customer with three orders appears three times. Rewriting IN as JOIN can silently multiply rows.

NOT IN with NULL is the classic trap. id NOT IN (1, NULL) means id <> 1 AND id <> NULL; the second part is always UNKNOWN, so no row qualifies.

-- safe even if orders.customer_id contains NULL
SELECT c.*
FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);

<> ALL (subquery) behaves exactly like NOT IN, and adding DISTINCT does not remove the NULL.

Window functions

A window function computes a value over a set of rows related to the current row without collapsing them (unlike GROUP BY).

Function Ties 90, 90, 80
ROW_NUMBER() 1, 2, 3 (tie order arbitrary)
RANK() 1, 1, 3 (gap)
DENSE_RANK() 1, 1, 2 (no gap)

SUM(amount) OVER (PARTITION BY region ORDER BY id) is a running total that restarts per region. Without the ORDER BY inside OVER, every row gets the whole partition's total.

LAG(amount) returns the previous row's value in the window order; for the first row it returns NULL unless you pass a default: LAG(amount, 1, 0). LEAD looks forward.

CTEs and recursion

A CTE (WITH name AS (...)) is a named query visible to the one statement that follows. It can be referenced several times there. SQL Server expands it inline like a view and does not store the result, so referencing it twice may run it twice; use a temp table when you need one stored result.

A recursive CTE has an anchor member and a recursive member joined with UNION ALL. The recursive part runs repeatedly against the previous step's rows until it returns nothing.

WITH chain AS (
  SELECT id, 0 AS depth FROM employees WHERE id = 2      -- anchor
  UNION ALL
  SELECT e.id, c.depth + 1
  FROM employees e JOIN chain c ON e.manager_id = c.id   -- recursive
)
SELECT * FROM chain;

SQL Server stops a recursive CTE at 100 levels by default (OPTION (MAXRECURSION n) changes this). PostgreSQL requires WITH RECURSIVE; SQL Server does not accept that keyword.

UNION vs UNION ALL

UNION ALL appends results. UNION removes all duplicates from the final result, including duplicates that came from one input, which costs a sort or hash. Use UNION ALL when duplicates are impossible or wanted.

Indexes (SQL Server)

  • Clustered index: its leaf level is the table, rows stored in key order. One per table. The primary key is clustered by default, but it does not have to be.
  • Nonclustered index: a separate structure with the key columns, optional INCLUDE columns, and a locator back to the row.
  • Composite index (customer_id, order_date) is sorted by the first column, then by the second within it. It supports customer_id = 42 AND order_date >= … but not order_date alone, and not customer_id + 0 = 42.
  • Covering index: contains every column the query uses, so no lookup into the table is needed. INCLUDE adds columns to the leaf level without making them part of the key.

Transactions and ACID

  • Atomicity: all of a transaction's changes happen or none do.
  • Consistency: a transaction moves the database between valid states (constraints hold). This is not the "C" of CAP.
  • Isolation: concurrent transactions are shielded from each other according to the isolation level.
  • Durability: once COMMIT returns, the change survives a crash.

In SQL Server each statement outside an explicit transaction commits on its own. Multi-step work, such as debiting and crediting two accounts, needs BEGIN TRANSACTION … COMMIT plus SET XACT_ABORT ON or TRY…CATCH with ROLLBACK.

Normalization

  • 1NF: one atomic value per cell; no comma-separated lists or repeating columns.
  • 2NF: no non-key column depends on only part of a composite key.
  • 3NF: no non-key column depends on another non-key column (no transitive dependency). customer_city in orders depends on customer_id, so it belongs in customers.

SQL injection and parameters from C#

Never build SQL by concatenating or interpolating input. Send values as parameters:

using var cmd = new SqlCommand("SELECT id FROM users WHERE email = @email", conn);
cmd.Parameters.Add("@email", SqlDbType.NVarChar, 256).Value = email;

Parameters cannot change the query's structure, let the server reuse the plan, and handle dates, decimals and quotes correctly. They cannot replace identifiers such as table or column names; use an allow-list for those. Data read from your own database is not automatically safe either (second-order injection).

Practise this level
20 questions
Practise →