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!
No! Relational theory states that tables are unordered mathematical sets. Without an ORDER BY clause, the database engine returns rows in arbitrary physical disk order, which can change between query executions.
Yes! Unlike WHERE (which executes in Step 2), ORDER BY executes in Step 7, after SELECT (Step 5). Therefore, the database knows all column aliases defined in SELECT.
In MySQL, NULLs are treated as the lowest values (appearing first in ASC and last in DESC). In PostgreSQL and Oracle, you can explicitly control placement using NULLS FIRST or NULLS LAST.
Proceed to the next class in sequence to build production mastery of relational database architecture.
Continue to Class 20: LIMIT & OFFSET → Previous: ← Logical Operators | Full Syllabus
Selecting and renaming columns for sorted output.
Pairing ORDER BY with LIMIT for deterministic pagination.
Controlling how NULL values are sorted in result sets.
Eliminating expensive in-memory sort operations via B-tree order.