Search code examples
sqlsqlitegroup-by

What row gets selected when you GROUP BY without aggregate function?


When I use GROUP BY and don't give a column an aggregate function it doesn't give an error, so what is it supposed to do? From my experimentation it selects the last row from the data set:

select A, AVG(B), C from table group by C

A
1
2
3
4

Then it will return:

A AVG(B) C
4 4.3 a

Solution

  • Standard SQL does not allow this.

    SQLite (and MySQL) just give the value from some random record in the group. (It happens to be the last one in this case because of the way the computation is implemented.)

    SQLite (beginning with version 3.7.11) guarantees that when you use MIN or MAX, such unaggregated values come from the a record that matches the MIN/MAX.