Aggregation & GROUP BY
Concept  ·  SQL & Querying

Selecting a column that isn't grouped or aggregated errors in strict engines, returns silent garbage in loose ones.

After grouping, one output row represents many input rows — a bare column is the question 'which of the many values?' with no answer. Strict engines refuse (the error is the lesson); MySQL's legacy mode and ANY_VALUE() answer 'whichever', the nondeterministic-latest bug in aggregation clothes. Three honest resolutions: group by it, aggregate it, or you actually wanted a window.

See it break
looms
millwoolkg
northmerino5
northalpaca3
southmerino4
The trap
SELECT
  mill,
  wool,
  SUM(kg) FROM
  looms
GROUP BY
  mill
ORDER BY
  mill;
The fix
SELECT
  mill,
  MAX(wool) AS heaviest,
  SUM(kg) AS kg
FROM
  looms
GROUP BY
  mill
ORDER BY
  mill;

Selecting the ungrouped 'wool' column raised a binder error — after grouping, one row stands for many looms, so a bare column has no single value; strict engines refuse, loose ones return silent garbage.

The rule

Group by it (part of the identity), aggregate it (MAX/MIN/STRING_AGG), or use a window (keep the rows) — chosen consciously.

Shows up elsewhere
PARTITION BY keeps rows; GROUP BY collapses'Latest' without a tiebreaker
Try one →Prove it in practice →