Fun with subqueries in duckdb
Correlated and uncorrelated subqueries
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?
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.