Menu
CoddyTech

Sort and Limit

Part of the First Queries section of Coddy's PostgreSQL journey. Lesson 4 of 20.

Tables have no guaranteed display order. ORDER BY sorts the result; ASC means smallest first and DESC means largest first. Add a unique id as a second sort key when values tie.

Input table products:

idnamecategorypricestockactivenote
1Maptravel125TrueNULL
2Notebookbooks80TrueRecycled
3Atlasbooks243FalseNULL
4Mughome128TrueBlue
5lamphome302FalseClearance
6Mini maptravel610TrueNULL
SELECT id, price FROM products ORDER BY price DESC, id ASC LIMIT 2;

The example returns the two highest prices: id 5 at 30 and id 3 at 24. Sorting happens before LIMIT selects the first two rows. The id tie-breaker makes equal prices predictable.

Use ORDER BY for reliable order and LIMIT to cap the result after sorting.

challenge icon

Challenge

Easy

Return id, name and stock for the three products with the least stock. Sort by stock ascending, then id ascending.

The input tables are shown in the test panel. Each run starts from fresh data. Return the named columns in the stated order; do not hard-code the displayed rows.

Try it yourself

-- Write your SQL here.
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in First Queries

Practice on your own: PostgreSQL playground