๐ŸŽ“ A1Learner
๐Ÿ”
0 of 43 lessons completed

SQL Order By

ORDER BY is the part of a query that sorts the rows of the result. The rows come back in the order the sort names.

Sort by name

This query sorts the customers by name. The names come back in alphabet order.

SELECT name FROM customers ORDER BY name;

Sort in reverse

DESC flips the sort. The highest price comes first and the lowest price comes last.

SELECT name, price FROM products ORDER BY price DESC;

A second key breaks ties

The first key sorts by category, and three categories hold two products each. The second key sorts by price inside each category, dearest first.

SELECT name, category, price FROM products ORDER BY category, price DESC;

Example

SELECT name, price FROM products ORDER BY price;

Key points

  • ORDER BY: the keyword pair that sorts a result
  • ASC: the sort direction that runs from smallest to largest
  • DESC: the sort direction that runs from largest to smallest
  • A sort with no direction named runs as ASC.
  • ORDER BY comes after WHERE in a query.
  • A second sort key breaks the ties the first key leaves.
  • Without ORDER BY, the engine returns rows in its own order, and that order is not promised.

In this example, ORDER BY sorts the products by price. No direction is named, so the sort runs as ASC. The cheapest product comes first and the dearest comes last.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท DB Fiddle

Exercise

What does ORDER BY price DESC do?