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

推荐订阅源

U
Unit 42
博客园 - Franky
T
Tailwind CSS Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
月光博客
月光博客
人人都是产品经理
人人都是产品经理
雷峰网
雷峰网
Hugging Face - Blog
Hugging Face - Blog
有赞技术团队
有赞技术团队
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
阮一峰的网络日志
阮一峰的网络日志
C
Check Point Blog
爱范儿
爱范儿
T
The Blog of Author Tim Ferriss
aimingoo的专栏
aimingoo的专栏
Stack Overflow Blog
Stack Overflow Blog
博客园 - 聂微东
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
L
LangChain Blog
云风的 BLOG
云风的 BLOG
MyScale Blog
MyScale Blog
Microsoft Security Blog
Microsoft Security Blog
The Cloudflare Blog
博客园 - 三生石上(FineUI控件)

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
SQL Subqueries vs CTEs: What I Wish Someone Told Me When ...
Leah Kivuti · 2026-04-28 · via DEV Community

When you first start learning SQL, everything feels simple. You write basic SELECT queries, maybe add a WHERE, and life is good.

Then suddenly you meet things like subqueries and CTEs, and it feels like SQL switched languages overnight.

I remember staring at nested queries thinking, “Why would anyone write a query inside another query?”

Turns out… there’s a reason. And once it clicks, it actually makes SQL a lot more powerful and clean.

Let’s break it down in a simple way.


Subqueries (a query inside a query)

A subquery is exactly what it sounds like — you run one query inside another one.

Think of it like:

“I need one answer first, so I can use it in another question.”

Example:

```sql id="a1b2c3"
SELECT name, salary
FROM employees
WHERE salary > (
SELECT AVG(salary)
FROM employees
);




What’s happening here?

* First, SQL calculates the average salary
* Then it uses that result to filter employees

So instead of doing it manually, SQL handles it in one go.

---

# A simple way to think about it

Imagine your manager says:

> “Show me employees who earn more than the company average.”

You don’t guess the average. You calculate it first. That’s the subquery part.

---

# When subqueries make sense

Use them when:

* You need a quick calculation inside another query
* You’re filtering using averages, counts, or totals
* The logic is small enough to fit in one place

But honestly… once things get more complex, subqueries start to feel messy.

That’s where CTEs come in.

---

# CTEs (Common Table Expressions)

CTEs are just a cleaner way of writing complicated queries.

Instead of nesting everything, you break your query into steps and give them names.

It starts with `WITH`.

### Example:



```sql id="d4e5f6"
WITH high_earners AS (
    SELECT name, salary
    FROM employees
    WHERE salary > 50000
)
SELECT *
FROM high_earners;

Enter fullscreen mode Exit fullscreen mode


Why CTEs feel better

If subqueries feel like stacking papers inside envelopes, CTEs feel like labeling folders.

You can actually read your query like a story:

  1. First, get high earners
  2. Then use them in the final result

It’s much easier to follow.


Same problem, two styles

Let’s say we want customers who spent more than 1000.

Subquery version:

```sql id="g7h8i9"
SELECT customer_id, total_spent
FROM (
SELECT customer_id, SUM(amount) AS total_spent
FROM sales
GROUP BY customer_id
) x
WHERE total_spent > 1000;




### CTE version:



```sql id="j1k2l3"
WITH customer_totals AS (
    SELECT customer_id, SUM(amount) AS total_spent
    FROM sales
    GROUP BY customer_id
)
SELECT *
FROM customer_totals
WHERE total_spent > 1000;

Enter fullscreen mode Exit fullscreen mode

Same result. One just feels way easier to read.


When to use what (real talk)

Use subqueries when:

  • The logic is short
  • You just need one quick calculation
  • You don’t want extra structure

Use CTEs when:

  • Your query is getting long
  • You’re doing multiple steps
  • You want your SQL to look clean and readable
  • You’re working in a team

The honest takeaway

Nobody really cares if you use subqueries or CTEs in isolation.

What matters is:

Can someone else read your SQL without getting confused?

That’s where CTEs usually win.

But good SQL developers don’t pick sides — they use whatever makes the query clearer.


Final thought

When I first learned this, I thought it was just “advanced SQL stuff.”

But really, it’s just about organizing your thinking.

Subqueries = quick thinking
CTEs = structured thinking

Both are useful. You just get better at knowing when to switch.


If you're learning SQL right now, don’t rush this part. Write messy queries first, then refactor them into cleaner CTEs. That’s where the real growth happens.