Querying DataCore· 25 min read

ORDER BY & LIMIT

Sort results and limit how many come back — the basis of “top 10” and “latest” lists.

What you will learn

  • Sort with ORDER BY
  • Limit results with LIMIT

ORDER BY and LIMIT

By default rows come back in no particular order. ORDER BY sorts the result by a column, and LIMIT caps how many rows you get. Together they power features like “top 5 sellers” or “10 latest posts”. You add them to the end of a SELECT: SELECT ... ORDER BY column DIRECTION LIMIT n.

ORDER BY (ASC/DESC) and LIMIT
SELECT * FROM users ORDER BY age DESC;     -- oldest first
SELECT * FROM users ORDER BY name ASC;     -- A to Z

SELECT * FROM products ORDER BY price DESC LIMIT 5;  -- top 5 dearest

Line by line: ORDER BY age DESC sorts by age descending (largest first), so the oldest user is on top. ORDER BY name ASC sorts by name ascending (A to Z). The last query does both jobs — it sorts products by price highest-first and then LIMIT 5 keeps only the first five rows, giving you the 5 most expensive products.

Note: Output (for ORDER BY age DESC with our 3 users): Ravi 25 Meera 23 Asha 22 The rows are the same data as before, just reordered so the highest age comes first. DESC = high to low; ASC = low to high.

Tip: Combine them for real features: ORDER BY created_at DESC LIMIT 10 = “the 10 newest records”. ASC is ascending (default), DESC is descending.

Q. How do you get the 5 most expensive products?

Answer: ORDER BY price DESC sorts highest first; LIMIT 5 returns the first five.

✍️ Practice

  1. Sort users by age, oldest first.
  2. Get the 3 newest products.

🏠 Homework

  1. List the 5 cheapest in-stock products.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →