Mastering MySQL for Data AnalystsLesson 24 of 42
Lesson 24 of 42

Subqueries in MySQL: Scalar, Multi-Row, IN, ANY & ALL

Overview & Learning Objectives

A subquery is a nested query enclosed in parentheses embedded inside an outer SQL statement. In data analytics, subqueries allow dynamic filtering against calculated benchmarks—such as finding orders exceeding the store average, or retrieving customers who purchased items from top-selling categories. MySQL classifies subqueries into Scalar (returning a single 1x1 value) and Multi-Row (evaluated via `IN`, `ANY`, `ALL`).

  • Write scalar subqueries to benchmark individual rows against dynamic aggregate metrics.
  • Construct multi-row subqueries using `IN`, `NOT IN`, `ANY`, and `ALL`.
  • Understand how the MySQL optimizer rewrites subqueries into semi-joins.

Industry Standard

Standard: Analytics engineering standards at Uber mandate checking execution plans for subqueries to ensure the MySQL optimizer decorrelates or flattens nested queries into semi-joins.

Real-World Example: ScoopCraft Above-Average Order Basket Isolation

ScoopCraft identifies high-value orders that generated higher revenue than the nationwide average order value.

order_iddark_storeorder_totalNational Avg (Subquery)Variance
ORD-601Koramangala Hub₹550.00₹340.00+₹210.00 (Above Average)
ORD-602Indiranagar Hub₹280.00₹340.00-₹60.00 (Excluded by WHERE)
ORD-603Whitefield Hub₹680.00₹340.00+₹340.00 (Above Average)

Syntax & Core SQL Implementation

-- Scalar subquery in WHERE clause
SELECT order_id, dark_store, order_total
FROM orders
WHERE order_total > (
    SELECT AVG(order_total) FROM orders
);

-- Multi-row subquery using IN
SELECT customer_name, email
FROM customers
WHERE customer_id IN (
    SELECT DISTINCT customer_id 
    FROM orders 
    WHERE order_total > 1000.00
);

-- Multi-row subquery using > ALL
SELECT product_name, price
FROM products
WHERE price > ALL (
    SELECT price FROM products WHERE category = 'Cones'
);

Parameters & Arguments Breakdown

  • Scalar Subquery: Returns exactly 1 column and 1 row (used with =, >, <).
  • IN: Evaluates to TRUE if candidate value matches any value returned by subquery.
  • ANY / SOME: Compares value to each value in subquery (e.g. > ANY means greater than at least one value).
  • ALL: Compares value to every value in subquery (e.g. > ALL means greater than the maximum value in subquery).

Sample Walkthrough (Q&A)

Question: What happens if a scalar subquery in a WHERE comparison returns 2 rows instead of 1?

SQL Pattern: WHERE price > (SELECT price FROM products WHERE category = "Tubs")

Result: Error Code 1242: Subquery returns more than 1 row

Explanation: Scalar operators (=, >, <) require strict 1x1 cardinality. For multi-row results, use IN, ANY, or ALL.

Common Mistakes & Limitations

  • Using a scalar comparison operator (`=`) when the subquery can return multiple records, causing runtime crashes.
  • Nesting deeply repeated subqueries in the `SELECT` column list ($O(N)$ execution), creating massive I/O bottlenecks.

Keyboard Shortcuts (MySQL Workbench)

ActionWindowsMac
Execute QueryCtrl + EnterCmd + Enter

Pro Tips & Modern Best Practices

  • In MySQL 8.0, the query optimizer automatically transforms most `WHERE col IN (SELECT ...)` subqueries into efficient Semi-Joins under the hood.
  • Prefer `> (SELECT MAX(price) ...)` over `> ALL (...)` for cleaner query readability and deterministic index seeks.