GROUP BY and Aggregates
Cheat sheet · https://pcornel.dk/topic.php?topic=6197
Answer
GROUP BY groups rows and aggregate functions (COUNT, SUM, AVG, MIN, MAX) compute values per group; HAVING filters groups.
Remember
Every non-aggregated selected column must be in GROUP BY (strict modes). Filter rows with WHERE before grouping; filter groups with HAVING. COUNT(col) skips NULLs; COUNT(*) does not.
First checks
SELECT status, count(*) FROM orders GROUP BY status;— first check for this topicpsql -c "SELECT now(), version();"— PostgreSQL reachable and versionmysql -e "SELECT NOW(), VERSION();"— MariaDB/MySQL reachable and versionsqlcmd -S <server> -Q "SELECT @@VERSION"— SQL Server reachable and version
Verify in this order
FROM → WHERE → GROUP BY → aggregates → HAVING
Where it usually breaks
MySQL without ONLY_FULL_GROUP_BY returns arbitrary values for ungrouped columns.
Read-only verification commands unless stated otherwise. Confirm syntax for your platform and release. Full reference: https://pcornel.dk/topic.php?topic=6197