Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: What is the default Order By of queries?

Tags:

mysql

What is the default order of a query when no ORDER BY is used?

like image 828
Vijayan Avatar asked Jan 05 '12 17:01

Vijayan


People also ask

Which is the correct order for an SQL query?

The correct answer is Select, where, group by, having.

What is the default order of ORDER BY?

In SQL, what is the default sort order of the Order By clause? By default, the order by statement will sort in ascending order if no order (whether ascending or descending) is explicitly specified.

Which is the default ordering if ORDER BY is not provided in select statement?

MySQL by default seems to order by the record structure on disk, (which can include out-of-sequence entries due to deletions and optimisations) but it often initially fools developers into not bother using order-by clauses because the data appears to default to primary-key ordering, which is not the case!

What is the default ordering of rows returned from a select query?

When you issue a SELECT , the rows often get returned in the same order they were inserted in the table. You can change the order of the rows by adding an ORDER BY clause at the end of your query, with a column name after. By default, the ordering will be in "ascending order", from lowest value to highest value.


2 Answers

There is no such order present. Taken from http://forums.mysql.com/read.php?21,239471,239688#msg-239688

  • Do not depend on order when ORDER BY is missing.

  • Always specify ORDER BY if you want a particular order -- in some situations the engine can eliminate the ORDER BY because of how it does some other step.

  • GROUP BY forces ORDER BY. (This is a violation of the standard. It can be avoided by using ORDER BY NULL.)

SELECT * FROM tbl -- this will do a "table scan". If the table has never had any DELETEs/REPLACEs/UPDATEs, the records will happen to be in the insertion order, hence what you observed.

If you had done the same statement with an InnoDB table, they would have been delivered in PRIMARY KEY order, not INSERT order. Again, this is an artifact of the underlying implementation, not something to depend on.

like image 95
Rahul Avatar answered Oct 02 '22 14:10

Rahul


There's none. Depending on what you query and how your query was optimised, you can get any order. There's even no guarantee that two queries which look the same will return results in the same order: if you don't specify it, you cannot rely on it.

like image 34
alf Avatar answered Oct 02 '22 14:10

alf