Subqueries and Selecting One Row per Group
🎯 Introduction
By the end of this article, you will be able to find users by related records and select each author's article with the highest ID.
🔎 EXISTS checks only whether a match exists
This article uses two tables. The query_user user table:
| id | username | age | city | created_at |
|---|---|---|---|---|
| 1 | Xiao Ming | 25 | Beijing | 2026-10-01 09:00:00 |
| 2 | Xiao Hong | 30 | Shanghai | 2026-10-02 09:00:00 |
| 3 | Xiao Gang | 22 | Beijing | 2026-10-03 09:00:00 |
| 4 | Xiao Lin | 30 | Shanghai | 2026-10-04 09:00:00 |
| 5 | Xiao An | NULL | Hangzhou | 2026-10-05 09:00:00 |
The article_sample article table:
| id | user_id | title |
|---|---|---|
| 1 | 1 | Learning SQL |
| 2 | 1 | Understanding Queries |
| 3 | 2 | Database Notes |
article_sample.user_id corresponds to query_user.id. To initialize them, use the creation and insertion statements for user data and article data, respectively.
Finding users who have written articles does not require expanding every article into a result row:
SELECT u.id, u.username FROM query_user AS u
WHERE EXISTS (
SELECT 1 FROM article_sample AS a WHERE a.user_id = u.id
) ORDER BY u.id;
Query result:
| id | username |
|---|---|
| 1 | Xiao Ming |
| 2 | Xiao Hong |
Each person appears once. The query in parentheses is a subquery, a query used inside another query. EXISTS checks only whether at least one row is found. The value in SELECT 1 is not displayed.
Use NOT EXISTS to find people who have not written articles:
SELECT u.id, u.username FROM query_user AS u
WHERE NOT EXISTS (
SELECT 1 FROM article_sample AS a WHERE a.user_id = u.id
) ORDER BY u.id;
Query result:
| id | username |
|---|---|
| 3 | Xiao Gang |
| 4 | Xiao Lin |
| 5 | Xiao An |
When you only need to check existence, this expresses the intent more directly than expanding all articles and then removing duplicates.
📏 Use a query result as a comparison value
Find users older than the average of known ages:
SELECT username, age FROM query_user
WHERE age > (SELECT AVG(age) FROM query_user)
ORDER BY id;
Query result:
| username | age |
|---|---|
| Xiao Hong | 30 |
| Xiao Lin | 30 |
The average age is 26.75. The parenthesized query must return a single value here. A subquery returning multiple rows cannot be used directly in this comparison.
🏷 Name an intermediate result with WITH
First count each author's articles, then select authors with at least two:
WITH author_count AS (
SELECT user_id, COUNT(*) AS total
FROM article_sample GROUP BY user_id
)
SELECT user_id, total FROM author_count WHERE total >= 2;
Query result:
| user_id | total |
|---|---|
| 1 | 2 |
WITH defines author_count as a query result that can be referenced within this statement, not a permanent table. It makes the “aggregate, then filter” process easier to read. For a simple aggregation, HAVING is also sufficient.
🥇 Number each author's articles with ROW_NUMBER
To select each author's article with the highest id while retaining its title, first inspect the numbered rows:
SELECT user_id, id, title,
ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY id DESC) AS rn
FROM article_sample ORDER BY user_id, rn;
Query result:
| user_id | id | title | rn |
|---|---|---|---|
| 1 | 2 | Understanding Queries | 1 |
| 1 | 1 | Learning SQL | 2 |
| 2 | 3 | Database Notes | 1 |
ROW_NUMBER assigns row numbers. PARTITION BY user_id restarts numbering at 1 for each author, and ORDER BY id DESC puts articles with higher IDs first.
A function that calculates a result within a group for each row while preserving its details is called a window function. Unlike GROUP BY, it does not combine multiple articles into one row.
🎯 Keep row number 1 in the outer query
WITH ranked AS (
SELECT user_id, id, title,
ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY id DESC) AS rn
FROM article_sample
)
SELECT user_id, id, title FROM ranked WHERE rn = 1 ORDER BY user_id;
Query result:
| user_id | id | title |
|---|---|---|
| 1 | 2 | Understanding Queries |
| 2 | 3 | Database Notes |
The row numbers must be calculated before an outer WHERE can filter them. You cannot write WHERE rn = 1 at the same query level that calculates rn.
This example selects by id; it does not treat an auto-increment ID as an actual publication time. To select the most recently published article, sort by publication time and add id to break ties.
❓ Questions and Answers
Q1: Do I need a window function if I only need the article ID for each author, without its title?
Not necessarily. Grouping by user_id and calculating MAX(id) gives each author's highest article ID.
Q2: Does WITH store its result permanently?
No. The name is valid only within this statement. Design a separate table if you need permanent storage.
Q3: Are NOT IN and NOT EXISTS interchangeable?
No. If a NOT IN subquery contains NULL, results may differ from what you expect. NOT EXISTS usually expresses the absence of related records more clearly.
🧪 Exercise
Change rn = 1 to rn <= 2 to retrieve each author's two highest-ID articles. Check that Xiao Ming appears twice.
-- Write your SQL or record your verification results here
