SQL Intermediate for Confirmed Developers: CTEs, Window Functions
Intermediate SQL for confirmed developers: subqueries and CTEs, window functions, set operations and CASE, indexes, transactions and isolation levels, normalization, with quizzes.
Study this lesson with its quizzes on Brainbotox →
SQL subqueries, EXISTS and common table expressions (CTEs)
A subquery is a query nested inside another query, and a common table expression (CTE) is a named subquery declared with WITH that makes a complex query readable.
Kinds of subquery
-- scalar: returns one value
SELECT name FROM products
WHERE price > (SELECT AVG(price) FROM products);
-- list: used with IN
SELECT name FROM customers
WHERE id IN (SELECT customer_id FROM orders WHERE total > 500);
-- derived table: in FROM, needs an alias
SELECT city, avg_total
FROM (SELECT c.city, AVG(o.total) AS avg_total
FROM customers c JOIN orders o ON o.customer_id = c.id
GROUP BY c.city) AS t
WHERE avg_total > 100;Correlated subqueries and EXISTS
SELECT c.name FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);
A correlated subquery refers to the outer query (c.id), so it is evaluated logically once per outer row. EXISTS is true as soon as one row is found.
NOT IN with a subquery that returns a NULL gives no rows at all, because x <> NULL is unknown. Use NOT EXISTS, which behaves correctly.CTEs
WITH paid AS (
SELECT customer_id, SUM(total) AS revenue
FROM orders
WHERE status = 'paid'
GROUP BY customer_id
),
big AS (
SELECT customer_id FROM paid WHERE revenue > 1000
)
SELECT c.name, p.revenue
FROM customers c
JOIN paid p ON p.customer_id = c.id
WHERE c.id IN (SELECT customer_id FROM big);Check yourself
- What is a correlated subquery?
- What does NOT IN return when the subquery result contains a NULL?
- Which keyword introduces a CTE?
- How long does a CTE exist?
- What does EXISTS (subquery) test?
- A subquery used in FROM (a derived table) needs an alias.
SQL window functions: ROW_NUMBER, RANK, LAG and running totals
A window function computes a value for each row from a set of related rows, its window, without collapsing the rows as GROUP BY does.
Syntax
SELECT name, department, salary,
AVG(salary) OVER (PARTITION BY department) AS dept_avg,
RANK() OVER (PARTITION BY department ORDER BY salary DESC) AS dept_rank
FROM employees;PARTITION BYsplits the rows into groups (optional).ORDER BYinsideOVERorders the rows within each partition.- Every input row stays in the result.
Ranking functions
| Salaries | ROW_NUMBER | RANK | DENSE_RANK |
|---|---|---|---|
| 900 | 1 | 1 | 1 |
| 800 | 2 | 2 | 2 |
| 800 | 3 | 2 | 2 |
| 700 | 4 | 4 | 3 |
Top N per group
WITH ranked AS (
SELECT o.*, ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_at DESC) AS rn
FROM orders o
)
SELECT * FROM ranked WHERE rn = 1; -- latest order of each customerWHERE, because windows are computed after WHERE, GROUP BY and HAVING. Compute it in a CTE or subquery, then filter outside.LAG, LEAD and running totals
SELECT day, revenue,
LAG(revenue) OVER (ORDER BY day) AS previous_day,
revenue - LAG(revenue) OVER (ORDER BY day) AS change,
SUM(revenue) OVER (ORDER BY day) AS running_total,
AVG(revenue) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS avg_7_days
FROM daily_sales;ORDER BY in the window, an aggregate becomes cumulative: by default the frame runs from the start of the partition to the current row. A ROWS BETWEEN ... clause sets the frame explicitly.Check yourself
- How does a window function differ from GROUP BY?
- Two rows tie for 2nd place. What rank does RANK() give the next row?
- Which function always gives distinct consecutive numbers, even for ties?
- What does LAG(revenue) OVER (ORDER BY day) return?
- Why can you not write WHERE ROW_NUMBER() OVER (...) = 1?
- What does SUM(x) OVER (ORDER BY day) compute?
SQL set operations, CASE and NULL handling
Set operations combine the results of two queries vertically, CASE adds conditional logic to an expression, and a few functions tame NULL.
Set operations
| Operator | Returns |
|---|---|
UNION | Rows of both queries, duplicates removed |
UNION ALL | Rows of both queries, duplicates kept |
INTERSECT | Rows present in both |
EXCEPT (MINUS in Oracle) | Rows of the first query that are not in the second |
SELECT email FROM customers UNION SELECT email FROM newsletter_subscribers;
UNION ALL when duplicates are impossible or acceptable: UNION must do extra work to remove them.CASE
SELECT name, total,
CASE
WHEN total >= 1000 THEN 'large'
WHEN total >= 100 THEN 'medium'
ELSE 'small'
END AS size
FROM orders;Conditions are tested in order and the first true one wins. Without ELSE, the result is NULL.
Conditional aggregation
SELECT customer_id,
COUNT(*) AS orders,
SUM(CASE WHEN status = 'paid' THEN total ELSE 0 END) AS paid_total,
COUNT(CASE WHEN status = 'cancelled' THEN 1 END) AS cancelled
FROM orders
GROUP BY customer_id;This turns row values into columns (a pivot) in one pass over the table.
NULL handling
| Function | Result |
|---|---|
COALESCE(a, b, c) | The first non-NULL argument |
NULLIF(a, b) | NULL if a equals b, otherwise a |
SELECT total / NULLIF(quantity, 0) FROM items; -- avoids division by zero
ORDER BY col NULLS LAST where supported.Type conversion
SELECT CAST('2026-11-11' AS DATE), CAST(price AS INTEGER) FROM products;Check yourself
- What is the difference between UNION and UNION ALL?
- What does EXCEPT return?
- What does a CASE expression return when no WHEN matches and there is no ELSE?
- What does NULLIF(quantity, 0) return when quantity is 0?
- What is conditional aggregation?
- What must two queries share to be combined with UNION?
SQL indexes and query performance basics
An index is a sorted data structure, usually a B-tree, that lets the database find rows without reading the whole table. It speeds up reads and slows down writes.
Creating indexes
CREATE INDEX idx_orders_customer ON orders (customer_id); CREATE UNIQUE INDEX idx_users_email ON users (email); CREATE INDEX idx_orders_cust_date ON orders (customer_id, created_at);
A primary key and a unique constraint create an index automatically. Foreign key columns usually deserve one, since they are used in joins.
What a B-tree index helps
- Equality and range filters:
=,<,BETWEEN,LIKE 'abc%'. - Joins on the indexed column.
ORDER BYandGROUP BYon the indexed columns.
Composite indexes and the leftmost prefix
(customer_id, created_at) serves filters on customer_id, and on customer_id plus created_at. It does not serve a filter on created_at alone.Predicates that defeat an index
| Slow (not sargable) | Fast (sargable) |
|---|---|
WHERE YEAR(created_at) = 2026 | WHERE created_at >= '2026-01-01' AND created_at < '2027-01-01' |
WHERE LOWER(email) = 'a@b.c' | Store normalised values, or index the expression |
WHERE name LIKE '%son' | WHERE name LIKE 'Jo%' |
WHERE price + 1 > 100 | WHERE price > 99 |
The cost of indexes
- Every
INSERT,UPDATEandDELETEmust also update each index. - Indexes use disk and memory.
- An index on a column with few distinct values (low selectivity), such as a boolean, rarely helps.
Reading the plan
EXPLAIN SELECT * FROM orders WHERE customer_id = 42;
EXPLAIN shows how the database will run the query: a full table scan (sequential scan) or an index scan, and the join method. A covering index contains every column the query needs, so the table itself is never read.
Check yourself
- What is the usual data structure behind a database index?
- Which filter can use an index on (customer_id, created_at)?
- Why is WHERE YEAR(created_at) = 2026 slow on an indexed column?
- What is the main cost of adding indexes?
- What is a covering index?
- Which statement shows the execution plan?
SQL transactions, ACID and isolation levels
A transaction is a unit of work that the database treats as all-or-nothing, and its guarantees are summarised by the acronym ACID.
ACID
| Property | Meaning |
|---|---|
| Atomicity | All statements succeed, or none take effect |
| Consistency | Constraints hold before and after the transaction |
| Isolation | Concurrent transactions do not see each other's unfinished work |
| Durability | Once committed, changes survive a crash |
BEGIN; UPDATE stock SET qty = qty - 1 WHERE product_id = 7; SAVEPOINT before_order; INSERT INTO orders (product_id) VALUES (7); ROLLBACK TO before_order; -- undo part of the work COMMIT;
Concurrency anomalies
| Anomaly | What happens |
|---|---|
| Dirty read | You read data another transaction has not committed, and may roll back |
| Non-repeatable read | You read a row twice and get different values, because another transaction committed a change |
| Phantom read | You run the same query twice and new rows appear |
| Lost update | Two transactions read, then both write; one overwrites the other |
Isolation levels
| Level | Dirty read | Non-repeatable | Phantom |
|---|---|---|---|
| READ UNCOMMITTED | Possible | Possible | Possible |
| READ COMMITTED | No | Possible | Possible |
| REPEATABLE READ | No | No | Possible (by the standard) |
| SERIALIZABLE | No | No | No |
The default is READ COMMITTED in PostgreSQL, SQL Server and Oracle, and REPEATABLE READ in MySQL InnoDB.
Locks and deadlocks
Writers lock the rows they change until the transaction ends. A deadlock occurs when two transactions each wait for a lock the other holds. The database detects it and aborts one of them; the application should retry.
Check yourself
- What does the A in ACID stand for?
- What is a dirty read?
- Which isolation level prevents dirty reads but allows non-repeatable reads?
- What is the default isolation level of PostgreSQL?
- How does a database resolve a deadlock?
- What does Durability guarantee?
Database design and normalization: 1NF, 2NF, 3NF
Normalization is the process of organising tables so that each fact is stored exactly once, which prevents inconsistent data.
Why redundancy hurts
If the customer's address is copied on every order row, changing it means updating many rows (update anomaly), you cannot store a customer without an order (insert anomaly), and deleting the last order loses the address (delete anomaly).
The normal forms
| Form | Rule | Violation |
|---|---|---|
| 1NF | Each column holds one atomic value; no repeating groups | A column phones holding "123, 456" |
| 2NF | 1NF, and every non-key column depends on the whole primary key | In order_items(order_id, product_id, product_name), the name depends on product_id only |
| 3NF | 2NF, and non-key columns depend only on the key, not on each other | In employees(id, dept_id, dept_name), dept_name depends on dept_id |
Relationships
| Type | Implementation |
|---|---|
| One to many | A foreign key on the "many" side: orders.customer_id |
| Many to many | A junction table with two foreign keys: student_courses(student_id, course_id) |
| One to one | A foreign key with a UNIQUE constraint |
Keys and referential actions
A surrogate key is an artificial identifier (auto-increment or UUID). A natural key comes from the data (an email, an ISBN). Surrogate keys stay stable when business data changes.
customer_id INTEGER REFERENCES customers(id) ON DELETE CASCADE
ON DELETE CASCADE deletes child rows with the parent; RESTRICT refuses the delete; SET NULL clears the reference.
Denormalization and views
Reporting queries on a highly normalised schema need many joins. Denormalization deliberately stores redundant data (a cached total, a copied name) to read faster, at the price of keeping it in sync.
CREATE VIEW customer_revenue AS SELECT c.id, c.name, SUM(o.total) AS revenue FROM customers c JOIN orders o ON o.customer_id = c.id GROUP BY c.id, c.name;
A view is a stored query that behaves like a table. It holds no data of its own.
Check yourself
- What is the goal of normalization?
- Which form is violated by a column that stores a comma-separated list of phone numbers?
- How do you model a many-to-many relationship?
- employees(id, dept_id, dept_name) violates which normal form?
- What does ON DELETE CASCADE do?
- What is a view?