3.1 — Sorting with ORDER BY
What You'll Learn
- How to sort data in SQL using
ORDER BY
- Sorting ascending and descending
- Excel sorting vs. SQL sorting
From Excel to SQL: Sorting Data
In Excel, you click a column header to sort your data. In SQL, you use the ORDER BY
clause.
Excel:
Sort the "Amount" column from largest to smallest.
SQL:
sql
SELECT * FROM sales
ORDER BY Amount DESC;
ORDER BY Amount
sorts by the Amount column.DESC
means descending (largest to smallest). UseASC
for ascending (default).
Sorting by Multiple Columns
You can sort by more than one column, just like Excel’s custom sort.
sql
SELECT * FROM sales
ORDER BY Product ASC, Amount DESC;
- First sorts by Product (A-Z), then by Amount (largest to smallest) within each product.
Key Points
- Use
ORDER BY
to sort results. - Add
ASC
(ascending) orDESC
(descending) as needed. - Multiple columns can be sorted in order.
Next Steps
Next, you’ll learn how to limit the number of results—just like scrolling through a few rows in Excel.