MySQL Order By
ORDER BY sorts database results.
What is it?
ORDER BY sorts database results.
Why do we use it?
Sorting makes tables and reports easier to use.
How does it work?
MySQL sorts the selected rows using one or more columns.
Syntax
SELECT * FROM students ORDER BY name ASC;
Example
<?php
$conn = new mysqli("localhost", "root", "", "aifa_php_lab");
$result = $conn->query("SELECT id,name,email FROM students ORDER BY name ASC");
while ($row = $result->fetch_assoc()) {
echo htmlspecialchars($row['name']) . "<br>";
}
?>
Example Explained
More Examples
Use ORDER BY id DESC to display newest records first.
⚠️ Important Rules
ASC means ascending and DESC means descending.
❌ Common Mistakes
Using a user-provided column name directly without controlling allowed values.
🌍 Real-World Use
Admin tables, rankings and reports.
📝 Practice Exercise
Create a student list sorted by name and ID.
💻 Try It Yourself
Write and run this PHP lesson inside the AIFA Coding Lab.