Skip to content

Sorting and Limiting: ORDER BY and LIMIT

Programming SQL Difficulty 1/5

Beginning of the lesson

Sorting and Limiting: ORDER BY and LIMIT

Put your rows in the right order, then keep just the ones you want

Big Idea: A table stores rows, but it does not promise any order. ORDER BY lets you sort the rows however you like, and LIMIT lets you keep only the first few. Together they answer questions like "Who are the top 3 players?"
By the end you will be able to:
  • sort rows with ORDER BY, low-to-high (ASC) or high-to-low (DESC),
  • break ties by sorting on more than one column,
  • keep only a handful of rows with LIMIT,
  • skip rows with OFFSET to build pages,
  • write a "top-N" query to find the best or worst rows.

1. Our example: a game leaderboard

Every example in this lesson uses one small table called players. It is the scoreboard of a video game. Let us build it once so we all picture the same data.

CREATE TABLE players (
    id      INT,
    name    VARCHAR(20),
    score   INT,
    level   INT,
    country VARCHAR(15)
);

INSERT INTO players (id, name, score, level, country) VALUES
    (1, 'Aisha', 950, 7, 'Kenya'),
    (2, 'Bilal', 720, 5, 'Egypt'),
    (3, 'Chen',  950, 8, 'China'),
    (4, 'Diego', 610, 4, 'Peru'),
    (5, 'Elena', 880, 6, 'Spain'),
    (6, 'Farah', 720, 5, 'Iran'),
    (7, 'Grace', 1040, 9, 'Kenya'),
    (8, 'Hiro',  610, 4, 'Japan');

If we just ask for everything, the database is free to hand the rows back in any order (often the order they were stored):

SELECT name, score, level, country FROM players;
namescorelevelcountry
Aisha9507Kenya
Bilal7205Egypt
Chen9508China
Diego6104Peru
Elena8806Spain
Farah7205Iran
Grace10409Kenya
Hiro6104Japan

This is a messy scoreboard! Nobody wants a leaderboard that is not in order. Let us fix that.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers