SQL:SQL ORDER BY, LIMIT, and OFFSET for Pagination
SQL•Sorting & Pagination

SQL ORDER BY, LIMIT, and OFFSET for Pagination

Sort query results ascending (ASC) or descending (DESC) and slice pagination subsets with LIMIT.

Syntax

SELECT * FROM table ORDER BY column DESC LIMIT 10 OFFSET 20;

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
ORDER BYClauseSorts rows by one or more columns.
LIMITClauseRestricts maximum number of rows returned.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing SQL locally:

CREATE TABLE users (
    id INTEGER PRIMARY KEY,
    username TEXT,
    points INTEGER
);

INSERT INTO users VALUES
    (1, 'dev_alex', 850),
    (2, 'sarah_code', 1420),
    (3, 'mark_t', 990),
    (4, 'jane_smith', 1250),
    (5, 'c_hacker', 610);

-- Retrieve top 3 leaderboard users
SELECT username, points
FROM users
ORDER BY points DESC
LIMIT 3;
Expected Output:
username    points
----------  ------
sarah_code  1420  
jane_smith  1250  
mark_t      990   

How It Works: Step-by-Step

  • Lines 1-13: Sets up users leaderboard table.
  • Lines 16-19: ORDER BY points DESC sorts descending; LIMIT 3 returns top 3.

Key Concepts

  • ORDER BY defaults to ASC (ascending) if direction is omitted.
  • LIMIT n OFFSET m implements traditional database pagination.

Common Mistake: Using LIMIT without an ORDER BY clause

Relational databases do not guarantee any default order without explicit ORDER BY.

❌ Incorrect
SELECT * FROM users LIMIT 5; // Unpredictable row order!
✅ Correct
SELECT * FROM users ORDER BY id ASC LIMIT 5;

Related SQL Tutorials & Compiler

Run and test SQL on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

SQL Online Compiler