Beginner · Databases and SQL basics · topic 18 of 54 · 20 min
ORDER BY, LIMIT and DISTINCT
Explanation
Rows have no order until you ask
A database does not promise any order for the rows it returns. If you need "cheapest first" or "newest first", you must say so with ORDER BY. ASC means ascending (small to big, A to Z) and is the default. DESC means descending (big to small, Z to A).
SELECT name, price FROM products ORDER BY price DESC;Sorting by more than one column
You can sort by several columns. The database sorts by the first one, and only when two rows are equal there does it look at the second one.
SELECT name, category, price
FROM products
ORDER BY category ASC, price DESC;LIMIT and OFFSET: pages of results
LIMIT n keeps only the first n rows. OFFSET m skips the first m rows. Together they give pages: with 10 items per page, page 1 is LIMIT 10 OFFSET 0, page 2 is LIMIT 10 OFFSET 10, and page p is LIMIT 10 OFFSET (p - 1) * 10.
SELECT name, price FROM products
ORDER BY price ASC
LIMIT 3 OFFSET 3;DISTINCT and AS
DISTINCT removes repeated rows from the result. SELECT DISTINCT category FROM products lists each category once, even if fifty products share it. AS gives a column a new name in the result, called an alias, which makes the output easier to read.
SELECT DISTINCT category FROM products ORDER BY category;
SELECT name AS product, price AS price_in_rupees FROM products;Watch the lesson
ORDER BY, LIMIT and DISTINCT · 1/6
Today we sort results, cut them into pages, and remove repeats.
Prefer a video by a teacher? Find free videos on “sql order by limit offset distinct tutorial” on YouTube ↗
In real life: Search results in a shopping app
When you search "pressure cooker" in a shopping app and pick "Price: low to high", the backend runs a query with WHERE name LIKE '%cooker%' ORDER BY price ASC LIMIT 20 OFFSET 0. When you scroll down and the next batch loads, the app asks for OFFSET 20, then OFFSET 40. The phone never downloads all 5,000 cookers at once, only one page at a time.
Practice (0/3 done)
The products table has id, name, category, price and stock. Show the name and price of every product, the most expensive first.
Show name, category and price of every product, sorted by category from A to Z, and inside each category by price from highest to lowest.
The app lists products cheapest first, 3 per page. Show PAGE 2. Return two columns: the name renamed to product (use AS), and price.
Quick quiz
Read more (free)
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.