Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 718
Tomas Avatar asked Jan 26 '15 12:01

Tomas


People also ask

Does GROUP BY guarantee order?

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.

Can I use GROUP BY without ORDER BY?

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.

Does ORDER BY work with 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.

Does order matter in GROUP 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.


1 Answers

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.

like image 152
juergen d Avatar answered Nov 04 '22 10:11

juergen d