Home > Back-end >  SQL - Use of ORDER BY on an already sorted table
SQL - Use of ORDER BY on an already sorted table

Time:07-11

This question is a curiosity about query performance.

I generated a table where I order the rows by a timestamp in a descending order with nulls trailing at the end.

ORDER BY time_updated DESC NULLS LAST

Now I have a query that will pull the latest change for an object using a different query that uses an ORDER BY.

Does having the second ORDER BY make the query redundant at all?

CodePudding user response:

There no such thing as a "sorted table".

This is because in relational databases, tables do not have inherent row ordering. You may have inserted the rows in a specific order, but that doesn't mean the engine stores them like that.

You need to explicitly add ORDER BY when querying the table, if you want to retrieve the rows with a specific ordering. Otherwise, the engine is free to return the rows in any order, and this order may change in the future without notice.

  • Related