← Python lessons

SQL DESC and LIMIT

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

SQL DESC after ORDER BY sorts rows from largest to smallest. LIMIT keeps only the first rows of a result. Together they find the top row.

The examples below use this books table. Change a query and press Run to see its result.

Table: books

titleprice
Wonder18
Matilda15
Holes16
The Hobbit25

Sort from largest to smallest

ORDER BY sorts smallest first. Write DESC (short for descending) after the column to sort largest first:

SELECT title, priceFROM booksORDER BY price DESC;

The most expensive book, The Hobbit, comes first. Text sorts from Z to A with DESC, and times like '14:05' sort latest first.

Show only the first rows

LIMIT goes at the very end of the query. The number after it says how many rows to keep:

SELECT title, priceFROM booksORDER BY titleLIMIT 2;

Only the first two titles from A to Z are in the result: Holes and Matilda.

Find the top row with DESC and LIMIT 1

Sort with DESC, then keep one row with LIMIT 1. The one row left is the most expensive book:

SELECT title, priceFROM booksORDER BY price DESCLIMIT 1;

Only The Hobbit is left, at 25 dollars.

Note: Without ORDER BY, LIMIT 1 keeps whichever row comes first in the table, which is not always the most expensive.

See also: SQL ORDER BY.

Your turn

Add two lines to the query so it shows only the book whose title comes last from A to Z.

🎯 Goal — make your query show exactly:
title  | price
-------+------
Wonder | 18
(1 row)
-- add ORDER BY with DESC, then LIMIT, and move the ; to the endSELECT title, priceFROM books;