TGViewer
Coding Interview Preparation Coding Interview Preparation @coding_interview_preparation · 5.9K subscribers
Post #1382 288
📊 SQL SATURDAY #4 - Subqueries and CTEs

Time to clean up messy nested queries. Same orders table as before.

The old, hard-to-read way (nested subquery):
sql
SELECT customer_id, total_spent
FROM (
SELECT customer_id, SUM(amount) AS total_spent
FROM orders
GROUP BY customer_id
) AS customer_totals
WHERE total_spent > 150;


The cleaner way, using a CTE (Common Table Expression):
sql
WITH customer_totals AS (
SELECT customer_id, SUM(amount) AS total_spent
FROM orders
GROUP BY customer_id
)
SELECT customer_id, total_spent
FROM customer_totals
WHERE total_spent > 150;


Same result, dramatically more readable - especially once you start chaining multiple CTEs together:

sql
WITH customer_totals AS (
SELECT customer_id, SUM(amount) AS total_spent
FROM orders
GROUP BY customer_id
),
big_spenders AS (
SELECT customer_id
FROM customer_totals
WHERE total_spent > 150
)
SELECT c.name
FROM customers c
JOIN big_spenders b ON c.id = b.customer_id;


💡 Why interviewers love CTE questions: they reveal whether you can decompose a complex problem into logical, named steps - the same skill you need for clean production SQL, not just passing a test.

⚠️ Performance note: CTEs aren't automatically materialized/cached in every database engine - in some (like older Postgres versions), a CTE could be re-run each time it's referenced. Worth knowing your specific database's behavior before assuming CTEs are always a free readability win.

Do you default to CTEs or subqueries in your day-to-day work? 👇
  • 👍 1
More from @coding_interview_preparation
  1. Oct 8, 2026If you're prepping for system design interviews, this repo is gold It contains a curated,…
  2. Oct 6, 2026document post
  3. Oct 4, 2026💼 Why Your Resume Gets Rejected Before a Human Reads It You may have good skills and proj…
  4. Oct 2, 2026🧠 Coding Myths You Should Stop Believing There's a lot of advice online about learning to…
  5. Oct 1, 2026Most Asked Topics in AI Engineer Interviews Based on 2026 candidate reports
  6. Sep 30, 2026💼 What Companies Actually Look For in a Fresher Think companies only care about your CGPA…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →