Skip to content
wannacode

Sorting, the first N, no repeats

Problem

Top 3 for the shop window

The owner wants the three most expensive products on the home page. You know how to get the name and the price. But in what order do the rows come, and how do you take just three?

The idea

ORDER BY

ORDER BY sorts the result. By default from small to large:

SQLdatabase: shop

DESC reverses it, from large to small:

SQLdatabase: shop

You can sort by several columns: first by the first, and on a tie by the second. Customers by city, and within a city by name:

SQLdatabase: shop

Text sorts alphabetically, dates like 2026-10-19 by time.

More precisely, if you are curious

Without ORDER BY, the order of the rows is not promised. It often comes out by id, but that is an accident of how the database read the table. After a change to the table or with a new index, the order can change. When order matters to you, write ORDER BY.

The idea

LIMIT: only the first

LIMIT n returns the first n rows of the result. Together with ORDER BY it gives a top N:

SQLdatabase: shop

LIMIT runs last, after sorting. That is why “the three most expensive” is right. Without ORDER BY it would be three random products.

OFFSET skips rows. That is how pages are made: the second page of orders, 10 per page:

SQLdatabase: shop

Try it

The new customers

Show the name and sign-up date of the five newest customers, newest first.

SQLdatabase: shop

The idea

DISTINCT: no repeats

Which cities are the customers from? With SELECT city, each city repeats as many times as it has customers. DISTINCT removes the repeats:

SQLdatabase: shop

Six cities and NULL: Boris has no city, and that absence is a separate result too.

Try it

The order statuses

Show all the different order statuses, in alphabetical order.

SQLdatabase: shop

Exercise

Cheap and in stock

Show the name, price and stock of the five cheapest products that are in stock, cheapest first.

SQLdatabase: shop
More precisely, if you are curious

Where do NULLs go when sorting? In SQLite and MySQL, ORDER BY city puts them first; in PostgreSQL and Oracle they come last. If it matters, say so: ORDER BY city NULLS LAST. SQLite understands it since version 3.30.

SQLdatabase: shop

Test

Check yourself

1. In what order do the rows of a SELECT without ORDER BY come?
2. What does LIMIT 10 OFFSET 20 do?
3. SELECT DISTINCT city FROM customers also returns NULL. Why?
4. How do you write “most expensive first”?

Made by Ivo Gergov as part of Evo Tech's campaign for accessible programming education ·