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:
| Parameter | Type | Description |
|---|---|---|
| ORDER BY | Clause | Sorts rows by one or more columns. |
| LIMIT | Clause | Restricts maximum number of rows returned. |
Ready-to-Run Code Example
Executable in CompilraRun 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
SQL Session-Level Variable Mapping Constraints and CTE Declarations
Define and map session-level variables, CTE bind parameters, and column expressions in SQL queries.
SQL WHERE Filtering: Comparison and Logical Operators (AND, OR, IN)
Filter records using the WHERE clause with comparison, AND, OR, NOT, IN, and BETWEEN.
SQL Dynamic Transactional CASE WHEN Metrics Query Logic
Implement dynamic transactional business logic and classification metrics in SQL using CASE WHEN expressions.
SQL Online Compiler
Open in Compilra IDE
Run and test SQL on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.