SELECT: Getting the Data You Need

ORDER BY and LIMIT: Sorting and Top Results

22 min

Putting results in order

So far, the archive has returned rows in whatever order was convenient for fetching, joining, filtering, and returning them.

But people often need the rows in a specific order.

You can see this right away in Kotomarket:

  • the most expensive products;
  • the cheapest products;
  • the newest orders;
  • the products with the most stock;
  • users in alphabetical order;
  • the latest events in the log.

In SQL, you use ORDER BY to set that order.

SELECT name, price
FROM products
ORDER BY price;

This query sorts the products by price.

By default, SQL sorts in ascending order:

ORDER BY price

is the same as:

ORDER BY price ASC

ASC means ascending.

To sort in the opposite direction, use DESC:

SELECT name, price
FROM products
ORDER BY price DESC;

DESC means descending.

For numbers, it's straightforward:

ASC  → 1, 2, 3, 4, 5
DESC → 5, 4, 3, 2, 1

For text, sorting follows alphabetical order according to the rules of the database and its locale.

SELECT name, category
FROM products
ORDER BY name ASC;

This query shows product names from the beginning of the alphabet to the end.

QUERY: The archive can fetch rows in whatever order is convenient. A report needs an order that you define yourself.

Rows shaped like capsules form a glowing staircase in descending order, with the top five glowing brighter than the rest
ORDER BY arranges the rows like a staircase, and LIMIT takes the top — the revived store's first top list.

Without ORDER BY, there is no guaranteed order

Here's an important rule:

SQL doesn't guarantee row order without ORDER BY.

For example:

SELECT id, name, price
FROM products;

This query might return the rows in one order today and a different order tomorrow.

Sometimes it may look as though the database returns rows:

  • in insertion order;
  • by id;
  • in the order they're stored in the table;
  • in the order they're displayed in the interface.

But you can't rely on any of those patterns.

The database may choose a different , use a different index, or read the data differently after statistics are updated or the table changes. The result order can change even though the SQL query stays the same.

If order matters, state it explicitly:

SELECT id, name, price
FROM products
ORDER BY id;

or:

SELECT id, name, price
FROM products
ORDER BY price DESC;

The rule is simple:

No ORDER BY means no guaranteed order.

This matters especially when you use LIMIT. LIMIT takes the “first rows,” but without sorting, you don't know which rows the database will treat as first.

as storedsorted59.9089.9045.9054.9042.90ORDER BYprice DESC89.9059.9054.9045.9042.90LIMIT 3ORDER BY sorts, LIMIT keeps the top
ORDER BY arranges all the result rows first, and only then does LIMIT take the rows from the top.
SELECT name, price
FROM products
ORDER BY price DESC
LIMIT 5;

ASC and DESC

ORDER BY supports two sort directions.

ASC means ascending:

SELECT name, price
FROM products
ORDER BY price ASC;

For prices, that means:

cheaper products first, more expensive products later.

DESC means descending:

SELECT name, price
FROM products
ORDER BY price DESC;

For prices, that means:

more expensive products first, cheaper products later.

If you don't specify a direction, SQL uses ASC.

So these two queries are equivalent:

SELECT name, price
FROM products
ORDER BY price;
SELECT name, price
FROM products
ORDER BY price ASC;

When you're starting out, it helps to read the clause aloud:

ORDER BY price ASC

— sort by price from lowest to highest.

ORDER BY price DESC

— sort by price from highest to lowest.

LIMIT: take only the first rows

LIMIT restricts the number of rows in the result.

For example:

SELECT name, price
FROM products
LIMIT 3;

This query returns only three rows.

But LIMIT by itself doesn't say which rows you want. It simply takes the first rows from the result the query produces.

That's why LIMIT is almost always paired with ORDER BY when the choice of rows matters.

The three cheapest products:

SELECT name, price
FROM products
ORDER BY price ASC
LIMIT 3;

The three most expensive products:

SELECT name, price
FROM products
ORDER BY price DESC
LIMIT 3;

The newest orders:

SELECT id, user_id, created_at
FROM orders
ORDER BY created_at DESC
LIMIT 10;

The logic is always the same:

  1. ORDER BY arranges the rows in the order you need.
  2. LIMIT takes the rows from the top of that ordered result.
ORDER BY price DESC
LIMIT 5

reads as:

put the most expensive products at the top and take the first five.

Why ORDER BY comes near the end of a query

In SQL, the order in which you write query clauses doesn't completely match the most useful way to think about how they're processed.

For example:

SELECT name, price
FROM products
WHERE category = 'Books'
ORDER BY price DESC
LIMIT 5;

You can read this query step by step:

  1. FROM products — take the products table.
  2. WHERE category = 'Books' — keep only the books.
  3. SELECT name, price — choose the columns you need.
  4. ORDER BY price DESC — sort the result by price.
  5. LIMIT 5 — keep the first five rows.

So the sorting applies to the filtered result, rather than to the whole table before filtering.

If the table contains a thousand products but only twenty of them are books, the query first keeps those twenty books, then sorts them by price, and finally takes the five most expensive ones.

This distinction makes queries easier to read:

WHERE

controls which rows participate.

ORDER BY

controls the order in which they're shown.

LIMIT

controls how many rows remain at the top.

Sorting by multiple columns

Sometimes one column isn't enough.

For example, suppose you want to sort products:

  1. first by category;
  2. within each category, by price from highest to lowest.

To do this, list multiple expressions in ORDER BY, separated by commas:

SELECT name, category, price
FROM products
ORDER BY category ASC, price DESC;

Read this query as:

first sort by category in ascending order, and when the category is the same, sort products in that category by price in descending order.

Example result:

namecategoryprice
Portal HouseAccessories$30.00
Anti-Gravity BowlAccessories$10.00
Laser Mouse ToyToys$17.00
Interceptor Mouse ToyToys$9.00
SQL for CatnautsBooks$25.00
Memory of Old EarthBooks$12.00

The first sort key has priority:

category ASC

It arranges the rows by category.

The second key applies only when the first key has the same value:

price DESC

It orders products within the same category.

You can choose a different direction for each column:

ORDER BY category ASC, price DESC, name ASC

That means:

  1. category in ascending order;
  2. within each category, price in descending order;
  3. when prices are equal, name in ascending order.
Practice: write the query
Find Kotomarket's five largest orders: select id and total_amount from orders. Sort from the largest amount to the smallest, and when amounts are equal, sort by id from smallest to largest. Keep only the first five.
Column names and their order are not checked — the values are compared.
SELECT id, total_amount
FROM orders;
Practice: write the query
Arrange the books and toys on the shelf: select name, category, and price for products in the Books and Toys categories. First sort by category alphabetically, then within each category from most expensive to cheapest.
Column names and their order are not checked — the values are compared.
SELECT name, category, price
FROM products
WHERE category IN ('Books', 'Toys');

Sorting by an expression

You can sort by a calculation as well as by an existing column.

For example, the products table contains:

  • price — the product price;
  • stock — the quantity in stock.

If you want to find out which products tie up the most money in inventory, you can calculate their inventory value:

price * stock

The query:

SELECT name, price, stock
FROM products
ORDER BY price * stock DESC;

sorts products by price multiplied by quantity in stock.

So a product that costs $10.00 with 100 units in stock can appear above a product that costs $50.00 with only 2 units in stock.

Because:

10.00 * 100 = 1000.00
50.00 * 2   = 100.00

ORDER BY can work with expressions like this:

ORDER BY price * stock DESC

This is useful when the order depends on a calculation rather than a single column.

Sorting by an alias

If an expression is long, repeating it in ORDER BY is inconvenient.

You can give the expression a name with an :

SELECT
    name,
    price,
    stock,
    price * stock AS stock_value
FROM products
ORDER BY stock_value DESC;

Here:

price * stock AS stock_value

creates a calculated column named stock_value in the result.

Then:

ORDER BY stock_value DESC

sorts by that calculated value.

This works because ORDER BY is logically applied after the SELECT list has been formed. By the time sorting happens, the stock_value alias is available.

But don't confuse this with WHERE.

This doesn't work:

SELECT
    name,
    price,
    stock,
    price * stock AS stock_value
FROM products
WHERE stock_value > 100;

The alias from SELECT isn't available yet in WHERE.

Instead, either repeat the expression:

SELECT
    name,
    price,
    stock,
    price * stock AS stock_value
FROM products
WHERE price * stock > 100
ORDER BY stock_value DESC;

Or use a — but that's a topic for later modules.

The main point of this lesson:

You can use a SELECT alias in ORDER BY. You can't use it in WHERE.

SELECT
    name,
    price,
    stock,
    price * stock AS stock_value
FROM products
ORDER BY stock_value DESC
LIMIT 5;
Practice: write the query
Find the three products with the least money tied up in inventory. Inventory value is price * stock: select name and this value as stock_value from products. Sort from the lowest value to the highest and keep only the first three rows.
Column names and their order are not checked — the values are compared.
SELECT name
FROM products;

Where NULL values go when sorting

NULL means that a value is missing. When you sort, you need to decide where those rows should appear:

  • at the beginning;
  • at the end.

In PostgreSQL, NULL is considered greater than any ordinary value by default when sorting.

So with ascending order:

ORDER BY city ASC

rows with NULL appear at the end.

With descending order:

ORDER BY city DESC

rows with NULL appear at the beginning.

To avoid relying on defaults, you can state the position explicitly:

ORDER BY city ASC NULLS FIRST

That means:

sort cities in ascending order, but put rows with no city at the beginning.

Or:

ORDER BY city ASC NULLS LAST

That means:

sort cities in ascending order, and put rows with no city at the end.

You can use this with DESC too:

ORDER BY price DESC NULLS LAST

This is useful for top lists.

For example, if some products have an unknown price, this query:

SELECT name, price
FROM products
ORDER BY price DESC
LIMIT 5;

may put products with NULL at the top in PostgreSQL, because with DESC, NULL values come first.

To get the most expensive products that have a known price, it's better to write:

SELECT name, price
FROM products
ORDER BY price DESC NULLS LAST
LIMIT 5;

Now products with an unknown price won't displace products with known prices from the top list.

One portability note: different DBMSs may use different default positions for NULL. PostgreSQL lets you specify NULLS FIRST and NULLS LAST explicitly. MySQL doesn't use this syntax, and its default behavior is different: NULL is usually treated as smaller than ordinary values.

SELECT name, price
FROM products
ORDER BY price DESC NULLS LAST
LIMIT 5;

Ties: when values are equal

Imagine we're selecting the three most expensive products:

SELECT id, name, price
FROM products
ORDER BY price DESC
LIMIT 3;

If every product has a different price, the order is clear.

But what if several products have the same price?

For example:

idnameprice
10Portal House$30.00
11Orbital Scratching Post$30.00
12Captain's Bed$30.00
13Anti-Gravity Bowl$10.00

The first three products all have the same price.

This condition:

ORDER BY price DESC

guarantees only one thing:

products that cost $30.00 will appear above products that cost $10.00.

But it doesn't guarantee the order of the $30.00 products relative to one another.

That may seem like a minor detail. It matters for reports, tests, and .

If several rows have the same value in the sort column, their relative order is undefined. It may change after the data is updated, when the changes, or even between similar runs.

To make the order completely predictable, add a second sort key — usually a unique id:

SELECT id, name, price
FROM products
ORDER BY price DESC, id ASC
LIMIT 3;

Now read the sorting as:

  1. first by price, from highest to lowest;
  2. when prices are equal, by id from smallest to largest.

This gives you a stable order.

Stable ordering for LIMIT and pages

Nondeterministic ordering is especially risky when you use it with LIMIT.

For example:

SELECT id, name, price
FROM products
ORDER BY price DESC
LIMIT 10;

If many products have the same price, the database may choose any ten rows from the tied group at the boundary of the top list.

A product may make the top 10 today.
Tomorrow, with exactly the same prices, it may not.

That's not a database bug. The query simply doesn't define the order completely.

For a stable result, add a unique column at the end of the sort:

SELECT id, name, price
FROM products
ORDER BY price DESC, id ASC
LIMIT 10;

This is especially important for .

For example, the first page:

ORDER BY price DESC
LIMIT 10

and the second page using an offset:

ORDER BY price DESC
LIMIT 10 OFFSET 10

If rows have the same price and there's no additional sort by id, the same row can “jump” between pages.

This is more reliable:

ORDER BY price DESC, id ASC
LIMIT 10 OFFSET 10

The main rule:

If you use LIMIT for a report, top list, or page, your sorting should completely determine the row order.

Can you sort by a column that isn't in SELECT?

In reports, you often don't want to display technical columns even though you need them to sort the result.

For example, suppose you want to show product names but sort them by price:

SELECT name
FROM products
ORDER BY price DESC;

That's allowed.

price doesn't have to appear in the SELECT list for you to use it in ORDER BY.

The query returns only name, but price determines the order of the rows.

This is useful when a column affects how the result is arranged but doesn't need to be shown to the reader.

For example:

SELECT id, total_amount
FROM orders
ORDER BY created_at DESC
LIMIT 10;

This gives us the ten newest orders without showing their creation dates in the result.

Common ORDER BY and LIMIT patterns

The combination of ORDER BY + LIMIT appears frequently in SQL.

The most expensive products:

SELECT name, price
FROM products
ORDER BY price DESC
LIMIT 5;

The cheapest products:

SELECT name, price
FROM products
ORDER BY price ASC
LIMIT 5;

The newest orders:

SELECT id, user_id, created_at
FROM orders
ORDER BY created_at DESC
LIMIT 10;

The first users alphabetically:

SELECT id, full_name
FROM users
ORDER BY full_name ASC
LIMIT 20;

Products with the most stock:

SELECT name, stock
FROM products
ORDER BY stock DESC
LIMIT 10;

Products with the highest inventory value:

SELECT
    name,
    price,
    stock,
    price * stock AS stock_value
FROM products
ORDER BY stock_value DESC
LIMIT 10;

In every case, the pattern is the same:

ORDER BY what_matters
LIMIT rows_needed

The key rule for top lists

LIMIT without ORDER BY doesn't create a top list.

SELECT name, price
FROM products
LIMIT 5;

These aren't the five most expensive products.
These aren't the five cheapest products.
They're simply five rows that the database happened to return first.

You get a top list only when you define the sorting criterion explicitly:

SELECT name, price
FROM products
ORDER BY price DESC
LIMIT 5;

Here, the criterion is price in descending order.

Interview question

Interview question:
Does SQL guarantee row order without ORDER BY?

Strong answer:
No. Without ORDER BY, row order isn't guaranteed. It depends on the , indexes, the state of the table, and decisions made by the optimizer. You can't assume rows will be returned in insertion order or by id unless the query says so explicitly.


Interview question:
What does ORDER BY price DESC LIMIT 5 do?

Strong answer:
First, ORDER BY price DESC sorts the rows by price from highest to lowest. Then LIMIT 5 keeps the first five rows. If price is the product price, this combination selects the five most expensive products.


Interview question:
Why is LIMIT 10 without ORDER BY a bad idea for a top list or a page?

Strong answer:
Without ORDER BY, there is no guaranteed row order. LIMIT 10 simply takes the first ten rows from an undefined order. For a top list, specify the sorting criterion explicitly, for example ORDER BY price DESC LIMIT 10. For a stable page, add a unique key at the end of the sort, for example ORDER BY price DESC, id.


Interview question:
Does ORDER BY price DESC guarantee a stable order if several rows have the same price?

Strong answer:
Only the order by price is guaranteed. If several rows have the same price, their order relative to one another is undefined. For a stable result, add another sort key, preferably a unique one: ORDER BY price DESC, id.


Interview question:
Can you sort by an from SELECT?

Strong answer:
Yes. You can use a SELECT alias in ORDER BY. For example, define price * stock AS stock_value, then use ORDER BY stock_value DESC. This works because ORDER BY is logically applied after the SELECT list has been formed. But you can't use that alias in WHERE, because WHERE is processed earlier.


Interview question:
How can you control the position of NULL values when sorting?

Strong answer:
In PostgreSQL, you can explicitly specify NULLS FIRST or NULLS LAST. For example, ORDER BY price DESC NULLS LAST sorts prices in descending order and places rows with an unknown price at the end. This keeps NULL values from interfering with top lists and reports.

Check yourself
How do you select the 3 cheapest products?
Check yourself
What does a query without ORDER BY guarantee?
Check yourself
What does ORDER BY created_at DESC LIMIT 10 mean?
Check yourself
Why add id to ORDER BY price DESC, id?
Check yourself
Can you use an alias from SELECT in ORDER BY?

QUERY: First tell the archive what matters. Only then ask for the top rows.