Topic 9 · Databases · 9.5

ORDER BY Explained Simply

ORDER BY sorts the records returned by an SQL query so the output appears in a clear order.

Invitation

What if the correct records are in the wrong order?

SELECT chooses the fields. FROM chooses the table. WHERE may filter the records.

ORDER BY then sorts the records in the output using one chosen field.

ORDER BY sorts the output.
How ORDER BY changes the output
81 · 65 · 90 · 72
ORDER BY Score
65 · 72 · 81 · 90
Big Idea

Read the query as one simple sentence

SQL QueryPlain English
SELECT Name, Score
FROM Students
ORDER BY Score;
SELECT Name, ScoreChoose the Name and Score fields.
FROM StudentsUse the Students table.
ORDER BY ScoreSort the output using Score.
OUTPUTShow the lowest score first.
Plain English: “Show me each name and score, sorted by score.”
How It Works

Keep the same three-step pattern

The learning map stays the same. ORDER BY only changes the order of the result.

1. DATABASEStudents table
2. QUERYSELECT Name, Score FROM Students ORDER BY Score
3. OUTPUTLowest score to highest
Database → Query → Sorted Output.
Worked Example

Follow the database, query and output

1. Database

StudentIDNameAgeScore
101Alice1581
102Ben1665
103Chen1590
104Dia1672

2. SQL Query

SQLSort
SELECT Name, Score
FROM Students
ORDER BY Score;

3. Output

NameScore
Ben65
Dia72
Alice81
Chen90
Notice: Only the order changes. The same four records are still returned.
Ascending and Descending

ORDER BY is ascending unless told otherwise

Ascending order

ORDER BY Score; 65 72 81 90

Lowest to highest. This is the default.

Descending order

ORDER BY Score DESC; 90 81 72 65

Highest to lowest.

ASC means ascending. DESC means descending.
Text Can Be Sorted Too

Names are sorted alphabetically

SQL QueryMeaning
SELECT Name
FROM Students
ORDER BY Name;

Query Meaning

Choose the Name field from Students and sort the names alphabetically.

Output

Alice
Ben
Chen
Dia
Numbers sort by value. Text sorts alphabetically.
Exam Tip

Sort only after finding the correct records and fields

1Find the selected fields.
2Apply any WHERE condition.
3Sort using ORDER BY.
Exam rule: ORDER BY sorts in ascending order unless DESC is included.
Common Mistake

Do not sort in the wrong direction

✗ Incorrect for ORDER BY Score

90 81 72 65

This is descending order.

✓ Correct output

65 72 81 90

Ascending order is the default.

Remember: Use DESC only when the question asks for highest-to-lowest or Z-to-A order.
Summary

One keyword, one clear job

ORDER BYSorts the output.
ASCLowest to highest or A to Z.
DESCHighest to lowest or Z to A.
Final rule: ORDER BY sorts the records returned by the query.