CodingNeed.

2 · Handle real values · 12 MIN

Sort ties and choose a small result

A stable order needs an explicit tie-breaker.

ORDER BY points DESC puts larger scores first. Ada and Sam tie at 20, so id ASC breaks that tie with a stable second key. LIMIT keeps only the requested number of sorted rows in SQLite. Without an explicit tie-breaker the database may return tied rows in either order, which makes top lists and pagination confusing. SELECT column order controls the shape of each row; ORDER BY controls the order among rows.

Keep the source rows visible. Predict which rows and columns will remain after each operation.

Before you start

No installation. The tables below are loaded automatically for every run; edits do not touch the CodingNeed account database.

New words, explained

DESC
Descending: larger values first.
ASC
Ascending: smaller values first.
tieBreaker
A second ordering field used when the first is equal.

Follow the example step by step

  1. Sort all four rows on paper by points.
  2. Resolve the 20-point tie by id.
  3. Only then keep the first two rows.
  4. Reverse the primary direction for the exercise without changing its tie-breaker.
Practice table: learners
idnamecitypoints
1AdaDelhi20
2LinNULL (unknown)0
3GraceDelhi35
4SamPune20
Practice table: enrollments
learner_idcourse
1React
1SQL
3SQL

You are ready to move on when: Return the two lowest-scoring learners as name, points. Sort points ascending, then id ascending.

Read the example

SELECT name, points FROM learners
ORDER BY points DESC, id ASC
LIMIT 2;
Check the expected output
[["Grace",35],["Ada",20]]

Your challenge

Return the two lowest-scoring learners as name, points. Sort points ascending, then id ascending.

Common trap

LIMIT without ORDER BY does not define which rows are first.

Further reading: SQLite SELECT reference

Next lesson: Count rows before grouping them

Essential cookies keep your account signed in. Optional analytics is not configured on this site. Your choice does not affect access to lessons.

Read the Privacy Policy. You can change this choice in the footer.