Subqueries and Selecting One Row per Group

Find users by related records and select each author's article with the highest ID

🎯 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:

idusernameagecitycreated_at
1Xiao Ming25Beijing2026-10-01 09:00:00
2Xiao Hong30Shanghai2026-10-02 09:00:00
3Xiao Gang22Beijing2026-10-03 09:00:00
4Xiao Lin30Shanghai2026-10-04 09:00:00
5Xiao AnNULLHangzhou2026-10-05 09:00:00

The article_sample article table:

iduser_idtitle
11Learning SQL
21Understanding Queries
32Database 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:

idusername
1Xiao Ming
2Xiao 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:

idusername
3Xiao Gang
4Xiao Lin
5Xiao 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:

usernameage
Xiao Hong30
Xiao Lin30

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_idtotal
12

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_ididtitlern
12Understanding Queries1
11Learning SQL2
23Database Notes1

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_ididtitle
12Understanding Queries
23Database 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