← Python lessons

SQL ORDER BY

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

SQL ORDER BY sorts the rows of a query result by a column, smallest value first. It goes after FROM, at the end of the query.

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

Table: books

titleauthorpages
WonderR. J. Palacio320
MatildaRoald Dahl240
HolesLouis Sachar272

Sort rows by a number column

Without ORDER BY, rows come out in the order they were added to the table. Here they are sorted by pages:

SELECT *FROM booksORDER BY pages;

The shortest book, Matilda with 240 pages, comes first. The ; moves to the end, after ORDER BY pages.

Sort text in alphabetical order

A text column sorts from A to Z:

SELECT *FROM booksORDER BY title;

The titles now go Holes, Matilda, Wonder. Times written the same way, like '09:30' and '14:05', also sort as text from earliest to latest.

Sort by a column you do not show

The sorting column does not have to be one you chose after SELECT:

SELECT titleFROM booksORDER BY pages;

Only the titles show, shortest book first.

See also: SQL SELECT and FROM.

Your turn

Add a line to the query so the books are sorted by author, A to Z.

🎯 Goal — make your query show exactly:
title   | author        | pages
--------+---------------+------
Holes   | Louis Sachar  | 272
Wonder  | R. J. Palacio | 320
Matilda | Roald Dahl    | 240
(3 rows)
-- add ORDER BY to the query, and move the ; to the endSELECT *FROM books;