QamoosTech
DatabasesQueryingIntermediateSQL

GROUP BY

PronunciationGROOP BY

Definition

GROUP BY splits the rows of a query into groups that share a value, so that an aggregate such as a sum or a count is calculated for each group.

Where you hear it

In reporting queries such as "total per week", in SQL interviews, and in ORM code that groups values.

Examples

  • Group by week to get the amount collected in each one.
  • Use HAVING to filter groups after the grouping.
  • Grouping the payments by country gives one total for each country.

Common mistake

Selecting a column that is neither grouped nor aggregated. The database cannot know which row's value to show.

Don't confuse with

ORDER BY, which only sorts the rows. GROUP BY changes how many rows come back.

Say it at work

  • In a meeting or chatGroup by member and sum the amounts.
  • In an email or ticketFilter the groups with HAVING, not WHERE.