How can I use a scalar subquery to show a related summary beside each row?
Quick answer
In SQLite, put a one-column subquery in the SELECT list, then refer to the current outer row inside the subquery’s WHERE clause. For example, match each product’s category to other products’ categories and calculate AVG(price). The subquery is correlated because it uses the outer product’s category, so the comparison value varies by category. This example describes SQLite behavior, not every database.
The question, the details, the next step.
A practical checklist
Give the outer table a clear alias, such as
p, and use a different alias such asp2inside the subquery.Select the product columns and scalar subquery value together in the outer SELECT list.
Match the intended grouping field in the subquery’s WHERE clause, such as
p2.category = p.category.Use a one-column subquery and name its result with a helpful alias such as
category_avg.Check a small hand-calculated example and consider what
NULLwould mean if the subquery returns no rows.
A few more useful answers
Why is this called a correlated subquery?
It refers to an outer-query column—in this example, p.category—so its result depends on the current outer product row.
Does this query guarantee good performance?
No. The cited SQLite description explains semantics, not performance guarantees. Check the query with your actual data and SQLite setup.
Can I use this exact query in every database?
The example and cited behavior are specifically for SQLite. Other database systems may differ, so check the documentation for the system you use.
Sources
References used for this guide.
- [S1] SQLite SQL Language Expressions: Scalar and Correlated Subqueries sqlite.org · Checked
