Query data

Sort and limit results

Use ORDER BY and LIMIT to make query results predictable and return only the slice an interface needs.

8 minute lesson

~~~

SQL does not promise a row order unless you request one.

Return the newest five orders like this:

SELECT id, created_at, total
FROM orders
ORDER BY created_at DESC, id DESC
LIMIT 5;

DESC puts later timestamps first. The second key matters when two rows share the same timestamp. Because id is unique, the complete ordering is stable.

Without ORDER BY, LIMIT 5 means “any five rows the current plan produces.” An index change, database restart, or updated statistics can change which rows happen to appear.

You can sort ascending with ASC, which is normally the default:

ORDER BY total ASC

NULL placement differs between database systems and can also be controlled with database-specific syntax. Decide where missing values belong instead of relying on an accidental default.

LIMIT is useful for previews and pagination. Large OFFSET values can become slow because the database still finds and skips earlier rows. They can also produce duplicates or gaps while new rows are inserted. For large changing datasets, paginate from the last ordered key instead.

For example, after receiving (created_at, id) from the last row, the next query can continue after that pair using syntax suited to your database.

Your action is to insert two rows with the same timestamp. Compare ordering by created_at alone with ordering by created_at, id, then explain which result is stable.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →