Comments - Why is ORDER BY in a FROM Subquery Ignored?

 
5 years, 3 months ago Stevie Robb

I am not sure if this is expected behaviour or not, but using GROUP BY in the subquery seems to force the overall query to accept the ORDER BY clause in the subquery.

Is this correct behaviour?

 
3 years, 10 months ago Michael Widenius

An effect of some of the GROUP BY algorithms (sorting and collecting rows) will create a table where the rows happens to be in order. It's however not guaranteed according to the SQL standard

 
5 years, 6 months ago Darren Lines

Personally, I do see this as a bug, as the subquery is creating a result set, not a table, to a set of specified requirements; one requirement being an order, therefore it should be treated as ordered. This totally screws up previously working code that attempts to group based on the results of the ordered subquery. You cannot sort before grouping on the top level SELECT!

The limit hack seems to work, but must have a performance hit, so thanks @rspadim

 
3 years, 10 months ago Michael Widenius

The LIMIT clause will not have any performance hit as the extra 'limit' row counting is neglectable compared to doing the full ORDER BY.

 
10 years, 8 months ago Federico Razzoli

@rspadim That's true, and I understand that this can be a way to avoid refactoring bad code, which may take time. But creating an unnecessary temporary table doesn't seem a great solution to me.

 
11 years ago roberto spadim

an 'easy' workaround to this, is:

SELECT field1, field2 FROM (
SELECT field1, field2 FROM table1 
ORDER BY field2
LIMIT 18446744073709551615
) alias

this cause the optimizer to create a temporary table, and use filesort to order the query

the limit number is a 64bit unsigned -1 (2^64-1), this is a big number and can work with 99.999% of queries i know

 
7 years, 6 months ago Nicolas Tazzaz

@rspadim : Thank you for the workaround but on my biggest table, the time of execution increased since I tried. Do you have another idea ?

 
3 years, 10 months ago Michael Widenius

Higher execution time is expected if you force an ORDER BY on your biggest table.

 
Content reproduced on this site is the property of its respective owners, and this content is not reviewed in advance by MariaDB. The views, information and opinions expressed by this content do not necessarily represent those of MariaDB or any other party.