Sorting and limiting

Topic 3 of 4 in Querying a table11 min readBeginnerFree course

Overview

A query’s result is a set of rows, and a set has no order. If you want the cheapest products first, the newest orders at the top, or customers alphabetically, you have to ask — with ORDER BY. And when you only need the top few rows, LIMIT stops there.

Sorting, then limiting. Rows from products arrive in no guaranteed order: Assam Breakfast 9.50, Burr Grinder 89.00, Chamomile Calm 8.00, Electric Kettle 59.90, Jasmine Green 12.75. ORDER BY price DESC sorts them: Burr Grinder 89.00, Electric Kettle 59.90, Jasmine Green 12.75, Assam Breakfast 9.50, Chamomile Calm 8.00. LIMIT 2 then keeps the first two: Burr Grinder and Electric Kettle. ORDER BY sorts, ascending by default, and DESC reverses; you can sort by several columns, such as ORDER BY country, city. LIMIT n keeps the first n rows and OFFSET skips rows first, so page 3 of 20 is LIMIT 20 OFFSET 40. Without ORDER BY, the database may return rows in any order, and LIMIT then picks arbitrary rows.

ORDER BY

Add ORDER BY and a column at the end of the query:

SQL
SELECT name, price
FROM products
WHERE category_id = 2
ORDER BY price;
Text
          name          | price 
------------------------+-------
 Chamomile Calm         |  8.00
 Assam Breakfast        |  9.50
 Jasmine Green          | 12.75
 Darjeeling First Flush | 18.00
(4 rows)

The default direction is ascending (ASC): smallest numbers, earliest dates and A-to-Z text first. DESC reverses it:

SQL
SELECT name, price
FROM products
WHERE category_id = 2
ORDER BY price DESC;
Text
          name          | price 
------------------------+-------
 Darjeeling First Flush | 18.00
 Jasmine Green          | 12.75
 Assam Breakfast        |  9.50
 Chamomile Calm         |  8.00
(4 rows)

Sorting by several columns

When two rows have the same value in the first sort column, their order is undecided — unless you add a second column to break the tie. List columns separated by commas, each with its own direction:

SQL
SELECT country, city, first_name
FROM customers
ORDER BY country, city DESC, first_name;
Text
  country  |   city    | first_name 
-----------+-----------+------------
 France    | Lyon      | Hugo
 India     | Pune      | Asha
 India     | Pune      | Farhan
 India     | Mumbai    | Isha
 Nigeria   | Lagos     | Dee
 Singapore | Singapore | Chen
 Spain     | Madrid    | Elena
 UK        | Leeds     | Ben
 USA       | Seattle   | Grace
 USA       | Austin    | Jack
(10 rows)

Countries A to Z; within each country, cities Z to A (so Pune comes before Mumbai); within each city, first names A to Z (Asha before Farhan). DESC applies only to the column it follows.

Sorting by aliases and expressions

ORDER BY can use a column alias from the select list, or any expression — including columns you didn’t select:

SQL
SELECT name, price * stock AS stock_value
FROM products
ORDER BY stock_value DESC;
Text
          name          | stock_value 
------------------------+-------------
 Gift Card              |    24975.00
 Assam Breakfast        |      760.00
 Colombian Supremo      |      660.00
 Electric Kettle        |      599.00
 Ethiopian Yirgacheffe  |      580.00
 Burr Grinder           |      534.00
 Darjeeling First Flush |      450.00
 Jasmine Green          |      382.50
 Pour-Over Dripper      |      360.00
 Chamomile Calm         |       96.00
 Glass Teapot           |        0.00
 Decaf House Blend      |        0.00
(12 rows)
SQL
SELECT first_name, last_name
FROM customers
ORDER BY signup_date DESC;
Text
 first_name | last_name 
------------+-----------
 Jack       | Wilson
 Isha       | Patel
 Hugo       | Martin
 Grace      | Kim
 Farhan     | Ali
 Elena      | García
 Dee        | Okafor
 Chen       | Wei
 Ben        | Carter
 Asha       | Rao
(10 rows)

That second query sorts by signup_date without showing it — newest customers first.

You may also see ORDER BY 2, meaning “the second column of the select list”. It’s handy when typing interactively, but it breaks silently when someone reorders the columns, so prefer names in saved queries.

Where do NULLs go?

NULL isn’t a value, so where does it sort? In PostgreSQL, NULLs count as larger than everything: last when ascending, first when descending. The gift card has no category:

SQL
SELECT name, category_id
FROM products
ORDER BY category_id DESC, name
LIMIT 4;
Text
      name       | category_id 
-----------------+-------------
 Gift Card       |            
 Burr Grinder    |           3
 Electric Kettle |           3
 Glass Teapot    |           3
(4 rows)

Add NULLS FIRST or NULLS LAST to choose explicitly:

SQL
SELECT name, category_id
FROM products
ORDER BY category_id DESC NULLS LAST, name
LIMIT 4;
Text
       name        | category_id 
-------------------+-------------
 Burr Grinder      |           3
 Electric Kettle   |           3
 Glass Teapot      |           3
 Pour-Over Dripper |           3
(4 rows)

Other databases disagree on the default — MySQL and SQL Server treat NULLs as smallest — so if NULL placement matters, say what you want.

Text sorting and collations

Text is sorted by the database’s collation — its rules for the language. With a typical English collation, 'apple' and 'Apple' sort next to each other, and accented letters sort near their plain versions, so García and Garcia are neighbours. That’s usually what people expect. If you ever see uppercase words all sorted before lowercase ones, the database is using the simple byte-order C collation.

LIMIT: just the top rows

LIMIT n keeps the first n rows of the result. Combined with ORDER BY, it answers “top N” questions:

SQL
SELECT name, price
FROM products
ORDER BY price DESC
LIMIT 3;
Text
      name       | price 
-----------------+-------
 Burr Grinder    | 89.00
 Electric Kettle | 59.90
 Glass Teapot    | 32.00
(3 rows)

The three most expensive products. LIMIT is applied after sorting, so it always cuts the sorted list.

LIMIT without ORDER BY returns some rows, not the first or the last ones. That’s fine for a quick peek at a table (SELECT * FROM orders LIMIT 5) but never for a real answer.

The standard SQL spelling, also supported by PostgreSQL, Oracle and SQL Server, is FETCH FIRST 3 ROWS ONLY. Its variant WITH TIES also includes any rows that tie with the last one:

SQL
SELECT id, shipping_fee
FROM orders
ORDER BY shipping_fee DESC
FETCH FIRST 1 ROWS WITH TIES;
Text
 id | shipping_fee 
----+--------------
 12 |         9.50
  5 |         9.50
 24 |         9.50
(3 rows)

Three orders share the highest shipping fee, so all three come back even though you asked for one row.

OFFSET and pagination

OFFSET n skips the first n rows. Together with LIMIT, it splits a result into pages — the way a shop shows “products 1–4, 5–8, …”:

SQL
SELECT name, price
FROM products
ORDER BY price, name
LIMIT 4 OFFSET 0;
Text
       name        | price 
-------------------+-------
 Chamomile Calm    |  8.00
 Assam Breakfast   |  9.50
 Decaf House Blend | 11.25
 Colombian Supremo | 12.00
(4 rows)
SQL
SELECT name, price
FROM products
ORDER BY price, name
LIMIT 4 OFFSET 4;
Text
          name          | price 
------------------------+-------
 Jasmine Green          | 12.75
 Ethiopian Yirgacheffe  | 14.50
 Darjeeling First Flush | 18.00
 Pour-Over Dripper      | 24.00
(4 rows)

Page p with n rows per page is LIMIT n OFFSET (p − 1) × n. Two details matter:

  • The sort must be unique. If two products had the same price, the database could put them in either order — and one could appear on both pages or neither. Adding name (or the primary key) as a final sort column makes the order fully determined.
  • Large offsets are slow. OFFSET 100000 still makes the database produce and throw away 100,000 rows. For deep pagination, applications use keyset pagination instead: remember the last value shown and ask for WHERE (price, name) > (24.00, 'Pour-Over Dripper') ORDER BY price, name LIMIT 4.

Clause order, again

ORDER BY and LIMIT come last, in that order:

SQL
SELECT name, price          -- 1. columns
FROM products               -- 2. table
WHERE stock > 0             -- 3. rows to keep
ORDER BY price DESC         -- 4. sort
LIMIT 3;                    -- 5. how many
Text
      name       | price 
-----------------+-------
 Burr Grinder    | 89.00
 Electric Kettle | 59.90
 Gift Card       | 25.00
(3 rows)

Tip: if a result “looks sorted” without an ORDER BY, that’s an accident of how the data happens to be stored. It can change after an update, a vacuum, or a new index. If order matters, write ORDER BY.

Exercise

The latest orders

The shop's dashboard shows the three most recent orders. Write a query returning the id, customer_id, ordered_at and status of the three newest orders, newest first. Then write a second query for the products page: every product's name and price, sorted by price from cheapest to most expensive, showing the second page of four products (rows 5 to 8).

SQL
-- 1. The three newest orders
SELECT id, customer_id, ordered_at, status
FROM orders;

-- 2. Page 2 of the product list, 4 per page, cheapest first

Summary

  • Without ORDER BY, rows come back in no guaranteed order — even if they look sorted today.
  • ORDER BY sorts ascending by default; add DESC for descending, and list several columns to break ties.
  • You can sort by a column alias, an expression, or a column that isn't in the select list.
  • In PostgreSQL NULLs sort last in ascending order and first in descending; NULLS FIRST / NULLS LAST overrides that.
  • LIMIT n keeps the first n rows and OFFSET skips rows — always together with ORDER BY, or the rows you get are arbitrary.