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 →Example
Put rows in order
SELECT *
FROM orders
ORDER BY revenue DESC| order_id | customer_id | category | revenue | order_date |
|---|---|---|---|---|
| O2001 | C101 | Electronics | 299.99 | 2024-03-01 |
| O2005 | C102 | Clothing | 210.0 | 2024-03-05 |
| O2002 | C102 | Electronics | 149.5 | 2024-03-02 |
| O2004 | C103 | Electronics | 149.5 | 2024-03-04 |
| O2003 | C101 | Clothing | 89.0 | 2024-03-03 |
Step by step
- Sort by one column. DESC: biggest first. ASC, or nothing: smallest first.
SELECT * FROM orders ORDER BY revenue DESC - Sort by the first column, then by the second where the first ties.
SELECT * FROM orders ORDER BY category, 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 ASCLearn 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 →