GROUP BY clusters rows sharing the same values into summary rows so you can apply aggregate functions like COUNT, SUM, AVG, MIN, and MAX.
MariaDB’s GROUP BY lets you turn raw rows into summarized insights with just one clause.
GROUP BY partitions result-set rows that share identical values in one or more columns. Once grouped, aggregate functions can compute metrics such as total sales per customer or average order value per day.
Use GROUP BY whenever you need rolled-up numbers—totals, counts, averages, minimums, maximums—across logical buckets like customers, products, or dates.
The clause appears after FROM/WHERE and before ORDER BY or LIMIT. You list one or more grouping columns followed by optional HAVING to filter aggregated rows.
SELECT column1, aggregate_fn(col2)
FROM table
WHERE ...
GROUP BY column1 [, columnN]
HAVING aggregate_fn(col2) > value;
Query Orders and OrderItems to compute each customer’s spend.
SELECT c.id,
c.name,
SUM(oi.quantity * p.price) AS total_spent
FROM Customers c
JOIN Orders o ON o.customer_id = c.id
JOIN OrderItems oi ON oi.order_id = o.id
JOIN Products p ON p.id = oi.product_id
GROUP BY c.id, c.name
ORDER BY total_spent DESC;
Yes. HAVING acts like WHERE for aggregated data. For example, return only customers spending over $1,000.
... GROUP BY c.id HAVING SUM(oi.quantity * p.price) > 1000;
GROUP BY groups; ORDER BY sorts the final aggregated result. Always reference selected columns or aliases in ORDER BY to avoid ambiguity.
Index columns used in GROUP BY and JOIN predicates, avoid grouping unnecessary columns, and pre-filter rows with WHERE before grouping to shrink input data.
Non-aggregated column in SELECT that isn’t in GROUP BY. MariaDB rejects this unless ONLY_FULL_GROUP_BY is disabled. Fix by adding the column to GROUP BY or wrapping it in an aggregate.
Using HAVING for non-aggregated filters. HAVING runs after grouping and can slow queries. Move simple filters to WHERE whenever possible.
No. In MariaDB you must repeat the full expression or column name; aliases are resolved after GROUP BY.
MariaDB may internally sort, but the output order is not guaranteed. Use ORDER BY for deterministic ordering.
No; without GROUP BY the entire result set is treated as a single group.
Yes. Separate columns with commas to create composite groups, e.g., GROUP BY customer_id, product_id.
ROLLUP adds subtotal rows at increasing levels of aggregation, useful for multi-level reports.