SQL ORDER BY: Ascending, Descending & Multi-Column Sorting

In relational database theory, tables are unordered collections of rows. When you execute a SELECT without an ordering specification, the database returns rows in whatever sequence it found them on disk. To produce reliable, human-readable reports, use the ORDER BY clause to sort query results in Ascending (ASC) or Descending (DESC) order.


1. Single-Column Sorting (ASC & DESC)

• ASC (Ascending): The default sorting direction (numbers 0 to 9, letters A to Z, dates earliest to latest).

• DESC (Descending): Inverted sorting direction (highest numbers first, Z to A, most recent dates first).

-- Sort students from highest GPA to lowest (Descending)
SELECT student_id, first_name, gpa
FROM students
ORDER BY gpa DESC;

2. Multi-Column Sorting (Tie-Breaking)

When sorting large datasets, multiple records frequently share identical values in the primary sorting column. You can specify a secondary (and tertiary) tie-breaking column:

-- Sort primarily by Course alphabetically (A to Z), 
-- then break ties by GPA from highest to lowest (DESC)
SELECT student_id, first_name, course, gpa
FROM students
ORDER BY course ASC, gpa DESC;
student_id first_name course gpa
2 Pooja B.Tech 3.92
3 Aman BCA 3.85
1 Rahul BCA 3.75
4 Neha MCA 3.68

3. Sorting by Expressions & Aliases

Because ORDER BY executes after SELECT, you can sort by calculated aliases or length functions:

-- Sort students by name length
SELECT first_name, LENGTH(first_name) AS name_len
FROM students
ORDER BY name_len DESC;

Next, let us learn how to paginate results using SQL LIMIT & OFFSET!

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!