Sorting and Limiting Results
ORDER BY and LIMIT
When you run a plain SELECT, the order the rows come back in is not something you should count on, it depends on how the database happens to store them. If the order matters to you, and it very often does, you need to ask for it directly with ORDER BY.
SELECT name, price FROM products ORDER BY price ASC;ASC means ascending, from lowest to highest, so this lists the cheapest product first. Swap it for DESC, meaning descending, to list the most expensive product first:
SELECT name, price FROM products ORDER BY price DESC;Limiting how many rows come back
Sometimes you do not want every matching row, only a handful, such as the newest 5 blog posts on a homepage. That is what LIMIT is for:
SELECT title FROM posts ORDER BY created_at DESC LIMIT 5;Read this from left to right: take every post, put the newest one first, then only keep the first 5. That single line is exactly the kind of query that powers a "latest posts" section on a real blog homepage.
Putting WHERE, ORDER BY, and LIMIT together
These clauses can all be combined in one query, and SQL expects them in a specific order: WHERE first, then ORDER BY, then LIMIT.
SELECT name, price FROM products WHERE category = 'shoes' ORDER BY price ASC LIMIT 3;This finds every shoe, sorts them from cheapest to most expensive, and keeps only the cheapest 3. That is a query you might genuinely use to build a "budget picks" section in an online shop.
Where you will see this in real websites
A blog homepage showing its newest articles, a shop showing its lowest priced items first, a leaderboard showing the top scoring players, all of these rely on ORDER BY and LIMIT working together.
Quick check
Q1 Which query lists the 3 cheapest products first?
Q2 What does DESC mean in an ORDER BY clause?
Want to save your progress? It's free.
Create a free account