惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

量子位
Vercel News
Vercel News
Microsoft Azure Blog
Microsoft Azure Blog
爱范儿
爱范儿
N
Netflix TechBlog - Medium
Google DeepMind News
Google DeepMind News
H
Help Net Security
罗磊的独立博客
The Cloudflare Blog
J
Java Code Geeks
博客园 - 叶小钗
I
InfoQ
B
Blog
Blog — PlanetScale
Blog — PlanetScale
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
腾讯CDC
月光博客
月光博客
博客园_首页
雷峰网
雷峰网
M
MIT News - Artificial intelligence
博客园 - 【当耐特】
美团技术团队
T
The Blog of Author Tim Ferriss
博客园 - 司徒正美

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Subqueries vs CTEs: When, Why, How.
Abdi Omari · 2026-04-23 · via DEV Community
Cover image for Subqueries vs CTEs: When, Why, How.

Abdi Omari

With a background in Python programming, Learning SQL started feeling like a step back, every line is independent of the next and so far nothing seemed interconnected or Programming-like, until I hit a wall:

Picture this :

You have a table employees and you need to find employees who earn more than the average salary of their own department, not the company average.

This Problem requires two queries, one to get the average salary of each department and another to find the employee whose salary is above that average.

Such a problem requires thinking like a programmer and the solution is either a subquery or a CTE.
But what are they.

Subqueries

A subquery (or inner query or nested query) is a SELECT statement embedded inside another SQL statement (SELECT, INSERT, UPDATE, DELETE). It answers a question within a question.

SELECT name, salary, department_id
FROM employees e1
WHERE salary > (
    SELECT AVG(salary)
    FROM employees e2
    WHERE e2.department_id = e1.department_id
);

Enter fullscreen mode Exit fullscreen mode

The inner query runs first, finds the average salary then it is used in the outer query.

When should you use subqueries?

  1. For Simple Filtering - comparing a column against a single value or a short list in another table.
  2. In select or where clauses
  3. when the logic is trivial(few lines nested is clean, more lines becomes messy and inefficient)

CTEs

What is it?
A Common Table Expression (CTE) is a temporary, named result set that exists only during the execution of a single query. Think of it as a view that vanishes after the query finishes.

You define a CTE using the WITH clause at the top of your query, then reference it like a regular table.

WITH dept_avg AS (
    SELECT department_id, AVG(salary) AS avg_salary
    FROM employees
    GROUP BY department_id
)
SELECT e.name, e.salary, e.department_id
FROM employees e
JOIN dept_avg d ON e.department_id = d.department_id
WHERE e.salary > d.avg_salary;

Enter fullscreen mode Exit fullscreen mode

When to use

  1. Breaking down multi-step transformations – Window functions, aggregations, then joins.

  2. Reusing the same subquery multiple times – Reference the CTE name twice instead of duplicating code.

  3. Recursive queries – Impossible with standard subqueries.

  4. Improving readability – Name your steps (sales_summary, returns_calc) to self-document.

Let's now compare the two across four dimensions to further understand, the importance of each technique, the strengths and the weaknesses.

Clear Comparision - Subqueries vs CTEs

  1. Readability
Aspect Subquery CTE
Short logic Clear and concise Overkill
Nested depth > 2 Messy and inefficient Top-down, Clean
Multiple references Copy-paste to reuse Reference by name
Self-documenting requires comments Intent-revealing names

CTEs for any query beyond 10 lines. Subqueries become unreadable when nested three levels deep. CTEs let you read the query like a story: Step A -> Step B -> Final SELECT.

  1. Perfomance

In theory, CTEs and subqueries often produce the same execution plan because modern optimizers (PostgreSQL, SQL Server, Oracle) treat them similarly.

  1. Reusability

  2. Scope & Limitations

Feature Subquery CTE
Can appear in WHERE, SELECT, HAVING Yes must be in WITH before main query
Can be used in UPDATE/DELETE correlated subqueries depends on DB support
Can reference outer query correlated Yes CTEs are independent
Maximum nesting depth DB-dependent Same query can have many CTEs, but no nesting limit

Correlated subqueries are a unique power: the inner query references columns from the outer query, re-evaluating for each row.

Use a Subquery when:

  1. You need a scalar value in SELECT or WHERE (e.g., WHERE salary > (SELECT AVG(...))).
  2. You need a correlated query that references the outer row.
  3. The logic is very simple (one or two lines) and nesting would overcomplicate.
  4. Your database version doesn’t support CTEs (rare today).
  5. You’re in a WHERE IN clause with a small list from another table.

Use a CTE when:

  1. Your query has more than 2 layers of nesting – CTE flattens the pyramid.
  2. You need to reference the same derived table multiple times (e.g., join it to itself or use it twice in a UNION).
  3. You’re working with hierarchical data (org charts, category trees, recursive paths).
  4. You value readability for future maintenance – CTEs act as documentation.
  5. You’re building a complex report with steps: WITH cleansed_data AS (...), aggregated AS (...), final AS (...).

Start with a subquery if it’s short and sweet. The moment you find yourself nesting a third SELECT inside a WHERE inside a FROM, stop. Refactor into a CTE. Your future self—and your teammates—will thank you.

Both tools belong in every SQL developer’s belt. Master subqueries for their raw power in filtering and expressions. Master CTEs for their elegance in breaking down chaos into ordered, readable steps. The best SQL isn’t the fastest—it’s the one you can debug at 3 AM.