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 →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| order_id | customer_id | revenue | order_date | status |
|---|---|---|---|---|
| O2001 | C101 | 120.5 | 2024-03-05 | shipped |
| O2003 | C101 | 89.99 | 2024-03-05 | delivered |
| O2004 | C103 | 210.75 | 2024-03-06 | shipped |
| O2002 | C102 | 45.0 | 2024-03-07 | pending |
| O2005 | C102 | 45.0 | 2024-03-08 | delivered |
Step by step
- After SELECT, list the column names you want, separated by commas.
SELECT order_id, customer_id, revenue, order_date, status - FROM tells SQL which table to pull the data from.
SELECT order_id, customer_id, revenue, order_date, status FROM orders - 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
1. Using orders, write a query to show all rows sorted by revenue (smallest first).
SELECT * FROM orders ORDER BY revenue ASC2. Using products, write a query to show all rows sorted by price (smallest first).
SELECT * FROM products ORDER BY price ASC3. Using store_sales, write a query to show all rows sorted by revenue (smallest first).
SELECT * FROM store_sales ORDER BY revenue ASC4. Using reviews, write a query to show all rows sorted by rating (smallest first).
SELECT * FROM reviews ORDER BY rating ASC5. Using employees, write a query to show all rows sorted by salary (largest first).
SELECT * FROM employees ORDER BY salary DESCLearn 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 →