Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog › Common Table Expressions

Subquery vs CTE in SQL: How to Choose the Right Form

By Freedom251 Team · · 10 min read

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Subqueries and common table expressions (CTEs) can express the same relational logic, but they organize that logic differently. A subquery keeps a SELECT nested inside the statement where it is used. A CTE gives a query a name in a WITH clause, then lets the main statement refer to that name. Use an inline subquery for short, single-use logic that is clearest next to its predicate or join. Use a nonrecursive CTE when a query has named stages, a derived result is referenced more than once, or reviewers need to inspect an intermediate result. Use a recursive CTE for hierarchical or graph traversal. Neither keyword guarantees faster execution: the optimizer, database engine, version, references, and data determine the plan.

What is the difference between a subquery and a CTE?

An inline subquery is a nested SELECT statement placed inside another query. A CTE is a named query introduced by WITH and visible only to the statement that follows it. Both can define a derived relation and feed it into a larger query, so the choice is usually about structure, scope, reuse, and optimizer behavior rather than what rows are logically requested.

As an Amazon Associate I earn from qualifying purchases.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Inline subqueries keep short logic in place

A subquery appears where its result is needed: in a WHERE predicate, a FROM clause, or another expression. This keeps a compact condition close to the table or join it affects. The trade-off is that a deeply nested or repeated subquery can make the outer statement difficult to scan.

CTEs give intermediate queries a name

A CTE places the intermediate SELECT before the main statement:

#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter | 4Pack Type C Female to A Male Cable Converter for Apple Duo 17 16 15 14 Plus,iWatch Watch 12 11 10,iPad 9 8 Air,Airpods 5 4
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
WITH recent_orders AS (
  SELECT customer_id
  FROM orders
  WHERE order_date >= DATE '2026-01-01'
)
SELECT ...
FROM ...;

The name documents the role of that result and lets later clauses refer to it according to the target database’s grammar. A CTE is scoped to one SQL statement; it is not a database object that remains available afterward.

Equivalent logic does not mean identical execution

Two forms can return the same relational result while producing different execution plans. The optimizer may inline, fold, materialize, or re-execute an intermediate query depending on the engine and version. Treat syntax as a readability and dependency decision first, then verify performance on the actual system.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Can a subquery be rewritten as a CTE?

Yes, when the subquery is an independent relation. Move its SELECT into a named CTE and replace the original nested expression with a reference to that name.

Subquery form

SELECT c.customer_id
FROM customers AS c
WHERE c.customer_id IN (
  SELECT o.customer_id
  FROM orders AS o
  WHERE o.order_date >= DATE '2026-01-01'
);

CTE form

WITH recent_orders AS (
  SELECT customer_id
  FROM orders
  WHERE order_date >= DATE '2026-01-01'
)
SELECT c.customer_id
FROM customers AS c
WHERE c.customer_id IN (SELECT customer_id FROM recent_orders);

These statements illustrate the same relational intent. Date-literal syntax and optimization behavior vary by database management system, so run the form accepted by your engine and compare its result to the original.

Safe rewrite procedure

  1. Isolate the inner query. Confirm which columns it returns and whether it depends on columns from the outer query.
  2. Choose a descriptive CTE name. Name the business role, such as recent_orders, rather than a generic label such as temp1.
  3. Move the text into WITH name AS (...). Preserve filters, joins, grouping, and aliases.
  4. Replace every original use. Reference the CTE by name in the outer statement.
  5. Validate behavior. Compare row counts, duplicate handling, NULL behavior, and the execution plan before adopting the rewrite.

A correlated subquery refers to a value from the current outer row. It may require a different rewrite, such as a join or another staged expression; moving its text unchanged into a standalone CTE can change the meaning.

When should I use an inline subquery?

Choose an inline subquery when the expression is short, used once, and easier to understand at the point where it filters or joins data.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use it for a single local condition

If a nested query exists only to answer one predicate, keeping it beside that predicate makes the dependency obvious. The reader can understand the condition without jumping to the top of the statement.

Rank #2
Sale
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter | USB C Dongle with 90W Max Power Delivery, 3×5Gbps USB A Data Ports, for MacBook, Dell, and More (Charger Not Included)
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Use it when a name would add more ceremony than clarity

A one-line existence check or a small derived table may be clearer inline than as a separately named block. Avoid introducing a CTE solely because the query contains a nested SELECT; naming every tiny expression can make a short statement longer to navigate.

Watch for nesting that hides the data flow

Several levels of nested subqueries, repeated copies of the same expression, or a long derived table in the middle of a join are signs that a named stage may improve reviewability. At that point, the issue is not that subqueries are wrong, but that the dependency graph is hard to see.

When should I use a nonrecursive CTE?

Use a nonrecursive CTE when naming the intermediate relation makes a multi-stage transformation easier to read, test, or reuse in the same statement.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Break a transformation into reviewable stages

Separate filtering, aggregation, enrichment, and final presentation into named blocks. A reviewer can follow the data flow from one stage to the next instead of decoding a deeply nested expression.

Reuse a derived relation

A CTE can be referenced by multiple parts of one statement, subject to the database’s rules. This avoids copying the same SQL text into several subqueries and gives all references one definition to review. Reuse by name does not, by itself, promise that the database computes the result once.

Test an intermediate result

During development, replace the final statement with SELECT * from a CTE to inspect its rows and columns. This makes it practical to validate each stage before restoring the final joins or filters. Remove diagnostic projections and keep only the intended statement in production code.

Is a CTE just a temporary table?

No. A CTE is a statement-scoped query definition, not a table that persists for later statements and not automatically an indexed storage structure.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter | 85W Max PD, 2 USB 3.0 & 1 USBC Data Ports, SD/TF Card Reader, for Laptops/Mac and Other Type C Devices (Charger Not Included)
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
Characteristic CTE Temporary table
Lifetime Only the single statement that follows the WITH clause Can remain available across multiple statements according to the engine and session or transaction rules
Definition Query text with a name Table object populated by an explicit statement
Indexes and statistics Not automatically a separately indexable table Can be designed with indexes or statistics where the engine supports them
Best fit Readable, statement-local transformations Multi-statement workflows, large intermediates, or a deliberate storage and indexing step

Microsoft describes a CTE as a temporary named result set within the execution scope of one statement and warns that its query results are not materialized by definition. If the same named result is referenced more than once in SQL Server, each outer reference requires the defined query to be re-executed. That behavior is why a temporary table can be the better design when you need indexes, statistics, or reuse across separate statements.

Are CTEs faster than subqueries?

There is no cross-database rule that makes CTEs faster or slower than subqueries. The keyword alone does not predict runtime; compare actual plans and row counts on your database engine, version, schema, and data.

SQL Server: a CTE name is not a cache

SQL Server documentation states that CTE query results are not materialized and that each outer reference to the named result set requires the defined query to be re-executed. If a statement refers to the CTE several times, inspect the plan rather than assuming one computation is shared. Persisting the intermediate rows in a temporary table is a separate choice with different storage and indexing consequences.

PostgreSQL: folding and materialization can vary

PostgreSQL documents that a WITH query is normally evaluated once per execution when referenced more than once. A side-effect-free, nonrecursive WITH query may instead be folded into the parent query, and the MATERIALIZED or NOT MATERIALIZED options can override that choice where supported. Therefore, the same CTE text can be optimized differently depending on reference count and whether the planner can safely fold it.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

SQLite: use CTEs primarily to factor logic

SQLite describes ordinary CTEs as a way to factor out subqueries and make a statement easier to read and understand. It treats them like temporary views that exist only for one SQL statement. That description is a readability and scope guarantee, not a universal promise about physical storage or speed.

A practical performance check

  1. Run the original and rewritten statements against the same data snapshot.
  2. Capture each engine’s estimated or actual execution plan using its plan-inspection command.
  3. Compare scans, seeks, joins, sorts, spills, row estimates, and total work rather than looking only at elapsed time from one run.
  4. Test selective and large data sets, because an optimization that helps one cardinality can hurt another.
  5. Keep the clearer form unless the measured plan shows a meaningful, repeatable reason to choose the other.

How do recursive CTEs work?

A recursive CTE is the standard choice for repeatedly following parent-child relationships, such as organizational charts, bill-of-materials structures, directory trees, and graph or tree walks.

Anchor member

The anchor query produces the starting rows. For an organization chart, that could be the top-level manager; for a parts hierarchy, it could be the finished product.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray | Data transfer & Fast charging for MacBook, iPhone 17/16/15, iPad, Samsung Galaxy, Apple Watch
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Recursive member

The recursive query joins the prior output to the next level and produces another set of rows. Microsoft describes the process as running the anchor first, then repeatedly applying the recursive member to prior output.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Termination

Recursion stops when the recursive member returns no rows. The relationship must therefore have a reliable stopping condition, and the statement must follow the recursion and cycle restrictions of the target database. SQL Server and SQLite do not have identical grammar or recursive rules, so test the exact statement on every engine you support.

Use a recursive CTE for traversal, not merely to make an ordinary query look sophisticated. For a flat filter or aggregation, a nonrecursive CTE or inline subquery is easier to review.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

What are the scope and portability limits?

Both forms are statement-scoped, but their syntax and permitted contexts depend on the database management system.

Statement scope

A CTE name is available only within the statement that follows its WITH clause. An inline subquery is even more local: it exists only at the expression or table position where it is written. Neither creates a reusable view or a permanent schema object.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Dialect grammar

SQL Server documents CTEs for a statement beginning with SELECT, INSERT, UPDATE, MERGE, or DELETE. SQLite and other engines have their own rules for which statements, recursive forms, and clauses are allowed. If portability matters, check each target engine’s current grammar and run representative statements in every dialect rather than assuming that a valid WITH clause transfers unchanged.

Date and expression syntax

The example uses the SQL-standard-looking DATE '2026-01-01' literal. Some engines accept that form; others require a different date expression. Treat the relational rewrite as portable intent, not as a promise that every token is portable.

Best Value
Sale
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display | 85W Max PD, 1 Powered USB-C 5Gbps & 2 Powered USB-A 3.0 5Gbps Data Ports, for MacBook Pro, MacBook Air, Dell and More (Black)
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Which form should I choose?

Use the following decision guide before changing syntax.

Your situation Starting choice Reason
One short condition used once Inline subquery Keeps the logic beside the predicate or join
Several named transformation stages Nonrecursive CTE Makes the data flow easier to scan and review
The same derived relation appears in several places in one statement Nonrecursive CTE, then inspect the plan Provides one definition, without assuming materialization
Parent-child, hierarchy, tree, or graph traversal Recursive CTE Provides the anchor-plus-recursive-member pattern
Intermediate rows need indexes, statistics, or several statements of reuse Temporary table Those are storage and workflow requirements, not just naming requirements
Performance is the deciding factor Either form, measured on the target engine No universal speed ranking exists

How should I review a query that uses either form?

Review the dependency graph before debating the keyword. Ask what the intermediate rows represent, whether the expression is correlated, how many times it is referenced, and whether the statement must work on more than one engine.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Give CTEs names that describe their rows, grain, or business purpose.
  • Keep an inline subquery close to the condition it explains when that improves local clarity.
  • Check for accidental duplicate rows when replacing a predicate with a join.
  • Confirm that filters are applied at the intended stage and that aliases remain unambiguous.
  • For recursive statements, verify the anchor, recursive relationship, stopping behavior, and dialect-specific limits.
  • Use an execution plan for performance claims; readability alone is not evidence of a faster query.

The best rewrite is the one a future reader can inspect without reconstructing hidden dependencies, while still matching the optimizer and operational requirements of the database you actually run.

Frequently Asked Questions

Can I reference the same CTE from multiple statements?

No. A CTE name ends with the single statement that follows its WITH clause. If later statements need the rows, create a view, populate a temporary table, or repeat the definition according to your workflow.

Can I create an index directly on a CTE?

A CTE is a query definition rather than a separately managed table, so it is not the place to design persistent indexes. If indexing the intermediate rows is essential, materialize them in a table structure supported by your database and index that structure.

Why did a CTE rewrite change my row count?

The rewrite may have altered correlation, join cardinality, duplicate handling, or the point at which a filter is applied. Compare the intermediate rows and predicates stage by stage before comparing the final totals.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Do recursive CTEs work the same way in every database?

No. Engines differ in recursive grammar, allowed clauses, and restrictions. Treat the anchor-and-recursive-member idea as portable, but validate the exact syntax and termination behavior on each target system.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Common Table ExpressionsCTEdatabase performancePostgreSQLSQLSQL ServerSQLiteSubqueries

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.