๐ฝ SQL ORDER BY Clause โ Sort Results in Ascending or Descending Order
๐งฒ Introduction โ Why Use ORDER BY?
In SQL, the ORDER BY
clause is used to sort the result set of a query by one or more columns. By default, sorting is ascending, but you can also specify descending order.
Whether you’re generating reports, displaying search results, or organizing large datasets, ORDER BY
helps you present data in a structured and meaningful way.
๐ฏ In this guide, youโll learn how to:
- Use
ORDER BY
with one or multiple columns - Sort data in ascending or descending order
- Combine
ORDER BY
withWHERE
,LIMIT
, and functions
โ 1. Basic ORDER BY Syntax
SELECT column1, column2
FROM table_name
ORDER BY column1;
โ
Sorts results based on column1
in ascending order (default).
๐ผ 2. Sort in Ascending (ASC) Order
SELECT name, salary
FROM employees
ORDER BY salary ASC;
โ Displays results with the lowest salary first.
๐ฝ 3. Sort in Descending (DESC) Order
SELECT name, salary
FROM employees
ORDER BY salary DESC;
โ Displays results with the highest salary first.
๐ 4. Sort by Multiple Columns
SELECT name, department, salary
FROM employees
ORDER BY department ASC, salary DESC;
โ Sorts first by department, then by salary within each department.
๐ง 5. ORDER BY with WHERE and LIMIT
SELECT name, age
FROM customers
WHERE country = 'USA'
ORDER BY age DESC
LIMIT 5;
โ Filters results, sorts them, then limits to top 5 oldest.
๐งฎ 6. ORDER BY with Expressions and Aliases
SELECT name, salary * 12 AS annual_salary
FROM employees
ORDER BY annual_salary DESC;
โ You can sort by calculated fields or column aliases.
๐ Best Practices
โ Do This | โ Avoid This |
---|---|
Use clear column names or aliases | Sorting by ambiguous positions |
Combine with WHERE and LIMIT | Sorting entire dataset unnecessarily |
Use proper indexes on sorted columns | Sorting on non-indexed large columns |
๐ Summary โ Recap & Next Steps
The ORDER BY
clause is crucial for organizing and presenting query results. It gives users control over the structure of the data output.
๐ Key Takeaways:
- Use
ORDER BY
to sort results by one or more columns - Default is ascending (
ASC
); useDESC
for descending - Works with aliases, expressions, and LIMIT
โ๏ธ Real-World Relevance:
Used in reporting dashboards, sorted product listings, leaderboards, and admin panels.
โก๏ธ Next up: Learn how to use GROUP BY to aggregate data by categories.
โ FAQ โ SQL ORDER BY Clause
โ What is the default sort order in SQL?
โ
Ascending (ASC
) is the default order.
โ Can I sort by multiple columns?
โ
Yes, separate them with commas in the ORDER BY
clause.
โ Can I sort by an alias or expression?
โ
Absolutely. Use calculated fields or aliases directly in ORDER BY
.
โ How do I get the top N rows in sorted order?
โ
Combine ORDER BY
with LIMIT
(MySQL/PostgreSQL) or TOP
(SQL Server).
โ Is ORDER BY slow on large tables?
โ
It can be. Indexing the columns used in ORDER BY
can improve performance.
Share Now :