skipnothing/SQL

Aggregate Functions

Six rows sit in the orders table, four carrying a real amount and two left blank. Ask for the total, the average, the largest, and the engine hands back a single row of numbers, the whole column folded into one.

  • ▸Six orders go in, one number comes out, and without grouping the result is always exactly one row.
  • ▸The mean of 188.50 over four real amounts is 47.13, not the 31.42 from dividing by all six.
  • ▸Match no rows and the totals come back NULL, not zero.
BUILDS ON
01

Many rows in, one number out

The orders table has six rows. Four of them carry an amount: 42.00, 17.50, 99.00, and 30.00. Two are blank. Add the four amounts together and you get 188.50, a single number standing in for the whole column.

That is a different shape of query from anything so far. A WHERE filter keeps some rows and drops others, but the output is still rows of the same width. Here the output is not a smaller set of rows, it is one value: the column of amounts has been folded down to a single cell. The question stopped being "which rows?" and became "what is the one summary of these rows?"

The input is a whole column. The output is one row. That collapse, many values down to one, is the move this topic is built on.

TRY TO GET MORE THAN ONE ROW BACK

Keep going, sign up to unlock the rest

4 more parts in this topic, plus 30+ more topics in SQL.

Sign up, it's freeSee the full SQL