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.
• 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;
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 |
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!