Code / SQL with Data / Unit 3: Sorting and calculating

ORDER BY and LIMIT ORDER BY और LIMIT

Lesson 6 of 13 · about 12 minutes · Sort results, by one or many columns, and keep the top few.

⚡ 0 XP

Step 1 of 2

Sorting with ORDER BY

Masala chaiBun maskaPoha

Without ORDER BY, a database may return rows in any order. To sort, add ORDER BY at the end:

  • ORDER BY runs or ORDER BY runs ASC — smallest first (A→Z for text)
  • ORDER BY runs DESC — biggest first

You can sort by several columns: ORDER BY team, runs DESC sorts by team A→Z, and inside each team by runs, highest first. The order of clauses is always: SELECT … FROM … WHERE … ORDER BY ….

Example
SELECT name, runs
FROM players
ORDER BY runs DESC;

🎯 Challenge: Team sheet +15 XP

Show name, team and runs of all players, sorted by team A→Z, and inside each team by runs from highest to lowest.

Try twice to unlock the solution (0/2)

query.sqlCtrl ⏎
Tables (practice database)
Results

Press Run to see your query’s rows here.

Checklist

Press Run to check your code.

  • Your rows match the expected answer, in the right order
  • Uses ORDER BY
Lesson notes (text version)

1. Sorting with ORDER BY

Without ORDER BY, a database may return rows in any order. To sort, add ORDER BY at the end:

  • ORDER BY runs or ORDER BY runs ASC — smallest first (A→Z for text)
  • ORDER BY runs DESC — biggest first

You can sort by several columns: ORDER BY team, runs DESC sorts by team A→Z, and inside each team by runs, highest first. The order of clauses is always: SELECT … FROM … WHERE … ORDER BY ….

                SELECT name, runs
FROM players
ORDER BY runs DESC;
              

Challenge: Team sheet

Show name, team and runs of all players, sorted by team A→Z, and inside each team by runs from highest to lowest.

2. Top N with LIMIT

LIMIT 5 keeps only the first 5 rows of the result. Together with ORDER BY … DESC it answers every “top N” question:

SELECT name, runs FROM players ORDER BY runs DESC LIMIT 5;

LIMIT always comes last. Without ORDER BY, “the first 5 rows” could be any 5, so always sort first.

                SELECT name, runs
FROM players
ORDER BY runs DESC
LIMIT 5;
              

Challenge: Top 3 wicket-takers

Show name and wickets of the 3 players with the most wickets, highest first.

Search by task, format or tool name.