Sorting and limiting results

Put rows in order and take only the first few.

A real SQLite database runs inside your browser tab. Nothing to install.

ORDER BY sorts the result

Without ORDER BY, a database may return rows in any order. Add it at the end of the query to sort.

The default direction is ascending, smallest first. Add DESC for largest first.

Example
SELECT name, marks FROM students ORDER BY marks;

Your turn: highest first

Here the order of the rows is checked too.

Practice task

Show every column for all students, with the highest marks first.

Your answer is run and checked in the lesson. Create a free account to try it.

Sorting by more than one column

List several columns in ORDER BY, separated by commas. Rows are sorted by the first column, and the second column decides the order among rows that tie.

Each column can have its own direction.

Example
SELECT city, name, marks FROM students ORDER BY city, marks DESC;

LIMIT takes the first rows

LIMIT 3 returns at most three rows. It is written last, after ORDER BY.

Sorting first and limiting second is how you ask for the top or bottom few.

Example
SELECT name, marks FROM students ORDER BY marks LIMIT 2;

Your turn: the top three

Combine sorting and limiting.

Practice task

Show the name and marks of the three students with the highest marks, best first.

Your answer is run and checked in the lesson. Create a free account to try it.