Sub topic 6
What a grouped query may select
Assume you know basic SELECT, WHERE, and ORDER BY syntax, understand tables and NULL, and have basic INNER JOIN and LEFT JOIN experience. This chapter focuses on one rule: after GROUP BY changes many input rows into one row per group, every selected value must make sense for that group.
The grouped result has one row per group
Suppose several orders belong to each customer:
SELECT customer_id,
COUNT(*) AS order_count,
SUM(amount) AS total_amount
FROM orders
GROUP BY customer_id;GROUP BY customer_id creates one group for each distinct customer_id. The query therefore returns one result row per customer. The selected expressions are valid because:
customer_ididentifies the group.COUNT(*)produces one value for the group.SUM(amount)produces one value for the group.
An aggregate function is a function that combines multiple input rows into one value. Common aggregate functions include COUNT, SUM, AVG, MIN, and MAX.
A selected column that is neither grouped nor aggregated would have no single value to return. For example:
SELECT customer_id,
order_date,
SUM(amount) AS total_amount
FROM orders
GROUP BY customer_id;If one customer has orders on several dates, which order_date should appear? SQL cannot choose a meaningful answer, so most database systems reject this query.
Grouping columns and aggregate expressions
You can group by more than one column. Each distinct combination becomes a separate group:
SELECT customer_id,
status,
COUNT(*) AS order_count
FROM orders
GROUP BY customer_id, status;A customer with both paid and pending orders receives separate rows. The group key is the pair (customer_id, status), not either column alone.
You can also group by an expression. The expression must be available for every row before aggregation:
SELECT EXTRACT(YEAR FROM order_date) AS order_year,
SUM(amount) AS yearly_total
FROM orders
GROUP BY EXTRACT(YEAR FROM order_date);Some systems allow the alias order_year in the GROUP BY; others do not. Repeating the expression is more portable.
Why arbitrary columns are unsafe
Consider this query:
SELECT customer_id,
status,
MAX(amount) AS largest_order
FROM orders
GROUP BY customer_id;MAX(amount) is well defined for each customer. status is not. The order with the largest amount might be paid, refunded, or pending, but this query does not ask SQL to find the status belonging to that largest order.
If you need the row containing the largest order, use a separate technique such as a window function:
SELECT order_id, customer_id, status, amount
FROM (
SELECT o.*,
ROW_NUMBER() OVER (
PARTITION BY customer_id
ORDER BY amount DESC, order_id
) AS row_number
FROM orders AS o
) AS ranked
WHERE row_number = 1;This asks for a complete order row, rather than pretending that MAX(amount) also selects the matching status.
Logical processing order
A useful model for a grouped query is:
WHERE filters individual rows before groups form. GROUP BY then creates groups. SELECT computes the output expressions for each group. This order explains why a non-grouped, non-aggregated column cannot be selected: the group may contain several different values.
Database systems differ in whether they permit a column that is functionally dependent on a grouped column, such as selecting a customer name when grouping by a unique customer ID. For portable SQL, include every non-aggregated selected column in GROUP BY, or aggregate it deliberately.
Exercise
Why is status invalid in a query that selects customer_id, status, and COUNT(*) but groups only by customer_id?
Show answer
One customer can have multiple statuses, so the group does not determine one status value. Add status to GROUP BY or choose an aggregate or another row-selection method.