SQL isn’t just about retrieving data—it’s also about controlling how that data is presented. That’s where ORDER BY
comes in. This clause lets you sort results by any column, whether you're working with text, numbers, or dates.
Examples of SQL ORDER BY
Here’s the base syntax:
SELECT column1, column2 FROM table ORDER BY column1 ASC | DESC;
Real-world examples:
1. Ranking scores from highest to lowest:
SELECT name, points FROM players ORDER BY points DESC;
2. Sorting names alphabetically:
SELECT name FROM players ORDER BY name;
3. Combining multiple sort keys:
SELECT first_name, salary FROM employees ORDER BY department, salary DESC;
4. Sorting by birthdate:
SELECT name, birthdate FROM players ORDER BY birthdate ASC;
You can also use column numbers:
ORDER BY 2 DESC;
This references the second column in the SELECT
list.
FAQ
Can SQL ORDER BY work with multiple columns?
Yes, you can sort using several columns in priority order.
How does it sort text values?
Alphabetically by default using ASC
. You can reverse the order with DESC
.
What impact does ORDER BY have on performance?
It can slow down queries, especially on large datasets. Indexing sort columns helps mitigate this.
Can I sort all data types?
Most, yes. Numbers, strings, and dates work. Binary or complex data types may not sort as expected.
Conclusion
The SQL ORDER BY
clause gives you clear control over how data is sorted and displayed. It’s flexible and works across most SQL dialects.
To see more examples and best practices, read the full guide: SQL ORDER BY Clause: Definitive Guide.
Top comments (0)