Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do databases implement SQL 'ORDER BY x'?

I'm wondering how these work under the hood, especially for large result sets. For example, would the DB likely write the raw result to disk and then do an external sort?

I'm also wondering how this works with LIMIT...OFFSET. If the DB can't utilize an existing index it seems like the DB would have to sort the whole thing and pluck the subset of the raw result set.

like image 516
seand Avatar asked Aug 10 '11 17:08

seand


People also ask

How does ORDER BY in SQL work?

The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

How do you use ORDER BY in Microsoft SQL?

ORDER BY is usually the last item in an SQL statement. You can include additional fields in the ORDER BY clause. Records are sorted first by the first field listed after ORDER BY. Records that have equal values in that field are then sorted by the value in the second field listed, and so on.

How do you write a query for ORDER BY?

Syntax. SELECT column-list FROM table_name [WHERE condition] [ORDER BY column1, column2, .. columnN] [ASC | DESC]; You can use more than one column in the ORDER BY clause.

Does SQL automatically order?

We learned that SQL Server doesn't guarantee any order of the results stored in the table, nor in the results set returned from your queries, but we can sort the output by using the order by clause.


2 Answers

Indexes are ordered; if there's a suitable index, that will be used. Otherwise, they'll need to sort, as you suppose. The execution plan for a query (which you can get with e.g. EXPLAIN or via client menus; the exact method of getting it varies with the DBMS) may contain hints as to how a query will be sorted.

See:

  1. MySQL: ORDER BY Optimization
  2. PostgreSQL: Indexes and ORDER BY
  3. SQL Server Indexes
  4. Oracle: Understanding Indexes
like image 134
outis Avatar answered Nov 05 '22 18:11

outis


mySQL shows their own Order By optimization on this link

Oracle shows theor own Order By algorithm procedure here

Basically, If you have an index, it is ordered. But when you don't sorting occurs which is O(n log n)

like image 21
Saher Ahwal Avatar answered Nov 05 '22 20:11

Saher Ahwal