Module 01 · lesson 6

ORDER BY: sorting the result

The founder wants to see the most expensive products on top — to understand where the store earns the most per unit.

Sorting the result

ORDER BY orders rows by the column you name. For example, from the smallest stock to the largest:

SELECT name, stock
FROM products
ORDER BY stock ASC;

The direction is set by a word after the column:

  • ASC — ascending (the default, you can omit it);
  • DESC — descending.

Several columns

You can sort by several columns separated by commas — first by the first, and on ties — by the second:

ORDER BY category ASC, price DESC

First it orders by category, and within each — from most to least expensive. ORDER BY always comes at the end of the query (before LIMIT, if there is one).

Your turn

The founder needs the most expensive products on top. Output name and price, sorted from most to least expensive.

Summary

  • ORDER BY orders the result; it's written at the end of the query.
  • ASC — ascending (the default), DESC — descending.