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

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

A CTE and a subquery can express the same relational logic: a subquery nests an intermediate SELECT where it is used, while a common table expression (CTE) names that query in a WITH clause. Use a short, single-use subquery when keeping the logic beside its join or condition is clearest; choose a nonrecursive CTE when named stages or multiple references make the query easier to inspect. Neither form guarantees faster execution—the database engine and query shape matter.

What is the difference between a subquery and a CTE?

A subquery is a SELECT nested inside another SQL statement. A CTE is a named query introduced by WITH and available within the scope of one statement. The main practical difference is how you organize the SQL: a subquery puts its logic inline, while a CTE gives that logic a name that the rest of the statement can refer to.

For example, both forms below select customers who have orders dated on or after January 1, 2026. The date-literal syntax shown is not universal; check the target database’s rules.

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

Inline subquery

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'
);

Nonrecursive CTE

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);

The CTE version gives the intermediate result a descriptive name, recent_orders. In a larger query, that name can make the purpose of a stage easier to see. In the shorter version, the filter stays next to the condition that uses it. These examples illustrate equivalent relational intent, not a guarantee that every rewritten query is interchangeable without checking its logic and dialect syntax.

#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.

When should I use a CTE instead of a subquery?

Choose based on how the query will be read, maintained, and used—not on an assumption that one syntax is inherently better.

Use an inline subquery for short, single-use logic

An inline subquery is often the more direct choice when the intermediate query is small, appears once, and is easy to understand in place. It keeps a simple filter or derived relation close to the join or condition that depends on it. Naming every small expression as a separate CTE can make a straightforward statement longer without making its dependencies easier to follow.

Use a nonrecursive CTE for named stages

A CTE is useful when a statement consists of meaningful steps—for example, first defining a filtered set and then using it in a later part of the statement. A name such as recent_orders tells a reader what the intermediate result represents. That can help reviewers follow a multi-stage transformation without mentally unpacking several levels of nested parentheses.

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

A CTE can also be helpful during review: its defining query can be inspected as a standalone SELECT to check what rows that stage produces. Treat this as a way to inspect the logic, not as proof that the database stores or caches the result.

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 a recursive CTE for hierarchy traversal

When the task is to walk a parent-child hierarchy, tree, or graph, a recursive CTE provides an anchor-plus-recursive-member structure. Typical use cases include organizational charts and bills of materials. A nonrecursive subquery does not provide that recursive traversal pattern.

Are CTEs faster than subqueries?

There is no universal speed ranking. The keyword alone does not tell you whether the engine will inline, materialize, or re-execute a query; behavior depends on the database system and the query.

Microsoft’s SQL Server documentation says CTE query results are not materialized and that each outer reference to a named result set requires the defined query to be re-executed. PostgreSQL documents different planning behavior: a WITH query is normally evaluated once per execution when referenced more than once, while a side-effect-free, nonrecursive query may be folded into its parent query. PostgreSQL also allows MATERIALIZED or NOT MATERIALIZED to override that choice. These are engine-specific rules, not interchangeable promises about all CTEs.

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

Consequently, rewriting a subquery as a CTE—or the reverse—may affect optimization on a particular engine, especially when the named result is referenced repeatedly. It may also make no meaningful difference. Check the execution plan and row counts on the actual database engine and version, using representative data, before attributing a performance change to the syntax. The cited documentation does not establish a cross-database benchmark or a general percentage improvement.

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.

Is a CTE just a temporary table?

No. A CTE is a named result set scoped to one SQL statement; it is not automatically a stored intermediate table. Microsoft explicitly says CTE results are not materialized in SQL Server. SQLite describes ordinary CTEs as acting like temporary views that exist only for one statement. PostgreSQL’s evaluation and folding behavior depends on the query and its planning rules.

A temporary table is a separate design choice. Consider one when a workflow spans multiple statements, needs indexes or statistics between steps, or must retain intermediate data beyond a single statement. A CTE is appropriate for naming logic inside one statement; it should not be assumed to provide persistence or the physical storage behavior of a temporary table.

Can a subquery be rewritten as a CTE?

Often, yes: move the nested query into a named expression in a WITH clause, then refer to that name from the main statement. The two example queries above show this transformation. Before treating the rewrite as complete, verify that the intermediate query returns the intended columns and rows, that the main statement uses it in the same logical way, and that the syntax is valid for the target database.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Identify the nested query. Confirm what it returns and where the outer statement uses it.
  2. Give the intermediate result a useful name. Put its SELECT inside a CTE introduced by WITH.
  3. Replace the inline query with a reference to the CTE. Keep the outer condition or join logically equivalent.
  4. Check the result and plan on the target engine. Compare row counts and execution plans rather than assuming the rewrite is faster or identical in performance.

The reverse transformation is also possible when a CTE is used only once: place its defining query inline at the point where the CTE name is referenced. If the CTE has several references or represents a useful named stage, removing the name may make the statement harder to review, and engine-specific evaluation behavior still matters.

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

What changes across SQL databases?

The organizational idea is widely useful, but CTE grammar and behavior are not identical across database systems. Check the documentation for the engine and version that will run the statement, particularly before using recursion or relying on optimization behavior.

Database documentation What it establishes Practical implication
Microsoft SQL Server A CTE is a temporary named result set scoped to one statement. Results are not materialized; each outer reference requires re-executing the defined query. Do not treat repeated CTE references as proof that the intermediate result is stored once.
SQLite Ordinary CTEs factor out subqueries and can make a statement easier to understand. CTEs act like temporary views for one statement; recursive CTEs support tree and graph traversal. Use a CTE to name a stage or express traversal, while checking SQLite’s own grammar and recursive restrictions.
PostgreSQL A WITH query is normally evaluated once per execution when referenced multiple times. A side-effect-free, nonrecursive query can be folded into its parent; MATERIALIZED and NOT MATERIALIZED can override the choice. Do not assume PostgreSQL’s planning behavior applies to another engine or every kind of CTE.

These documented differences are enough to rule out a blanket statement such as “CTEs always run once” or “CTEs always create a temporary table.” SQL Server and SQLite also differ in allowed statements and recursive restrictions, so portability requires checking the target dialect rather than relying on a query that happens to work elsewhere.

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

How do recursive CTEs work?

A recursive CTE builds a result iteratively. It begins with an anchor member, then runs a recursive member using output from the preceding iteration; recursion stops when the recursive member returns no rows. Microsoft documents this anchor-and-recursive-member sequence for SQL Server.

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

This structure suits data where each step can lead to another related step, such as moving from a manager to direct reports or from a component to subcomponents. The recursive member defines how the next set of rows is found; the anchor establishes where traversal begins. Because recursive syntax and restrictions vary by database, consult the relevant engine documentation before relying on a particular form.

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.

How should I decide between the two?

Use the form that makes the query’s dependencies easiest for the next reader to inspect. The following guide separates the common cases without implying a performance result.

  • Short expression, one use: prefer an inline subquery if it remains easy to read beside its condition or join.
  • Several logical stages: prefer nonrecursive CTEs when names make the transformation easier to scan or review.
  • Repeated references: a CTE can give a derived relation one name for use in multiple parts of a statement, but do not infer materialization; verify how the target engine handles those references.
  • Hierarchy or graph walk: use a recursive CTE where the database supports the required recursive form.
  • Multiple statements, indexes, or retained intermediate data: evaluate a temporary table rather than expecting a CTE to persist data.
  • Performance-sensitive rewrite: compare plans and row counts on the actual engine and version with representative data.

For a team query, the best choice may also depend on review conventions: consistently named stages can make a complicated transformation easier to discuss, while a simple inline expression avoids unnecessary scaffolding. The useful test is whether a reader can see what each part produces and how the next part depends on it.

Frequently Asked Questions

Does a CTE exist after the SQL statement finishes?

No. A CTE’s name is scoped to the statement that defines it. If later statements need an intermediate result, use a separate mechanism designed for data that must outlive that statement.

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

Can I use more than one CTE in a query?

A statement can be organized into named stages, but the exact grammar and rules for how those stages refer to one another depend on the database dialect. Check the target engine’s documentation when portability matters.

Should I convert every nested SELECT into a CTE?

No. A CTE is valuable when naming a stage improves comprehension; for a short expression used once, nesting can keep the logic closer to where it matters. Prefer clarity over a blanket formatting rule.

What should I inspect when a CTE rewrite changes performance?

Compare the execution plan and row counts on the same database engine and version, using representative data. A change may come from engine-specific optimization or reference behavior, so syntax alone does not identify the cause.

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.

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