datarekha

ORDER BY, LIMIT, and DISTINCT

Sorting results, paging through them, and removing duplicates — the small clauses you touch in almost every query.

5 min read Beginner SQL Lesson 3 of 27

What you'll learn

  • Sorting by one column, several columns, and even a column you didn't select
  • Paging with LIMIT + OFFSET, and why deep offsets get slow
  • DISTINCT versus GROUP BY for removing duplicates

Before you start

A query with no ORDER BY returns rows in whatever order the engine found convenient. That is not random, but it is not guaranteed either, and it can quietly shift between runs after an index change or a parallel scan. So if the order of the output matters, you say so.

We will sort this small product table:

idnamecategoryprice
1PencilStationery2
2NotebookStationery6
3CoffeeGrocery9
4LaptopElectronics900
5CableElectronics12

ORDER BY — sort the rows

The default is ascending; add DESC for descending.

SELECT name, price
FROM   products
ORDER BY price DESC;
nameprice
Laptop900
Cable12
Coffee9
Notebook6
Pencil2

Sort priority runs left to right, which lets you break ties — ORDER BY category, price DESC sorts by category first, then puts the priciest item first within each category. And because ORDER BY runs after FROM, it can sort by a column you did not even select: SELECT name FROM products ORDER BY price DESC returns just the names, but in price order — handy for “a clean list, in the right business order.”

LIMIT and OFFSET — top-N and paging

LIMIT n keeps the first n rows after sorting — that is how you ask for “the three priciest”:

SELECT name, price
FROM   products
ORDER BY price DESC
LIMIT 3;
nameprice
Laptop900
Cable12
Coffee9

OFFSET k skips the first k rows, so LIMIT 20 OFFSET 40 is “page 3 of 20-per-page”. It is the natural way to paginate — but it has a sting in the tail.

DISTINCT — collapse duplicate rows

DISTINCT removes rows where every selected column is identical:

SELECT DISTINCT category
FROM   products
ORDER BY category;
category
Electronics
Grocery
Stationery

The catch is in that word every: SELECT DISTINCT category, price de-duplicates on the whole (category, price) pair, not on category alone, so two Electronics items at different prices both survive. For pure de-duplication DISTINCT and GROUP BY are interchangeable; reach for GROUP BY the moment you also want a COUNT(*) or SUM(...) alongside — which is the next lesson.

Practice

Quick check

0/3
Q1SELECT name FROM users LIMIT 3 — is the result deterministic?
Q2You want page 4 of a list, 20 items per page, sorted by created_at DESC. Which clause?
Q3What does SELECT DISTINCT country, signup_date FROM users return?

Sign in to track your progress

Completed lessons, your XP, level, and streak save to your account — it's free and takes a few seconds.

Practice this in an interview

All questions

Related lessons

Explore further

Skip to content