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

2025/11/20 02:55

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.

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

Polymarket, Kalshi bet big on web3—and global expansion

Polymarket, Kalshi bet big on web3—and global expansion

The post Polymarket, Kalshi bet big on web3—and global expansion appeared on BitcoinEthereumNews.com. Polymarket and Kalshi are doubling down on their future — literally — as both prediction-market platforms push into web3 and global markets in search of new revenue streams. Both startups are also on the hunt for regulatory approvals, and partnerships with sports organizations. Summary Polymarket and Kalshi reportedly kicked off expansion efforts. The plans were unveiled at a private New York dinner attended by ICE CEO Jeffrey Sprecher. Both platforms are exploring decentralized technologies and international venue partnerships as trading volumes rise. Bloomberg reports the expansion was kicked off in classic Wall Street fashion: with a private dinner high above New York’s financial district, where even Intercontinental Exchange CEO Jeffrey Sprecher showed up. Why it matters Both companies have been ramping up their growth strategies, each aiming to break out of their current lanes. Polymarket, which is about to relaunch in the U.S., and Kalshi, which just partnered with Coinbase, are now circling opportunities in web3 technologies — essentially taking prediction markets from the basement of the internet to the broader blockchain universe. As trading volumes rise, regulators and institutional players have been paying much closer attention to the sector — and so is big tech. Alphabet, for example, will soon display live probabilities from Kalshi and Polymarket on Google Finance and Google Search. This will allow users to type natural-language questions such as “Will the Fed cut rates in December?” and instantly see odds and how they’ve shifted over time. Kalshi supplies regulated U.S. event markets tied to economic data and policy decisions, while Polymarket covers a wider global range of topics, including politics, sports, and crypto. Both platforms have seen rising activity as more traders rely on prediction markets to assess future outcomes rather than traditional polls or analyst forecasts. Still, details on specific deals or regulatory filings…
Share
BitcoinEthereumNews2025/11/21 10:27
Why are XRP, BTC, ETH, and DOGE Prices Crashing?

Why are XRP, BTC, ETH, and DOGE Prices Crashing?

The post Why are XRP, BTC, ETH, and DOGE Prices Crashing? appeared on BitcoinEthereumNews.com. XRP, BTC, ETH, and DOGE prices are experiencing significant declines, with the overall crypto market down 2.71% in the past 24 hours. Bitcoin has fallen below $90K, and Ethereum dropped under $3K, contributing to a broader market downturn. XRP Price Struggles as Price Dips Below $2 In the last 24 hours, the XRP price crashed by 2% and it has reduced by 15% in the current week, at a lower price of less than $2 in a bearish market. The price of the cryptocurrency is presented in the form of a descending triangle, which is indicative of the risk of a further decrease. A breakdown of major support lines added to the decline in the recent past, leading to stop-losses and a minor spurt of leveraged sell-side liquidations. Moreover, the whale action increased with 190 million XRP being sold within the past 48 hours. In the meantime, there is a Bitwise XRP ETF that has been launched, but the situation is unstable in the market. 190 million $XRP sold by whales in the last 48 hours! pic.twitter.com/nB0P7jADCx — Ali (@ali_charts) November 20, 2025 Bitcoin Price Plunges, Falling Below $90K Amid Market Sell-Off Bitcoin price dropped 2.24% to $86,858 over the past 24 hours, continuing a 12% weekly decline. The BTC was selling at a low of less than $90k as investor confidence shifted to the negative. Redemptions of Bitcoin ETFs amounted to a sharp decline of $3.3 billion this month, which further contributed to the negative pressure. Also, the Federal Reserve rate cut in December was in doubt, with the probability being now 33% and this burdened risk assets.  BTC also sent down vital support levels, causing automated selling. The recent better-than-anticipated jobs report in United States sparked a question as to what Fed would do in future. Ethereum Price…
Share
BitcoinEthereumNews2025/11/21 10:29
Music body ICMP laments “wilful” theft of artists’ work

Music body ICMP laments “wilful” theft of artists’ work

The post Music body ICMP laments “wilful” theft of artists’ work appeared on BitcoinEthereumNews.com. A major music industry group, ICMP, has lamented the use of artists’ work by AI companies, calling them guilty of “wilful” copyright infringement, as the battle between the tech firms and the arts industry continues. The Brussels-based group known as the International Confederation of Music Publishers (ICMP) comprises major record labels and other music industry professionals. Their voice adds to many others within the arts industry that have expressed displeasure at AI firms for using their creative work to train their systems without permission. ICMP accuses AI firms of deliberate copyright infringement ICMP director general John Phelan told AFP that big tech firms and AI-specific companies were involved in what he termed “the largest copyright infringement exercise that has been seen.” He cited the likes of OpenAI, Suno, Udio, and Mistral as some of the culprits. The ICMP carried out an investigation for nearly two years to ascertain how generative AI firms were using material by creatives to enrich themselves. The Brussels-based group is one of a number of industry bodies that span across news media and publishing to target the fast-growing AI sector over its use of content without paying any royalties. Suno and Udio, who are AI music generators, can produce tracks with voices, melodies, and musical styles that echo those of the original artists such as the Beatles, Depeche Mode, Mariah Carey, and the Beach boys. “What is legal or illegal is how the technologies are used. That means the corporate decisions made by the chief executives of companies matter immensely and should comply with the law,” Phelan told AFP. “What we see is they are engaged in wilful, commercial-scale copyright infringement.” Phelan. In June last year, a US trade group, the Recording Industry Association of America, filed a lawsuit against Suno and Udio. However, an exception…
Share
BitcoinEthereumNews2025/09/18 04:41