TMS TMS - 11 days ago 5
SQL Question

Does "group by" automatically guarantee "order by"?

Does "group by" clause automatically guarantee that the results will be ordered by that key? In other words, is it enough to write:

select *
from table
group by a, b, c


or does one have to write

select *
from table
group by a, b, c
order by a, b, c


I know e.g. in MySQL I don't have to, but I would like to know if I can rely on it accross the SQL implementations. Is it guaranteed?

Answer

group by does not order the data neccessarily. A DB is designed to grab the data as fast as possible and only sort if necessary.

So add the order by if you need a guaranteed order.