JavaRanch Home    
 
This page:         last edited 23 March 2012         What's Changed?         Edit

Use ORDER BY in SQL statements   

Use ORDER BY where appropriate

Whenever you need to obtain rows in a sorted order from a database, use the ORDER BY clause. When you do not specify the order of rows, the database can return rows in any order it likes. This is true even when you use other constructs which seem to guarantee a specific order of the rows, eg. a GROUP BY. In some databases result of a GROUP BY might always appear sorted, in others this is not the case. Don't try your luck, use ORDER BY whenever you need your rows sorted.

Failing to explicitly sort rows can lead to all kinds of errors, as discussed here.

It is also worth to note that rows in a database table do not have any intrinsic order. Questions like which row is the first/last in a table do not have any meaningful answer. Though sometimes the rows seem to be stored in a table in the order in which they were added, once you start to mix insert, update and delete statements on the table, the apparent order of the rows may change.

See also this thread.


SqlBestPractices

JavaRanchContact us — Copyright © 1998-2014 Paul Wheaton