SQL ORDER BY

Basic ORDER BY

SELECT name, age FROM students
ORDER BY age;

This sorts results by the age column in ascending order (default).

ASC and DESC

SELECT name, age FROM students
ORDER BY age DESC;

Add DESC to sort in descending order. Use ASC explicitly to clarify ascending order if needed.

Sorting by Multiple Columns

SELECT name, grade, age FROM students
ORDER BY grade DESC, age ASC;

This sorts by grade (descending) and then by age (ascending) within each grade.

Sorting by Column Position

SELECT name, age, grade FROM students
ORDER BY 2 DESC;

Here, 2 refers to the second column selected (age). This is less readable and not recommended.

Expressions in ORDER BY

SELECT name FROM users
ORDER BY LENGTH(name) ASC;

This orders results based on the length of the name.

ORDER BY with Aliases

SELECT name, score * 1.1 AS adjusted_score FROM students
ORDER BY adjusted_score DESC;

You can sort by an alias defined in the SELECT clause.

Best Practices

  • Always use ORDER BY to get consistent output
  • Prefer column names or aliases for readability
  • Avoid numeric positions unless absolutely necessary

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic