Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
In relational database theory, tables are defined as unordered mathematical sets. When you execute a basic SELECT query without an explicit sorting instruction, the database engine returns rows in arbitrary order (typically corresponding to the physical sequence of disk blocks or index order). To guarantee a predictable, deterministic sequence of records, you must use the ORDER BY clause.
ORDER BY ClauseThe ORDER BY clause is specified toward the end of your query (after FROM and WHERE):
ASC (Ascending): Smallest to largest (e.g., 1 to 100, A to Z, oldest date to newest). This is the default direction if omitted.DESC (Descending): Largest to smallest (e.g., 100 to 1, Z to A, newest date to oldest).Unlike the WHERE clause (which executes before SELECT), the ORDER BY clause executes AFTER SELECT in the logical query lifecycle. This means you can sort by column aliases defined in your SELECT statement!
When sorting character strings, the sorting order depends on the column's Collation:
utf8mb4_0900_ai_ci (case-insensitive), 'apple' and 'Apple' are considered identical in sort weight.utf8mb4_bin (binary), uppercase letters (ASCII 65-90) sort before lowercase letters (ASCII 97-122).ASC order, MySQL places NULL values at the top (treated as smaller than any value).DESC order, MySQL places NULL values at the bottom.ORDER BY. As soon as rows are updated, deleted, or indexes are rebuilt, unordered SELECT output order will change unpredictably.ASC nor DESC is explicitly specified in an ORDER BY clause?ORDER BY clause evaluated relative to the SELECT clause?NULL values when executing ORDER BY score DESC?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Handling NULL Values (IS NULL) | Multi-Column Sorting |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.