Brainbotox · Lessons · Exams

SQL Intermediate for Confirmed Developers: CTEs, Window Functions

by lazizanie · Programming · Data & AI · SQL · English

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);
A CTE exists only for the statement that follows it. It can be referenced several times and can refer to earlier CTEs, which lets you build a query step by step.
A join, a subquery and a CTE can often express the same result. Write the clearest version first, then check the execution plan if it is slow.

Check yourself

  1. What is a correlated subquery?
  2. What does NOT IN return when the subquery result contains a NULL?
  3. Which keyword introduces a CTE?
  4. How long does a CTE exist?
  5. What does EXISTS (subquery) test?
  6. A subquery used in FROM (a derived table) needs an alias.

Take the quiz on Brainbotox

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 BY splits the rows into groups (optional).
  • ORDER BY inside OVER orders the rows within each partition.
  • Every input row stays in the result.

Ranking functions

SalariesROW_NUMBERRANKDENSE_RANK
900111
800222
800322
700443

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 customer
A window function cannot be used in WHERE, 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;
With 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

  1. How does a window function differ from GROUP BY?
  2. Two rows tie for 2nd place. What rank does RANK() give the next row?
  3. Which function always gives distinct consecutive numbers, even for ties?
  4. What does LAG(revenue) OVER (ORDER BY day) return?
  5. Why can you not write WHERE ROW_NUMBER() OVER (...) = 1?
  6. What does SUM(x) OVER (ORDER BY day) compute?

Take the quiz on Brainbotox

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

OperatorReturns
UNIONRows of both queries, duplicates removed
UNION ALLRows of both queries, duplicates kept
INTERSECTRows 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;
Both queries must return the same number of columns with compatible types. Prefer 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

FunctionResult
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
NULLs sort first or last depending on the database. State it with ORDER BY col NULLS LAST where supported.

Type conversion

SELECT CAST('2026-11-11' AS DATE), CAST(price AS INTEGER) FROM products;

Check yourself

  1. What is the difference between UNION and UNION ALL?
  2. What does EXCEPT return?
  3. What does a CASE expression return when no WHEN matches and there is no ELSE?
  4. What does NULLIF(quantity, 0) return when quantity is 0?
  5. What is conditional aggregation?
  6. What must two queries share to be combined with UNION?

Take the quiz on Brainbotox

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 BY and GROUP BY on the indexed columns.

Composite indexes and the leftmost prefix

An index on (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) = 2026WHERE 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 > 100WHERE price > 99

The cost of indexes

  • Every INSERT, UPDATE and DELETE must 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.

Index for the queries you really run. Find them in the slow query log, add one index, and compare the plans before and after.

Check yourself

  1. What is the usual data structure behind a database index?
  2. Which filter can use an index on (customer_id, created_at)?
  3. Why is WHERE YEAR(created_at) = 2026 slow on an indexed column?
  4. What is the main cost of adding indexes?
  5. What is a covering index?
  6. Which statement shows the execution plan?

Take the quiz on Brainbotox

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

PropertyMeaning
AtomicityAll statements succeed, or none take effect
ConsistencyConstraints hold before and after the transaction
IsolationConcurrent transactions do not see each other's unfinished work
DurabilityOnce 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

AnomalyWhat happens
Dirty readYou read data another transaction has not committed, and may roll back
Non-repeatable readYou read a row twice and get different values, because another transaction committed a change
Phantom readYou run the same query twice and new rows appear
Lost updateTwo transactions read, then both write; one overwrites the other

Isolation levels

LevelDirty readNon-repeatablePhantom
READ UNCOMMITTEDPossiblePossiblePossible
READ COMMITTEDNoPossiblePossible
REPEATABLE READNoNoPossible (by the standard)
SERIALIZABLENoNoNo

The default is READ COMMITTED in PostgreSQL, SQL Server and Oracle, and REPEATABLE READ in MySQL InnoDB.

Higher isolation means fewer anomalies but more locking or more transactions aborted and retried. Choose the lowest level that keeps your data correct.

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.

Keep transactions short, touch tables in a consistent order, and never wait for user input inside a transaction.

Check yourself

  1. What does the A in ACID stand for?
  2. What is a dirty read?
  3. Which isolation level prevents dirty reads but allows non-repeatable reads?
  4. What is the default isolation level of PostgreSQL?
  5. How does a database resolve a deadlock?
  6. What does Durability guarantee?

Take the quiz on Brainbotox

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

FormRuleViolation
1NFEach column holds one atomic value; no repeating groupsA column phones holding "123, 456"
2NF1NF, and every non-key column depends on the whole primary keyIn order_items(order_id, product_id, product_name), the name depends on product_id only
3NF2NF, and non-key columns depend only on the key, not on each otherIn employees(id, dept_id, dept_name), dept_name depends on dept_id
A common summary: every non-key column must depend on the key, the whole key, and nothing but the key.

Relationships

TypeImplementation
One to manyA foreign key on the "many" side: orders.customer_id
Many to manyA junction table with two foreign keys: student_courses(student_id, course_id)
One to oneA 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

  1. What is the goal of normalization?
  2. Which form is violated by a column that stores a comma-separated list of phone numbers?
  3. How do you model a many-to-many relationship?
  4. employees(id, dept_id, dept_name) violates which normal form?
  5. What does ON DELETE CASCADE do?
  6. What is a view?

Take the quiz on Brainbotox