Grouping, Aggregation, and Counting Rules

Calculate counts and averages and distinguish filtering records from filtering aggregate results

🎯 Introduction

By the end of this article, you will be able to calculate counts and averages and distinguish filtering records from filtering aggregate results.


🔢 Does COUNT count rows or supplied values?

This article uses the following original query_user dataset. Xiao An's age is NULL, meaning it was not provided. All counts and averages below use these five rows.

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

If you need to create this table, use the creation and insertion statements in Query practice data. First, compare two ways of counting:

SELECT COUNT(*) AS total, COUNT(age) AS age_count FROM query_user;

Query result:

totalage_count
54

COUNT(*) counts records; COUNT(age) counts only records whose age is not NULL. Counting users and counting users who supplied an age are different operations.


➗ AVG ignores missing values

SELECT AVG(age) AS average_age FROM query_user;

Query result:

average_age
26.75

The number of displayed decimal places may vary. The calculation uses the four supplied ages: (25 + 30 + 22 + 30) ÷ 4. An unknown age is not treated as 0.

SUM(age) also ignores NULL and adds the known ages, producing 107 here. With no matching rows, SUM and AVG return NULL, whereas COUNT returns 0. The application must handle these values according to what the statistic represents.


🏙 Aggregate each city with GROUP BY

SELECT city, COUNT(*) AS user_count
FROM query_user GROUP BY city ORDER BY user_count DESC, city;

Query result:

cityuser_count
Beijing2
Shanghai2
Hangzhou1

Each city becomes one row, and user_count is the number of records in that group. Ties are sorted by city; the collation determines the comparison order for city names.

GROUP BY combines multiple rows into a group, so you cannot arbitrarily include username in the result: a city has multiple names, and the database cannot decide which one you intend to display. If you need individual users, do not merge them into groups.


🔍 WHERE selects records before aggregation

Count only users who are at least 25:

SELECT city, COUNT(*) AS user_count FROM query_user
WHERE age >= 25 GROUP BY city ORDER BY city;

Query result:

cityuser_count
Beijing1
Shanghai2

Hangzhou has no matching records and is absent from the result. WHERE filters the original records before grouping.


🧮 HAVING filters aggregate results

Find cities with at least two users:

SELECT city, COUNT(*) AS user_count FROM query_user
GROUP BY city HAVING COUNT(*) >= 2 ORDER BY city;

Query result:

cityuser_count
Beijing2
Shanghai2

HAVING checks the grouped results. COUNT(*) >= 2 cannot go in WHERE because each group's count has not yet been calculated at that stage.


✅ Calculate two counts with conditional aggregation

Display the total user count and adult count in one result:

SELECT COUNT(*) AS total,
    SUM(CASE WHEN age >= 18 THEN 1 ELSE 0 END) AS adult_count
FROM query_user;

Query result:

totaladult_count
54

CASE contributes 1 for rows meeting the age condition and 0 for other rows; SUM adds them. Excluding unknown ages from the adult count does not mean those users are assumed to be minors.


❓ Questions and Answers

Q1: Is COUNT(1) more accurate than COUNT(*)?

Both count rows here. COUNT(*) expresses the intent to count records more directly.

Q2: Does COUNT(*) after joining articles give the number of users?

Not necessarily. Multiple articles by one user produce multiple rows. Deduplicate by user ID or aggregate the articles first. The joins article demonstrates this with actual results.

Q3: Can I disable grouping checks to display username?

Do not disable checks to hide an ambiguous query. First decide exactly which record each group should return.


🧪 Exercise

Calculate the average age by city, then keep only cities with at least two users who supplied an age. Expect Beijing and Shanghai.

-- Write your SQL or record your verification results here