The "bad" correlated subquery outperformed the "good" JOIN. The subquery triggered a Nested Loop plan with fast index lookups (25 quick searches)The "bad" correlated subquery outperformed the "good" JOIN. The subquery triggered a Nested Loop plan with fast index lookups (25 quick searches)

Is JOIN Faster Than Correlated Subqueries? Taking a Look and Subsequently Debunking the Myth

4 min read

Hey there, fellow developers! If you've ever dabbled in SQL, you've probably heard the golden rule: "Never use correlated subqueries in SELECT—they're a recipe for N+1 disasters!" Instead, we're told to always opt for JOINs because they're set-based, efficient, and lightning-fast.

\ But is this rule set in stone? I decided to put it to the test across four popular database systems: MySQL 8.0, Oracle 23c, PostgreSQL 16, and SQLite 3.45. Spoiler alert: The results were eye-opening. Sometimes, the "bad" correlated subquery outperformed the "good" JOIN. Let's dive in and see why.

The Test Setup: Customers and Orders

To keep things fair, I used a simple schema with two tables:

Customers: A small table with 25 rows of customer data.

Orders: A larger table with 1,000 rows of orders, linked via a foreign key. The goal? Count the number of orders per customer, including those with zero orders.

\ Here's the schema (using MySQL syntax for reference):

-- Table of customers CREATE TABLE customers ( customer_id INT PRIMARY KEY, name VARCHAR(255) NOT NULL ); -- Table of orders CREATE TABLE orders ( order_id INT PRIMARY KEY, customer_id INT, order_date DATETIME, FOREIGN KEY (customer_id) REFERENCES customers(customer_id) ON DELETE CASCADE );

Data was populated with random values to simulate real-world scenarios.

The Two Queries: JOIN vs. Correlated Subquery

I compared two approaches to achieve the same result.

  1. The "Good" Way – JOIN + GROUP BY - This is the set-based, relational approach everyone loves:

    \

SELECT c.customer_id, COUNT(o.order_id) AS orders_count FROM customers c LEFT JOIN orders o ON c.customer_id = o.customer_id GROUP BY c.customer_id;

\

  • Pros: Handles all customers, even those without orders.
  • Theory: One optimized operation to join and aggregate.

\

  1. The "Bad" Way – Correlated Subquery This is the row-by-row method we're warned against:

    \

SELECT c.customer_id, (SELECT COUNT(o.order_id) FROM orders o WHERE o.customer_id = c.customer_id) AS orders_count FROM customers c;

\

  • Pros: Also includes customers with zero orders.
  • Theory: Executes a subquery for each customer—classic N+1 problem.

\

Testing Across Databases: The Results

I ran both queries on online SQL testers (links provided below) and analyzed execution times and plans using EXPLAIN. Here's what happened.

MySQL 8.0: Subquery Wins!

Execution Times: Subquery ~14 ms vs. JOIN ~16 ms.

\ Why? The subquery triggered a Nested Loop plan with fast index lookups (25 quick searches). JOIN used Hash Join + Aggregate, which was overkill for small data.

\ Key Insight: With an index on orders.customer_id, the subquery wasn't N+1—it was efficient Nested Loops.

\ Test Link: MySQL Tester

Oracle 23c: Subquery Dominates!

Execution Times: Subquery ~2.4 ms vs. JOIN ~15 ms.

\ Why? Similar to MySQL—Nested Loop for subquery vs. Hash Join for JOIN. The subquery avoided heavy aggregation overhead.

\ Key Insight: Indexes are crucial; without them, Oracle falls back to full scans.

\ Test Link: Oracle Tester

PostgreSQL 16: JOIN Takes the Lead

Execution Times: JOIN ~0.6 ms vs. Subquery ~1.9 ms.

\ Why? PostgreSQL's optimizer rewrote the subquery into a JOIN-like plan, but the explicit JOIN was slightly faster. Subquery showed 25 sub-plan executions (mild N+1).

\ Key Insight: PostgreSQL is smart—indexes level the playing field.

\ Test Link: PostgreSQL Tester

SQLite 3.45: A Tie!

Execution Times: Both ~1 ms.

\ Why? Plans were nearly identical: SCAN on customers + SEARCH on orders via index. No N+1 effect.

\ Key Insight: SQLite's simplicity made both queries efficient; choose based on readability.

\ Test Link: SQLite Tester

Key Takeaways: No Silver Bullet

The "JOIN is always faster" myth crumbles because performance depends on:

  • Database Optimizer: PostgreSQL rewrites queries; MySQL/Oracle follow your syntax more literally.
  • Data Size: Small outer tables (like our 25 customers) favor Nested Loops; large ones benefit from Hash Joins.Indexes: Without an index on orders.customer_id, subqueries tank. With it, they shine.
  • Bottom Line: Don't blindly follow rules. Always run EXPLAIN (or EXPLAIN ANALYZE) to see the actual execution plan. Test with your data!

\ What are your experiences with JOINs vs. subqueries? Drop a comment below!

\ This article is based on real testing and analysis. Links to testers are provided for you to verify the results.

Market Opportunity
LOOK Logo
LOOK Price(LOOK)
$0.01131
$0.01131$0.01131
-1.04%
USD
LOOK (LOOK) Live Price Chart
Disclaimer: The articles reposted on this site are sourced from public platforms and are provided for informational purposes only. They do not necessarily reflect the views of MEXC. All rights remain with the original authors. If you believe any content infringes on third-party rights, please contact service@support.mexc.com for removal. MEXC makes no guarantees regarding the accuracy, completeness, or timeliness of the content and is not responsible for any actions taken based on the information provided. The content does not constitute financial, legal, or other professional advice, nor should it be considered a recommendation or endorsement by MEXC.

You May Also Like

Why Multicoin Capital’s Kyle Samani Is Leaving Crypto for AI and Robotics

Why Multicoin Capital’s Kyle Samani Is Leaving Crypto for AI and Robotics

TLDR Kyle Samani is stepping down as managing partner of Multicoin Capital after nearly a decade in the crypto industry He plans to explore other technologies including
Share
Coincentral2026/02/05 15:58
Bitcoin Bulls Need to Reclaim This Key Level for a New Run at $125K

Bitcoin Bulls Need to Reclaim This Key Level for a New Run at $125K

The post Bitcoin Bulls Need to Reclaim This Key Level for a New Run at $125K appeared on BitcoinEthereumNews.com. Key points: Bitcoin bulls are busy flipping key levels back to support; can they crack $118,000 next? New all-time highs are on the horizon if the Fed reaction uptrend continues. Exchange traders are already bringing in large lines of liquidity on either side of price. Bitcoin (BTC) sought to flip $117,000 to support on Thursday as the Federal Reserve interest-rate cut boosted crypto markets. BTC/USD one-hour chart. Source: Cointelegraph/TradingView Watch these Bitcoin price levels next, say traders Data from Cointelegraph Markets Pro and TradingView showed BTC/USD gaining up to 1.3% after the daily close. Volatility hit as the US Federal Reserve announced its first rate cut of 2025, coming in at 0.25% to match market expectations. After a brief dip below $115,000, Bitcoin rebounded, liquidating both long and short positions to the tune of over $100 million over 24 hours. $BTC update: FOMC Price Action nailed 🔨 Boring Monday and Tuesday; Wednesday volatile with the classic retrace of an initial false move. $105M liquidated in 30mins during FOMC, that’s what it’s important to be aware of this. Absolutely love this market. Probably $120k next. https://t.co/azE7Fg6J10 pic.twitter.com/x3EPCmIlOx — CrypNuevo 🔨 (@CrypNuevo) September 17, 2025 Among traders, hopes were high that bulls would cement support and continue on to challenge all-time highs. “The more important part; will $BTC break through this crucial resistance zone?” crypto trader, analyst and entrepreneur Michaël van de Poppe queried in a post on X. An accompanying chart showed the bulls’ next battle at $118,000.  “All I’m sure about is that, once Bitcoin stabilizes, we’ll start to see big breakouts on Altcoins occur,” he added. BTC/USDT one-day chart with RSI, volume data. Source: Michaël van de Poppe/X Popular trader Daan Crypto Trades agreed on the significance of the $118,000 mark. During dovish comments by Fed Chair Jerome Powell…
Share
BitcoinEthereumNews2025/09/19 10:20
SUI Price Rebounds Above $1 as HashKey Enables Trading Support

SUI Price Rebounds Above $1 as HashKey Enables Trading Support

The post SUI Price Rebounds Above $1 as HashKey Enables Trading Support appeared on BitcoinEthereumNews.com. SUI price gives a major breakdown from the support
Share
BitcoinEthereumNews2026/02/05 16:32