Profile picture of Martin Joo

Martin Joo

@mmartin_joo

Published: March 13, 2025
1
6
81

Ever seen a SQL query with 3 nested subqueries and cried? 🧵 Let's clean them with CTEs.

Image in tweet by Martin Joo

2/ Original query: employees in departments where avg salary > $75k. Subquery-in-subquery chaos:

Image in tweet by Martin Joo

3/ With Common Table Expression (CTE):

Image in tweet by Martin Joo

4/ CTEs act as temporary tables that can be used in one query. Break complex logic into named blocks. For example, this CTE:

Image in tweet by Martin Joo

5/ Returns the following "temp table":

Image in tweet by Martin Joo

6/ Why use CTEs? ✅ Readable ✅ Reusable in same query ✅ Debuggable (test each CTE separately)

7/ CTEs can reference earlier CTEs. Chain them like functions! `dept_avg_salary` is a CTE from the earlier query. It can be used like a table:

Image in tweet by Martin Joo

8/ Thanks for reading! I'll release a book soon. It's called Building a database engine. Yes. We're going to build a DB engine. From scratch. Check it out here: https://buff.ly/4kcvgcv

Share this thread

Read on Twitter

View original thread

Navigate thread

1/8