NewsCrawler.org

SQL WITH clause, subquery or JOIN: how to choose between them

【SQL】WITH句って本当に必要?サブクエリ・JOINとの違いと使い分けを整理してみた
Image: zenn.dev

While fixing SQL that stacked several WITH clauses with subqueries inside, the author compared three ways to list departments with an average salary of 400,000 yen or more: a direct query with HAVING[1], a subquery[2], and a WITH clause defining a CTE[3]. All three return the same rows, and for that example the author found the plain HAVING query simplest — a WITH clause does not by itself make SQL easier to read. As a rule of thumb, subqueries suit one-off comparisons and IN or EXISTS checks; WITH suits step-by-step processing — for example, monthly sales totals before a yearly sum — and logic referenced in several places; plain SELECT with JOIN is enough for simple joins and aggregation. A CTE is not a real table, and speed has no single answer: PostgreSQL may fold a CTE into the parent query or compute it separately, SQL Server usually does not materialize[4] CTE results and can re-run them when they are referenced again, and a database can skip fetching columns listed in a CTE that the outer query never uses. The author concludes that the question is not whether to use WITH, but whether naming a step helps the person reading the query.

Read the original zenn.dev

Sources

  • Zenn JA

    【SQL】WITH句って本当に必要?サブクエリ・JOINとの違いと使い分けを整理してみた

    1 like0 bookmarks0 comments

Published: First seen: Читать по-русски

Open as a page