MySQL — Order By
Basic ORDER BY
-- Ascending order (default)
SELECT * FROM users ORDER BY name ASC;
-- Descending order
SELECT * FROM users ORDER BY name DESC;
ORDER BY Multiple Columns
SELECT * FROM users
ORDER BY age DESC, name ASC;
ORDER BY Examples
-- Sort by date
SELECT * FROM orders
ORDER BY created_at DESC;
-- Sort by multiple columns
SELECT * FROM products
ORDER BY category ASC, price DESC;
-- Sort by expression
SELECT name, price * stock AS value
FROM products
ORDER BY value DESC;
-- Sort with LIMIT
SELECT * FROM products
ORDER BY price DESC
LIMIT 10;
ORDER BY with Functions
-- Sort by string length
SELECT * FROM users
ORDER BY LENGTH(name) DESC;
-- Sort by date part
SELECT * FROM users
ORDER BY MONTH(created_at), DAY(created_at);
Mini Practice
Write MySQL code that:
- Sorts by name ascending
- Sorts by date descending
- Sorts by multiple columns
- Combines with LIMIT
Up Next
Next: Learn about Grouping Data.
Related Topics
Frequently Asked Questions about Order By
What is Order By in MySQL?
Order By is a fundamental concept in MySQL. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Order By?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Order By.
Why is Order By important in MySQL?
Order By is essential for MySQL development. Understanding this concept will help you write better code and solve real-world problems more effectively.