BBampaa

Lessons › SQL › Chapter 1: Reading data

SQL lesson

ORDER BY with single column and multiple columns

ORDER BY sorts the rows by a column. ASC is smallest first, and it's the default. DESC is biggest first. You can sort by a second column too. It decides the order when two rows tie on the first.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

Put rows in order

SELECT *
FROM orders
ORDER BY revenue DESC

Result:

order_idcustomer_idcategoryrevenueorder_date
O2001C101Electronics299.992024-03-01
O2005C102Clothing210.02024-03-05
O2002C102Electronics149.52024-03-02
O2004C103Electronics149.52024-03-04
O2003C101Clothing89.02024-03-03

Step by step

  1. Sort by one column. DESC: biggest first. ASC, or nothing: smallest first.
    SELECT * FROM orders ORDER BY revenue DESC
  2. Sort by the first column, then by the second where the first ties.
    SELECT * FROM orders ORDER BY category, revenue DESC

Practice

Try each one in your head first, then open the answer.

1. Using orders, write a query to show all rows sorted by revenue (smallest first).
SELECT * FROM orders ORDER BY revenue ASC
2. Using products, write a query to show all rows sorted by price (smallest first).
SELECT * FROM products ORDER BY price ASC
3. Using store_sales, write a query to show all rows sorted by revenue (smallest first).
SELECT * FROM store_sales ORDER BY revenue ASC
4. Using reviews, write a query to show all rows sorted by rating (smallest first).
SELECT * FROM reviews ORDER BY rating ASC

Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.

Try this lesson free →
About 5–10 minutes · no sign-up needed