Skip to content

LIMIT and TOP Clauses

Difficulty: Basic
Generated on: 2025-07-10 02:24:07
Category: SQL Cheatsheet for Database Development


SQL LIMIT and TOP Clauses Cheatsheet (Basic)

Section titled “SQL LIMIT and TOP Clauses Cheatsheet (Basic)”

This cheatsheet provides a quick reference for using LIMIT and TOP clauses in SQL to restrict the number of rows returned by a query. These clauses are essential for pagination, sampling data, and improving query performance.

What it is: The LIMIT and TOP clauses restrict the number of rows returned by a SELECT statement. They are crucial for controlling the size of result sets, especially when dealing with large tables.

When to use it:

  • Pagination: Displaying data in manageable chunks (e.g., 10 records per page).
  • Sampling: Retrieving a representative subset of data for analysis or testing.
  • Performance Optimization: Preventing the database from returning unnecessarily large result sets.
  • Finding Top N Records: Selecting the highest or lowest N values based on a specific column.

The syntax varies slightly depending on the database system.

MySQL / MariaDB / SQLite:

SELECT column1, column2, ...
FROM table_name
WHERE condition
ORDER BY column_name
LIMIT number_of_rows;
-- With offset (skipping rows)
SELECT column1, column2, ...
FROM table_name
WHERE condition
ORDER BY column_name
LIMIT number_of_rows OFFSET offset_value; -- or LIMIT offset_value, number_of_rows;

PostgreSQL:

SELECT column1, column2, ...
FROM table_name
WHERE condition
ORDER BY column_name
LIMIT number_of_rows;
-- With offset (skipping rows)
SELECT column1, column2, ...
FROM table_name
WHERE condition
ORDER BY column_name
LIMIT number_of_rows OFFSET offset_value;

SQL Server:

SELECT TOP (number_of_rows) column1, column2, ...
FROM table_name
WHERE condition
ORDER BY column_name;
-- With PERCENT
SELECT TOP (percent) PERCENT column1, column2, ...
FROM table_name
WHERE condition
ORDER BY column_name;
-- With TIES (SQL Server 2005 and later) - Includes rows with the same values as the last row.
SELECT TOP (number_of_rows) WITH TIES column1, column2, ...
FROM table_name
WHERE condition
ORDER BY column_name;

Oracle:

-- Oracle 12c and later (Recommended)
SELECT column1, column2, ...
FROM table_name
WHERE condition
ORDER BY column_name
FETCH FIRST number_of_rows ROWS ONLY;
-- With offset (skipping rows)
SELECT column1, column2, ...
FROM table_name
WHERE condition
ORDER BY column_name
OFFSET offset_value ROWS
FETCH FIRST number_of_rows ROWS ONLY;
-- Older Oracle versions (using ROWNUM - less efficient)
SELECT column1, column2, ...
FROM (
SELECT column1, column2, ...
FROM table_name
WHERE condition
ORDER BY column_name
)
WHERE ROWNUM <= number_of_rows;
  • Displaying the top 5 customers with the highest sales:

    -- SQL Server
    SELECT TOP (5) customer_id, total_sales
    FROM sales
    ORDER BY total_sales DESC;
    -- MySQL/PostgreSQL
    SELECT customer_id, total_sales
    FROM sales
    ORDER BY total_sales DESC
    LIMIT 5;
    -- Oracle 12c+
    SELECT customer_id, total_sales
    FROM sales
    ORDER BY total_sales DESC
    FETCH FIRST 5 ROWS ONLY;
  • Implementing pagination (displaying 10 records per page, starting from page 3):

    -- MySQL/PostgreSQL
    SELECT product_id, product_name, price
    FROM products
    ORDER BY product_name
    LIMIT 10 OFFSET 20; -- Page 3 (offset = (page_number - 1) * page_size = (3-1) * 10 = 20)
    -- Oracle 12c+
    SELECT product_id, product_name, price
    FROM products
    ORDER BY product_name
    OFFSET 20 ROWS
    FETCH FIRST 10 ROWS ONLY;
  • Retrieving a random sample of 100 records:

    -- PostgreSQL (using RANDOM())
    SELECT product_id, product_name
    FROM products
    ORDER BY RANDOM()
    LIMIT 100;
    -- MySQL (using RAND())
    SELECT product_id, product_name
    FROM products
    ORDER BY RAND()
    LIMIT 100;
    -- SQL Server (using NEWID())
    SELECT TOP (100) product_id, product_name
    FROM products
    ORDER BY NEWID();
    -- Oracle (requires more complex approach - consider using DBMS_RANDOM.VALUE)
    -- This example is for illustration and may not be the most performant.
    SELECT product_id, product_name
    FROM (
    SELECT product_id, product_name, DBMS_RANDOM.VALUE AS random_number
    FROM products
    )
    ORDER BY random_number
    FETCH FIRST 100 ROWS ONLY;
  • Always use ORDER BY: Without ORDER BY, the returned rows are not guaranteed to be consistent across multiple executions. The database can return any set of rows that satisfies the LIMIT condition. This is crucial for predictable results, especially when dealing with pagination or finding top N records.

  • Index Optimization: Ensure that the columns used in the ORDER BY clause are properly indexed. This significantly improves query performance, especially for large tables.

  • Use LIMIT early: Apply LIMIT as early as possible in your query, preferably before complex joins or subqueries, to reduce the amount of data processed. Some query optimizers can automatically push the LIMIT down, but it’s best to do it explicitly.

  • Consider WITH TIES (SQL Server): If you need to include all rows that have the same value as the last row in your top N result, use the WITH TIES option in SQL Server.

  • Avoid ROWNUM in Oracle (older versions) when possible: Oracle’s ROWNUM is evaluated before the ORDER BY clause in a subquery, which can lead to unexpected results. The FETCH FIRST ... ROWS ONLY syntax (Oracle 12c+) is the preferred approach.

  • Pagination Performance: For pagination, consider using keyset pagination (also known as “seek method”) instead of offset-based pagination, especially for large datasets. Keyset pagination uses the last value from the previous page to efficiently retrieve the next page of results.

Sample Data:

Let’s assume we have a table called employees with the following data:

employee_idemployee_namesalarydepartment
1Alice60000Sales
2Bob75000Marketing
3Charlie55000Sales
4David80000IT
5Eve75000Marketing
6Frank90000IT
7Grace65000HR
8Henry70000HR
9Ivy85000Finance
10Jack50000Sales

Examples:

  1. Retrieve the top 3 highest-paid employees:

    -- SQL Server
    SELECT TOP (3) employee_name, salary
    FROM employees
    ORDER BY salary DESC;
    -- MySQL/PostgreSQL
    SELECT employee_name, salary
    FROM employees
    ORDER BY salary DESC
    LIMIT 3;
    -- Oracle 12c+
    SELECT employee_name, salary
    FROM employees
    ORDER BY salary DESC
    FETCH FIRST 3 ROWS ONLY;

    Output (all databases):

    employee_namesalary
    Frank90000
    Ivy85000
    David80000
  2. Retrieve the top 2 employees with the lowest salaries:

    -- SQL Server
    SELECT TOP (2) employee_name, salary
    FROM employees
    ORDER BY salary ASC;
    -- MySQL/PostgreSQL
    SELECT employee_name, salary
    FROM employees
    ORDER BY salary ASC
    LIMIT 2;
    -- Oracle 12c+
    SELECT employee_name, salary
    FROM employees
    ORDER BY salary ASC
    FETCH FIRST 2 ROWS ONLY;

    Output (all databases):

    employee_namesalary
    Jack50000
    Charlie55000
  3. Retrieve the top 3 employees from the IT department:

    -- SQL Server
    SELECT TOP (3) employee_name, salary
    FROM employees
    WHERE department = 'IT'
    ORDER BY salary DESC;
    -- MySQL/PostgreSQL
    SELECT employee_name, salary
    FROM employees
    WHERE department = 'IT'
    ORDER BY salary DESC
    LIMIT 3;
    -- Oracle 12c+
    SELECT employee_name, salary
    FROM employees
    WHERE department = 'IT'
    ORDER BY salary DESC
    FETCH FIRST 3 ROWS ONLY;

    Output (all databases):

    employee_namesalary
    Frank90000
    David80000
  4. Retrieve the top 2 employees with the same highest salary (SQL Server WITH TIES):

    SELECT TOP (2) WITH TIES employee_name, salary
    FROM employees
    ORDER BY salary DESC;

    Output (SQL Server):

    employee_namesalary
    Frank90000
    Ivy85000
  5. Paginating Employees (MySQL/PostgreSQL - Page 2, 3 records per page):

    SELECT employee_name, salary
    FROM employees
    ORDER BY employee_name
    LIMIT 3 OFFSET 3;

    Output (MySQL/PostgreSQL):

    employee_namesalary
    Henry70000
    Ivy85000
    Jack50000
  • Missing ORDER BY: Forgetting to include an ORDER BY clause leads to unpredictable and inconsistent results. Always specify the order in which you want the limited rows returned.

  • Incorrect Offset Calculation: When implementing pagination, double-check your offset calculation. The offset should be (page_number - 1) * page_size. A wrong offset will lead to incorrect page results.

  • Performance Issues with Large Offsets: Offset-based pagination can become very slow for large offsets because the database still has to process all the rows up to the offset. Consider keyset pagination or other optimization techniques for large datasets.

  • Database-Specific Syntax: Be aware of the syntax differences between database systems. Using TOP in MySQL or LIMIT in SQL Server will result in syntax errors.

  • ROWNUM in Oracle (Older Versions): Understand how ROWNUM is evaluated in Oracle. It’s applied before the ORDER BY clause in a subquery, so you need to be careful about how you use it. Prefer FETCH FIRST ... ROWS ONLY (Oracle 12c+).

  • Data Modification During Pagination: If the underlying data changes between page requests, the pagination results may be inconsistent. Consider using techniques like snapshot isolation or optimistic locking to handle concurrent data modifications.

FeatureMySQL/MariaDB/SQLitePostgreSQLSQL ServerOracle (12c+)Oracle (Older)
Limiting RowsLIMITLIMITTOPFETCH FIRSTROWNUM
OffsetOFFSETOFFSETN/AOFFSETN/A
Top with TiesN/AN/AWITH TIESN/AN/A
PercentageN/AN/APERCENTN/AN/A
Random SamplingORDER BY RAND()ORDER BY RANDOM()ORDER BY NEWID()DBMS_RANDOM.VALUEDBMS_RANDOM.VALUE
Best PracticeLIMIT with ORDER BYLIMIT with ORDER BYTOP with ORDER BYFETCH FIRST with ORDER BYAvoid ROWNUM if possible, use subqueries carefully

This cheatsheet provides a solid foundation for using LIMIT and TOP clauses in SQL. Remember to adapt the syntax and techniques to your specific database system and use cases. Always prioritize performance and data consistency when working with large datasets.