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?
Yes, the ORDER BY is necessary, unless you don't actually care about the order. Just because you observe some type of sorting does not make it guaranteed.
The Group By clause is used to group data based on the same value in a specific column. The ORDER BY clause, on the other hand, sorts the result and shows it in ascending or descending order. It is mandatory to use the aggregate function to use the Group By.
When combining the Group By and Order By clauses, it is important to bear in mind that, in terms of placement within a SELECT statement: The GROUP BY clause is placed after the WHERE clause. The GROUP BY clause is placed before the ORDER BY clause.
No, the order doesn't matter for the GROUP BY clause. MySQL and SQLite are the only databases I'm aware of that allow you to select columns which are omitted from the group by (non-standard, not portable) but the order doesn't matter there either.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With