Skip to main content

Fun with subqueries in duckdb

Correlated and uncorrelated subqueries

data analysis
Author

Joram Mutenge

Published

2026-11-25

Most business questions cannot be answered with a single query. Instead, they require multiple queries. Fortunately, you can nest those queries into a single query and execute them together to get your answer. This is where subqueries come into the picture. Subqueries are useful because they make your SQL code easier to understand and reason about. In this article, I’ll explore the two types of subqueries: correlated and uncorrelated.

The dataset

I’ll be using a dataset containing transactions from a clothing store. I’ll read the data directly from the web. First, I’ll create a temporary table called sales, which will contain the data I’ll use throughout the analysis.

CREATE TEMP TABLE sales AS (
    SELECT * EXCLUDE('Account Number', 'Account Name')
    FROM read_csv_auto(
        'https://raw.githubusercontent.com/jorammutenge/learn-rust/refs/heads/main/sample_sales.csv'
    )
);

Let’s display the data.

FROM sales;
┌──────────┬──────────┬──────────┬────────────┬───────────┬─────────────────────┐
│   sku    │ category │ quantity │ unit price │ ext price │        date         │
│ varchar  │ varchar  │  int64   │   double   │  double   │      timestamp      │
├──────────┼──────────┼──────────┼────────────┼───────────┼─────────────────────┤
│ HX-24728 │ Hat      │        1 │      98.98 │     98.98 │ 2014-09-28 11:56:02 │
│ LK-02338 │ Sweater  │        9 │       34.8 │     313.2 │ 2014-04-24 16:51:22 │
│ ZC-07383 │ Sweater  │       12 │      60.24 │    722.88 │ 2014-09-17 17:26:22 │
│ QS-76400 │ Sweater  │        5 │      15.25 │     76.25 │ 2014-01-30 07:34:02 │
│ RU-25060 │ Sweater  │       19 │      51.83 │    984.77 │ 2014-08-24 06:18:12 │
│    ·     │    ·     │        · │        ·   │       ·   │          ·          │
│    ·     │    ·     │        · │        ·   │       ·   │          ·          │
│    ·     │    ·     │        · │        ·   │       ·   │          ·          │
│ FT-50146 │ Sweater  │        2 │      46.48 │     92.96 │ 2014-08-10 16:20:32 │
│ IC-59308 │ Socks    │       19 │      29.25 │    555.75 │ 2013-11-20 13:32:45 │
│ IC-59308 │ Socks    │       18 │      54.79 │    986.22 │ 2014-03-10 08:11:59 │
│ RU-25060 │ Sweater  │       15 │      62.53 │    937.95 │ 2014-04-11 02:50:03 │
│ LK-02338 │ Sweater  │       11 │       86.4 │     950.4 │ 2014-02-14 20:10:42 │
└──────────┴──────────┴──────────┴────────────┴───────────┴─────────────────────┘
  1000 rows (10 shown)        use .last to show entire result         6 columns

What’s a subquery?

A subquery is simply a query within another query. For example, say I want to calculate the average ext price. I can use the query below:

SELECT AVG("ext price")
FROM sales;
┌───────────────────┐
│ avg("ext price")  │
│      double       │
├───────────────────┤
│ 570.1799399999999 │
└───────────────────┘

What if I wanted to answer the business question: What’s the average extended price by category? Answering this question involves performing two aggregations: AVG and SUM. It turns out that I can’t simply nest the two aggregations to achieve this. The query below fails to execute.

SELECT AVG(SUM("ext price"))
FROM sales
GROUP BY category;
Binder Error:
aggregate function calls cannot be nested

LINE 1: SELECT AVG(SUM("ext price"))
                   ^^^^^^^^^^^^^^^^

I need to break this computation into stages to answer the business question, and a subquery allows me to do that.

SELECT AVG("ext price")
FROM (
    SELECT SUM("ext price") AS "ext price"
    FROM sales
    GROUP BY category
);
┌────────────────────┐
│  avg("ext price")  │
│       double       │
├────────────────────┤
│ 190059.98000000007 │
└────────────────────┘

The subquery above first calculates the total extended price for each of the three categories: hats, sweaters, and socks. It then calculates the average of those three values. I nested the two queries, not the two aggregations. Do you now see how it’s a query within a query?

Uncorrelated subqueries

These are subqueries that can run independently of the outer query. The previous example is a good illustration. We can run each of the two queries contained in that example independently, and both would execute successfully. Here are two more examples of uncorrelated subqueries.

I’ll begin with a query that answers the business question: Find the sales for the most expensive SKU. A successful query will return all rows associated with the SKU that has the highest unit price.

SELECT *
FROM sales
WHERE sku = (
    SELECT arg_max(sku, "unit price")
    FROM sales
);
┌──────────┬──────────┬──────────┬────────────┬───────────┬─────────────────────┐
│   sku    │ category │ quantity │ unit price │ ext price │        date         │
│ varchar  │ varchar  │  int64   │   double   │  double   │      timestamp      │
├──────────┼──────────┼──────────┼────────────┼───────────┼─────────────────────┤
│ GS-95639 │ Socks    │       20 │      59.44 │    1188.8 │ 2014-08-01 13:55:31 │
│ GS-95639 │ Socks    │       16 │      99.07 │   1585.12 │ 2013-10-13 09:29:49 │
│ GS-95639 │ Socks    │        4 │      65.46 │    261.84 │ 2013-11-21 13:18:56 │
│ GS-95639 │ Socks    │       11 │      40.98 │    450.78 │ 2014-03-02 05:34:44 │
│ GS-95639 │ Socks    │       19 │      95.38 │   1812.22 │ 2014-08-17 00:36:11 │
│    ·     │   ·      │        · │        ·   │       ·   │          ·          │
│    ·     │   ·      │        · │        ·   │       ·   │          ·          │
│    ·     │   ·      │        · │        ·   │       ·   │          ·          │
│ GS-95639 │ Socks    │        6 │      45.64 │    273.84 │ 2013-12-22 02:07:55 │
│ GS-95639 │ Socks    │        2 │      92.63 │    185.26 │ 2014-03-08 19:34:49 │
│ GS-95639 │ Socks    │       19 │      99.87 │   1897.53 │ 2014-01-18 03:59:53 │
│ GS-95639 │ Socks    │        3 │      17.84 │     53.52 │ 2014-05-06 00:09:19 │
│ GS-95639 │ Socks    │        9 │      30.65 │    275.85 │ 2014-09-11 11:51:54 │
└──────────┴──────────┴──────────┴────────────┴───────────┴─────────────────────┘
  78 rows (10 shown)         use .last to show entire result          6 columns

Again, I’ll emphasize that the two queries can run independently of each other.

The next query answers the business question: Which order was placed most recently? A successful query will return the order placed on the latest date in the table.

SELECT *
FROM sales
WHERE date = (
    SELECT MAX(date)
    FROM sales
);
┌──────────┬──────────┬──────────┬────────────┬───────────┬─────────────────────┐
│   sku    │ category │ quantity │ unit price │ ext price │        date         │
│ varchar  │ varchar  │  int64   │   double   │  double   │      timestamp      │
├──────────┼──────────┼──────────┼────────────┼───────────┼─────────────────────┤
│ ZC-07383 │ Sweater  │       14 │      42.27 │    591.78 │ 2014-09-30 19:57:34 │
└──────────┴──────────┴──────────┴────────────┴───────────┴─────────────────────┘

The most recent order involved the purchase of 14 sweaters.

Correlated subqueries

In a correlated subquery, the inner query refers to a column from the outer query. For this reason, the two queries depend on each other to execute. I’ll now answer the following business question: Which orders outperform the average order value within their own category?

SELECT *
FROM sales s1
WHERE "ext price" > (
    SELECT AVG(s2."ext price")
    FROM sales s2
    WHERE s2.category = s1.category
);
┌──────────┬──────────┬──────────┬────────────┬───────────┬─────────────────────┐
│   sku    │ category │ quantity │ unit price │ ext price │        date         │
│ varchar  │ varchar  │  int64   │   double   │  double   │      timestamp      │
├──────────┼──────────┼──────────┼────────────┼───────────┼─────────────────────┤
│ ZC-07383 │ Sweater  │       12 │      60.24 │    722.88 │ 2014-09-17 17:26:22 │
│ RU-25060 │ Sweater  │       19 │      51.83 │    984.77 │ 2014-08-24 06:18:12 │
│ FT-50146 │ Sweater  │       14 │       68.2 │     954.8 │ 2013-12-04 13:53:26 │
│ HX-24728 │ Hat      │       16 │      52.99 │    847.84 │ 2014-02-07 14:53:59 │
│ FT-50146 │ Sweater  │       17 │      34.61 │    588.37 │ 2014-04-06 20:52:15 │
│    ·     │    ·     │        · │        ·   │       ·   │          ·          │
│    ·     │    ·     │        · │        ·   │       ·   │          ·          │
│    ·     │    ·     │        · │        ·   │       ·   │          ·          │
│ ZC-07383 │ Sweater  │       16 │      49.27 │    788.32 │ 2014-06-18 11:32:15 │
│ RU-25060 │ Sweater  │       16 │      36.89 │    590.24 │ 2014-07-12 15:39:23 │
│ IC-59308 │ Socks    │       18 │      54.79 │    986.22 │ 2014-03-10 08:11:59 │
│ RU-25060 │ Sweater  │       15 │      62.53 │    937.95 │ 2014-04-11 02:50:03 │
│ LK-02338 │ Sweater  │       11 │       86.4 │     950.4 │ 2014-02-14 20:10:42 │
└──────────┴──────────┴──────────┴────────────┴───────────┴─────────────────────┘
  403 rows (10 shown)         use .last to show entire result         6 columns

In the second example, I’ll answer the business question: Which orders fall below the median order value for their respective SKUs?

SELECT *
FROM sales s1
WHERE "ext price" < (
    SELECT MEDIAN(s2."ext price")
    FROM sales s2
    WHERE s2.sku = s1.sku
);
┌──────────┬──────────┬──────────┬────────────┬───────────┬─────────────────────┐
│   sku    │ category │ quantity │ unit price │ ext price │        date         │
│ varchar  │ varchar  │  int64   │   double   │  double   │      timestamp      │
├──────────┼──────────┼──────────┼────────────┼───────────┼─────────────────────┤
│ HX-24728 │ Hat      │        1 │      98.98 │     98.98 │ 2014-09-28 11:56:02 │
│ LK-02338 │ Sweater  │        9 │       34.8 │     313.2 │ 2014-04-24 16:51:22 │
│ QS-76400 │ Sweater  │        5 │      15.25 │     76.25 │ 2014-01-30 07:34:02 │
│ FT-50146 │ Sweater  │        4 │      18.51 │     74.04 │ 2014-09-05 07:24:23 │
│ AE-95093 │ Socks    │        4 │      49.95 │     199.8 │ 2014-04-28 21:51:24 │
│    ·     │   ·      │        · │        ·   │       ·   │          ·          │
│    ·     │   ·      │        · │        ·   │       ·   │          ·          │
│    ·     │   ·      │        · │        ·   │       ·   │          ·          │
│ RU-25060 │ Sweater  │       11 │      36.65 │    403.15 │ 2013-12-05 20:13:34 │
│ IC-59308 │ Socks    │       20 │      20.58 │     411.6 │ 2013-11-21 03:13:13 │
│ GS-95639 │ Socks    │        9 │      30.65 │    275.85 │ 2014-09-11 11:51:54 │
│ HX-24728 │ Hat      │        3 │      69.58 │    208.74 │ 2014-06-05 14:29:25 │
│ FT-50146 │ Sweater  │        2 │      46.48 │     92.96 │ 2014-08-10 16:20:32 │
└──────────┴──────────┴──────────┴────────────┴───────────┴─────────────────────┘
  497 rows (10 shown)         use .last to show entire result         6 columns

What to remember

The key difference between correlated and uncorrelated subqueries is independence. An uncorrelated subquery can run on its own and returns a value or set of values that the outer query uses for filtering. A correlated subquery, on the other hand, depends on the current row being evaluated by the outer query. This is why it references columns from the outer query within the subquery.

When reading a query, a simple test is to ask yourself: Can the subquery be executed by itself? If the answer is yes, it is uncorrelated. If it relies on an outer table alias, such as s1.category or s1.sku, it is correlated.