SQL ORDER BY Clause

The ORDER BY clause in SQL is used to sort the result set of a query in ascending (ASC) or descending (DESC) order. By default, it sorts in ascending order.

📌 Syntax

SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC];

📊 Example Table: users

id | name    | age | city
---+---------+-----+---------
1  | Alice   | 22  | New York
2  | Bob     | 30  | London
3  | Charlie | 18  | Sydney
4  | Diana   | 27  | Toronto
5  | Ethan   | 35  | Paris

🔍 Example 1: Sort by Age Descending

SELECT * FROM users ORDER BY age DESC;

🔍 Example 2: Sort by Age Ascending

SELECT * FROM users ORDER BY age ASC;

🔍 Example 3: Sort by Multiple Columns

Sort first by city ascending, then by age descending:

SELECT * FROM users
ORDER BY city ASC, age DESC;

⚡ Best Practices

  • Always specify ASC or DESC explicitly for clarity.
  • Use ORDER BY on indexed columns for faster queries.
  • For large tables, avoid sorting unnecessary columns to improve performance.

📝 Summary

The ORDER BY clause allows you to control the order of query results. You can sort by single or multiple columns and choose ascending or descending order. It is often combined with WHERE, LIMIT, or JOIN for more advanced queries.

🚀 Next Steps

Next, we will learn about SQL GROUP BY and aggregation, which allow you to summarize data and calculate totals, averages, and counts.