SQL CTEs and Ranking
A local workbook for readable queries, top-N results and recursive hierarchies.

What you will build
Four assertions check grouped totals, two rows per store, ranking ties and a recursive employee hierarchy. The example uses Python's built-in sqlite3 module and an in-memory database.
This workbook is for readers who can run a Python script. It includes a small local example, explanations, exercises and worked answers. The package was checked on Windows with Python 3.13.17. Pinned package versions and setup instructions are included; they are not a claim to be the latest releases.
Read a sample
The following two sections are taken from the practical download edition.
Use a small local database
queries.py creates an in-memory SQLite database, builds sales and employee tables and runs four queries with expected-result assertions. It uses only the Python standard library. The database disappears when the connection closes, so this workbook does not modify an existing database file.
SQLite is the dialect used throughout this edition. The query patterns transfer to other databases, but placeholder syntax, date functions and recursive-query rules can differ. Test a query against the target engine rather than assuming every SQL feature has identical behaviour.
The sales dataset contains a tie: London has amounts 100, 90 and 90. The employee dataset is a small tree with Alex at the root, Sam and Jo reporting to Alex, and Lee reporting to Sam. These inputs are small enough to trace every output row.
Give an intermediate result a name
TOTALS uses a common table expression called store_totals to name an aggregation. The outer SELECT then filters that result by a parameterised threshold. Naming a stage makes the query easier to discuss and inspect without creating a permanent table.
A CTE exists within one statement. It is not automatically a persistent cache or a performance optimisation. The database planner chooses how to execute the statement. Use the CTE to clarify the query, then inspect the execution plan if performance matters.
With a threshold of 200, only London remains, with a total of 280. Bristol totals 120. The Python call passes the threshold as a parameter; it does not build SQL by joining a user-supplied string.
Inside the complete guide
- Use a small local database
- Give an intermediate result a name
- Rank inside a group, then filter outside
- Choose how ties should behave
- Walk a hierarchy with a recursive CTE
- Exercises and worked answers
Files in your download
The 6-page PDF includes the walkthrough and complete source listing. The examples folder contains:
queries.pyREADME.txtrequirements.txt
Scope and source material
This is a focused learning project with synthetic example data. It does not include hosted services or production deployment. This revised edition is based on previously published articles and uses replacement runnable examples; it is not a verbatim reprint.
Get the guide on Payhip — £4.99