BBampaa

Lessons › SQL › Chapter 1: Reading data

SQL lesson

ORDER BY with single column and multiple columns

ORDER BY sorts query results by one or more columns - smallest to largest, oldest to newest, A to Z, or reversed.

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

Example

Sorting Retail Orders with ORDER BY

SELECT order_id, customer_id, revenue, order_date, status
FROM orders
ORDER BY order_date ASC, revenue DESC

Result:

order_idcustomer_idrevenueorder_datestatus
O2001C101120.52024-03-05shipped
O2003C10189.992024-03-05delivered
O2004C103210.752024-03-06shipped
O2002C10245.02024-03-07pending
O2005C10245.02024-03-08delivered

Step by step

  1. After SELECT, list the column names you want, separated by commas.
    SELECT order_id, customer_id, revenue, order_date, status
  2. FROM tells SQL which table to pull the data from.
    SELECT order_id, customer_id, revenue, order_date, status
    FROM orders
  3. ORDER BY puts the rows in your chosen order.
    SELECT order_id, customer_id, revenue, order_date, status
    FROM orders
    ORDER BY order_date ASC, 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
5. Using employees, write a query to show all rows sorted by salary (largest first).
SELECT * FROM employees ORDER BY salary DESC

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