Sub topic 6
What a grouped query may select
This chapter assumes you can write basic SELECT, WHERE and ORDER BY queries. It also assumes you know how GROUP BY forms groups and how aggregates such as SUM and COUNT behave. Here the question is narrower: once a query has a GROUP BY, which expressions may appear in the SELECT list, and why?
The rule
After GROUP BY, the query returns one row per group. A single output row cannot hold several different values in one column. So every expression in the SELECT list must have exactly one value per group. That is true in two cases:
- The expression is an aggregate function, such as
SUM(amount). It reduces all rows in the group to one value. - The expression depends only on the grouping columns. Every row in a group has the same value for those columns, so the value is well defined.
A bare column that is in neither category is not allowed. Within a group it can take several values, and the database has no rule for choosing one.
The examples use this orders table:
| order_id | customer_id | status | amount | shipped_at |
|---|---|---|---|---|
| 1 | 10 | paid | 400 | 2026-01-03 |
| 2 | 10 | paid | 700 | 2026-01-05 |
| 3 | 10 | refunded | 150 | NULL |
| 4 | 20 | paid | 90 | 2026-01-04 |
A valid grouped query
SELECT customer_id,
COUNT(*) AS order_count,
SUM(amount) AS total_amount
FROM orders
GROUP BY customer_id;The query returns two rows, one for customer 10 and one for customer 20.
customer_idis a grouping column, so it has one value per group.COUNT(*)andSUM(amount)are aggregates, so each reduces its group to one value.
An invalid grouped query
SELECT customer_id,
status,
SUM(amount) AS total_amount
FROM orders
GROUP BY customer_id;This query fails in PostgreSQL, SQL Server, Oracle and MySQL with ONLY_FULL_GROUP_BY enabled. PostgreSQL reports that status must appear in the GROUP BY clause or be used in an aggregate function.
Customer 10 has the statuses paid and refunded. The query asks for one status next to one total, and nothing says which status to use.
Three ways to fix it
Which fix is right depends on what you meant to ask.
- Add the column to
GROUP BY. You get one row per customer and status. The totals now describe smaller groups. - Aggregate the column. Use
MAX(status), orCOUNT(DISTINCT status)if you want to know how many statuses there are. This keeps one row per customer. - Remove the column from
SELECT. Do this if you did not need it.
SELECT customer_id,
status,
SUM(amount) AS total_amount
FROM orders
GROUP BY customer_id, status;SELECT customer_id,
COUNT(DISTINCT status) AS status_count,
SUM(amount) AS total_amount
FROM orders
GROUP BY customer_id;Do not choose a fix only to make the error go away. Adding status to GROUP BY changes the meaning of the result. The aggregate fix keeps the meaning but loses the individual values.
Expressions built from grouping columns
The rule applies to expressions, not only to bare column names. Any expression computed from grouping columns and constants is valid, because it has one value per group.
SELECT customer_id,
UPPER(CAST(customer_id AS VARCHAR(10))) AS customer_label,
customer_id * 100 AS scaled_id,
SUM(amount) AS total_amount,
SUM(amount) / COUNT(*) AS manual_average
FROM orders
GROUP BY customer_id;customer_labelandscaled_iduse onlycustomer_id.manual_averagecombines two aggregates. You can do arithmetic on aggregate results, and you can nest scalar functions around them, for exampleROUND(AVG(amount), 2).
You cannot nest one aggregate directly inside another, as in SUM(COUNT(*)). Most databases reject it. PostgreSQL, for example, reports that aggregate function calls cannot be nested. To aggregate an aggregate, use a subquery or a common table expression (CTE) that computes the first level. Oracle is an exception that allows a limited nested form when a GROUP BY is present, but you should not rely on it for portable code.
Constants and non-column expressions
Literals and functions with no column inputs are fine, because they have the same value for every row in the group.
SELECT customer_id,
'order summary' AS report_name,
COUNT(*) AS order_count
FROM orders
GROUP BY customer_id;Be careful with non-deterministic functions such as RANDOM() or NEWID(). They are allowed syntactically, but they produce a different value per evaluation, and the result varies between runs. Treat them as outside the rule and avoid them in grouped queries.
How grouping by an expression changes the rule
If you group by an expression, the select list may repeat that same expression. Whether a differently written expression is accepted depends on the database.
SELECT EXTRACT(YEAR FROM shipped_at) AS ship_year,
COUNT(*) AS order_count
FROM orders
GROUP BY EXTRACT(YEAR FROM shipped_at);Here the select expression matches the grouping expression exactly. Matching expressions are the safe case in every major database.
Writing a different expression that happens to be derived from the same column often works in the logic, but some databases cannot prove it. For example, grouping by EXTRACT(YEAR FROM shipped_at) and selecting EXTRACT(YEAR FROM shipped_at) + 1 is accepted by PostgreSQL, which recognizes the grouped subexpression inside the larger one. Other engines can be stricter about matching. Repeat the grouped expression exactly, or wrap the query in a subquery, when you want predictable behavior.
Some databases let you refer to a select alias or a column position in GROUP BY. PostgreSQL and MySQL allow GROUP BY ship_year or GROUP BY 1. SQL Server and Oracle do not accept an alias there. Positional references are fragile, because adding a column to the select list can silently change the grouping.
Functional dependence and the primary key exception
Some databases accept a bare column when it is functionally dependent on the grouping columns. A column is functionally dependent when the grouping columns determine its value uniquely. The usual case is a primary key.
SELECT c.customer_id,
c.name,
COUNT(o.order_id) AS order_count
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.customer_id
GROUP BY c.customer_id;If customer_id is the primary key of customers, then each customer has exactly one name. PostgreSQL accepts this query without c.name in the GROUP BY. MySQL with ONLY_FULL_GROUP_BY does the same when it can detect the dependency. SQL Server and Oracle require you to list c.name explicitly.
The portable form is to list every non-aggregated column:
GROUP BY c.customer_id, c.nameAdding a functionally dependent column costs nothing and does not change the groups. The portable form is the better habit.
The MySQL permissive mode
Older MySQL configurations, and MariaDB by default in some versions, allowed the invalid query shown earlier. With ONLY_FULL_GROUP_BY turned off, MySQL picks an arbitrary value from the group for the bare column, usually the value from the first row it meets.
SET SESSION sql_mode = (SELECT REPLACE(@@sql_mode, 'ONLY_FULL_GROUP_BY', ''));With that mode off, the query returns a status for each customer, but the value is not guaranteed and can change after an index is added or the plan changes. Nothing in the result tells you the value was arbitrary. Keep ONLY_FULL_GROUP_BY enabled. Current MySQL versions enable it by default.
Selecting the row that has the maximum value
A common request is "show each customer's largest order, including its order_id". A first attempt often fails the rule:
SELECT customer_id, MAX(amount) AS largest, order_id
FROM orders
GROUP BY customer_id;MAX(amount) is one value per customer, but order_id is not. Adding MIN(order_id) would run, but it returns the lowest id, which is not necessarily the id of the largest order. The two aggregates are computed independently and do not describe the same row.
GROUP BY cannot express "the row where the max occurs". Use a window function or a join back to the aggregate.
SELECT order_id, customer_id, amount
FROM (
SELECT order_id,
customer_id,
amount,
ROW_NUMBER() OVER (PARTITION BY customer_id
ORDER BY amount DESC) AS rn
FROM orders
) AS ranked
WHERE rn = 1;This returns one whole row per customer. Ties are broken by the database arbitrarily unless you add a second ORDER BY column. The later chapter on window functions covers this approach.
How the rule works inside the engine
The rule follows from the logical evaluation order: FROM, WHERE, GROUP BY, HAVING, then SELECT. By the time SELECT runs, the individual rows have been collapsed into groups. The select list sees each group as a single unit with its grouping values and the ability to compute aggregates over the rows it contains. The original per-row values of non-grouping columns are no longer addressable as single values.
Quick checklist
Before running a grouped query, check each item in the SELECT list.
| Item in SELECT | Allowed? | Reason |
|---|---|---|
| A column listed in `GROUP BY` | Yes | One value per group |
| An aggregate such as `SUM(x)` | Yes | Reduces the group to one value |
| An expression of grouping columns | Yes | One value per group |
| A literal constant | Yes | Same value everywhere |
| A bare column not in `GROUP BY` | No, with exceptions | Several values per group |
| A column functionally dependent on a primary key in `GROUP BY` | Depends on the database | PostgreSQL and MySQL accept it, SQL Server and Oracle do not |
| An aggregate nested in an aggregate | No | Needs a subquery |
Exercise
A query is written as SELECT customerid, status, MAX(amount) FROM orders GROUP BY customerid; and fails with an error about status. Give two different corrections and say how each changes the result.
Show answer
First, add status to GROUP BY (GROUP BY customer_id, status). The result then has one row per customer and status, and MAX(amount) is the largest amount within each of those smaller groups. Second, aggregate status or drop it, for example COUNT(DISTINCT status) instead of status. The result keeps one row per customer, but you no longer see the individual status values. A third option is simply to remove status from the SELECT list if it was not needed.
Exercise
A colleague writes SELECT customerid, MAX(amount), orderid FROM orders GROUP BY customerid; and fixes the error by changing orderid to MIN(orderid). Why is the result misleading, and how would you get the orderid of each customer's largest order?
Show answer
MAX(amount) and MIN(orderid) are computed independently over the group, so the returned orderid is the lowest id for that customer, not necessarily the id of the order with the largest amount. GROUP BY cannot return the row where a maximum occurs. Use a window function such as ROWNUMBER() OVER (PARTITION BY customerid ORDER BY amount DESC) in a subquery and keep rows where the number is 1, or join the table back to a subquery that computes the per-customer maximum.