Advanced SQL: CTEs, Subqueries and Set Logic

Write readable multi-step SQL with CTEs, correlated subqueries, set operations, CASE logic, date handling and deduplication patterns.

Intermediate · about 10 hours · difficulty 3/5

Learn first: SQL Fundamentals

Real transformations are rarely one query. Advanced SQL is about breaking problems into steps and producing correct results on messy data.

Structuring queries

  • CTEs (WITH cleaned AS (...), daily AS (...) SELECT ...) make each step named and testable. This is the style dbt models use.
  • Subqueries: scalar, in IN/EXISTS, and correlated subqueries. Know when EXISTS is clearer than a join.
  • Recursive CTEs for hierarchies such as category trees or employee managers.

Logic and reshaping

  • CASE WHEN for bucketing and conditional aggregation: SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END).
  • UNION ALL vs UNION (the latter deduplicates and costs more), INTERSECT, EXCEPT.
  • Pivoting rows to columns with conditional aggregation.

Dates and strings

Truncating to day, week or month, generating a date spine to fill missing days, handling IST vs UTC, and string functions for cleaning (TRIM, LOWER, REGEXP_REPLACE).

Data engineering patterns

  • Deduplication: keep the latest record per key (you will do this with window functions next).
  • Upserts: INSERT ... ON CONFLICT in PostgreSQL, MERGE in warehouses.
  • Reconciliation: comparing row counts and sums between source and target with EXCEPT or full outer joins.

Pitfalls

  • Huge nested subqueries no one can read. Name steps with CTEs.
  • Using UNION when you meant UNION ALL, silently removing legitimate duplicates.
  • Date math in local time that breaks around midnight UTC.

You are ready to move on when you can produce a daily report with one row per day for the last 30 days, including days with zero orders, using a date spine and CTEs.

Key concepts

  • Common table expressions
  • Correlated subqueries and EXISTS
  • Recursive CTEs
  • CASE and conditional aggregation
  • UNION ALL, INTERSECT, EXCEPT
  • Date spines and time zones
  • MERGE and upserts
  • Source to target reconciliation

Mini project

Write a reconciliation script in SQL that compares a source orders table with a copied target table and reports missing rows, extra rows and rows whose amount differs. Use CTEs and EXCEPT or a full outer join.

Check yourself

When would you choose EXISTS over an INNER JOIN, and what problem does it avoid?

Free resources