iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

SQL SELECT TOP

SELECT TOP (SQL Server) limits the number of rows returned. Postgres and MySQL use LIMIT; SQLite uses LIMIT too.

Limiting rows by dialect

EXAMPLE
-- SQL Server / MS Access
SELECT TOP 10 id, name
FROM users
ORDER BY signup_date DESC;

-- Or as a percentage
SELECT TOP 5 PERCENT id, name
FROM users
ORDER BY total_spent DESC;

-- Postgres / SQLite / MySQL
SELECT id, name
FROM users
ORDER BY signup_date DESC
LIMIT 10;

-- Offset (skip the first N) - paging
SELECT id, name
FROM users
ORDER BY signup_date DESC
LIMIT 10 OFFSET 20;       -- page 3 of 10-per-page

-- Cursor-based paging (recommended for large datasets)
-- First page
SELECT id, name, signup_date
FROM users
WHERE signup_date < NOW()
ORDER BY signup_date DESC, id DESC
LIMIT 10;

-- Next page - pass the LAST row's values as a 'keyset' filter
SELECT id, name, signup_date
FROM users
WHERE (signup_date, id) < ('2026-01-15 10:00:00', 12345)
ORDER BY signup_date DESC, id DESC
LIMIT 10;

-- This scales much better than OFFSET because OFFSET still scans the skipped rows.

-- SQL Server modern alternative - OFFSET FETCH
SELECT id, name
FROM users
ORDER BY signup_date DESC
OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY;

-- Common mistake: LIMIT without ORDER BY
-- Without an explicit order, the database can return rows in ANY order.
-- Always pair LIMIT with ORDER BY in production code.

-- Top-N per group (window function)
SELECT *
FROM (
  SELECT
    o.*,
    ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY total DESC) AS rn
  FROM orders o
) ranked
WHERE rn <= 3;          -- top 3 orders per user

Why it matters

Always pair LIMIT/TOP with ORDER BY. Switch from OFFSET to keyset (cursor-based) pagination once your tables get large - OFFSET 1000000 will scan a million rows just to skip them.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
-- SQL Server
SELECT TOP 5 * FROM products;
-- MySQL / PostgreSQL
SELECT * FROM products LIMIT 5;
Try it Yourself »

Exercise

In MySQL / PostgreSQL, cap the result to the first 5 rows.

SELECT * FROM products 5;

Test yourself

Q1. MySQL / PostgreSQL keyword for limiting rows is…
Q2. SQL Server keyword for the same is…
Q3. "Top N" is only meaningful with…

Discussion

Loading…