MySQL
POSTGRESQL
SQL

SQL LIMIT Clause: Complete Handbook

intro

Let’s see what the SQL LIMIT clause is and how it allows you to control the number of records returned by your queries.

Tools used in the tutorial
Tool Description Link
Dbvisualizer DBVISUALIZER
TOP RATED DATABASE MANAGEMENT TOOL AND SQL CLIENT

By default, databases return all records that match the criteria specified in a SELECT query. On large datasets, this can easily lead to performance issues. That is why databases such as MySQL and PostgreSQL provide the SQL LIMIT clause. This powerful clause enables you to control the number of rows returned by a query, offering precise control over result sets.

In this article, you will find out what the LIMIT SQL clause is, which databases support it, and how and when to use it. Time to set a limit on the number of records returned by your queries!

What Is the LIMIT SQL Clause?

The LIMIT SQL clause restricts the number of rows returned by a query. In detail, it allows you to define an upper limit on the number of records fetched by an SQL query.

Note that LIMIT is not part of standard SQL. It appears as a vendor extension to SQL in some databases, including MySQL, PostgreSQL, and others. Refer to the official documentation pages to learn more:

In particular, SQL Server and Oracle do not support LIMIT. The SQL Server LIMIT equivalent clause is TOP while the Oracle equivalent clause is OFFSET...FETCH.

OFFSET...FETCH comes from the SQL 2008 standard as a method to standardize query limiting and offsetting behavior and is also supported by SQL Server, MariaDB, and PostgreSQL.

How to Use LIMIT in SQL

This is the syntax of LIMIT in SQL dialects that support the clause:

Copy
        
1 SELECT select_list 2 FROM table_name 3 [ WHERE ... ] 4 [ ORDER BY ... ] 5 [ LIMIT number_records ] [ OFFSET number_offset ]

Where:

  • number_records is a non-negative integer representing the number of rows the query should return;
  • number_offset is a non-negative integer that specifies the starting point from which to fetch rows. It indicates the number of rows to skip before starting row retrieval.

Note that a query can have an OFFSET clause without a LIMIT clause. However, the two clauses are typically used together in a single SQL LIMIT OFFSET query.

If number_records is 0, the LIMIT SQL query will always return an empty result set. Consider the sample query below:

Copy
        
1 SELECT * 2 FROM products 3 LIMIT 0;

This will always return an empty table, no matter how many rows the products table contains.

Note the empty result set
Note the empty result set

PostgreSQL also supports two special values for LIMIT:

  • ALL: To get all rows in the table.
  • NULL: To ignore the LIMIT clause and retrieve all rows.

Both produce the same results, changing the behavior of the query as if the LIMIT clause was not present at all. Assume you have the following PostgreSQL query:

Copy
        
1 SELECT * 2 FROM products 3 LIMIT ALL OFFSET 5;

That is equivalent to:

Copy
        
1 SELECT * 2 FROM products 3 OFFSET 5;

In both cases, the two queries will retrieve all rows from the products table starting from the sixth row.

If you try to use NULL or ALL in a MySQL query, you will get a syntax error. Similarly, number_offset can be NULL in PostgreSQL but not in MySQL. In PostgreSQL, setting number_offeset to NULL is equivalent to setting it to 0.

MySQL also supports an equivalent and more concise LIMIT OFFSET SQL syntax:

Copy
        
1 SELECT select_list 2 FROM table_name 3 [ WHERE ... ] 4 [ ORDER BY ... ] 5 [ LIMIT [ number_offset , ] number_records ]

For example, take a look at the MySQL query below:

Copy
        
1 SELECT * 2 FROM products 3 LIMIT 2, 5;

That is equivalent to:

Copy
        
1 SELECT * 2 FROM products 3 LIMIT 5 4 OFFSET 2

If you try to use the LIMIT x, y syntax in PostgreSQL, you will receive the following error:

Copy
        
1 [Code: 0, SQL State: 42601] ERROR: LIMIT #,# syntax is not supported 2 Hint: Use separate LIMIT and OFFSET clauses.

SQL Limit: Use Cases

Now that you know what databases support the LIMIT SQL clause and how it works, you are ready to explore its top three use cases.

Note: The sample queries in this section will be written in MySQL and executed in DbVisualizer, the database client with the highest user satisfaction in the market.

1. Implement SQL Pagination

Retrieving all the data in a table at once is slow and inefficient. Plus, displaying all the data on a single page leads to an overwhelming user experience. This is where SQL pagination comes in! That technique allows you to break large result sets into manageable chunks, which is crucial for web applications and APIs. SQL pagination is probably the most common use case for LIMIT.

Assume you have a web page displaying a list of blog posts. You want to display 10 posts per page, giving users the ability to navigate through multiple pages. Retrieve the blog posts for the page n with the following SQL LIMIT OFFSET query:

Copy
        
1 SELECT * 2 FROM posts 3 ORDER BY date_published DESC 4 LIMIT 10 OFFSET (n - 1) * 10;

Thus, you can retrieve the posts for the second page of your blog with:

Copy
        
1 SELECT * 2 FROM posts 3 ORDER BY date DESC 4 LIMIT 10 OFFSET 10;

The result will be:

Note that the result set contains 10 blog posts as desired
Note that the result set contains 10 blog posts as desired

2. Retrieve Top-N Records

Another common use case for LIMIT is to retrieve the top n records based on certain criteria, such as the highest sales, most recent activity, or highest-rated items.

Imagine you want to find the top 5 highest-paid employees in your company. This is how you can retrieve that information:

Copy
        
1 SELECT * 2 FROM employees 3 ORDER BY salary DESC 4 LIMIT 5;
Executing the LIMIT query on DbVisualizer
Executing the LIMIT query on DbVisualizer

Specifically, the SQL LIMIT 1 query is particularly popular because it enables you to get only the first row of a result set.

For example, suppose you wanted to retrieve the highest-paid engineer on your team. The query would be:

Copy
        
1 SELECT * 2 FROM employees 3 WHERE department = "Engineering" 4 ORDER BY salary DESC 5 LIMIT 1;

This time, the result will be:

Note the single result record
Note the single result record

3. Data Sampling

Data sampling involves selecting a random subset of data from a larger dataset for analysis or testing purposes. This technique is useful to quickly analyze a portion of your data without processing the entire dataset.

Now, suppose you want to analyze the demographics of a random sample of 100 customers from your database. You can get that data with the LIMIT query below:

Copy
        
1 SELECT * 2 FROM customers 3 ORDER BY RAND() 4 LIMIT 100;

The ORDER clause sorts the customer records randomly using the RAND() function, which assigns a random floating-point value between 0 and 1 to each row. By sorting the rows based on these random values, the set of results will be sorted randomly. Then, the LIMIT function limits the result set to 100 rows.

Best Practices of the LIMIT SQL Clause

Here are the most important best practices for the LIMIT SQL clause:

  • Always specify a reasonable limit to prevent retrieving an excessive number of rows, which can impact performance and consume unnecessary resources.
  • Combine LIMIT with ORDER BY to ensure consistent and predictable results. Avoid relying on the implicit order of rows returned by a database.
  • Use LIMIT in combination with an appropriate OFFSET to fetch subsets of data efficiently, implementing pagination with a single query.
  • Document the purpose of using LIMIT in your queries with some SQL comments.
  • Try to avoid using OFFSET with large datasets, as it can be inefficient. Instead, consider using keyset pagination techniques or other alternatives for efficient pagination.
  • Be mindful of the performance implications of using LIMIT, especially in queries involving large datasets or complex JOIN queries.
  • Be aware that the behavior of LIMIT may vary slightly between different database systems.

Conclusion

In this guide, you understood what the LIMIT clause is, how databases support it, and how it works. Now you know that the LIMIT clause helps you retrieve only a specific number of records from your queries. Thanks to the examples explored here, you also understood in what scenarios the SQL LIMIT clause comes in handy.

Writing complex queries becomes easier with a database client. DbVisualizer is a powerful database client that supports many DBMS technologies, comes with advanced query optimization functionality, and can generate ERD-like schemas with a single click. Try DbVisualizer for free today!

FAQ

Is there an SQL Server LIMIT clause?

No, SQL Server does not support the LIMIT clause. At the same time, it provides the same functionality via the TOP keyword and OFFSET... FETCH clause. See the documentation for more information.

How to get a single record with an SQL query?

You can get a single record from a query by using an SQL LIMIT 1 statement as follows:

Copy
        
1 SELECT * 2 FROM table_name 3 LIMIT 1;

The LIMIT clause can also define the starting and ending points. Here we count from 0, so if you want to return the second row counting from the top, your LIMIT clause would become LIMIT 1,1 instead of LIMIT 1 (count from 1, return 1.)

Does the LIMIT SQL clause have performance implications?

Yes, the LIMIT SQL clause can have performance implications. When used without proper consideration, especially on large datasets, it may impact query execution time and resource consumption. For efficient querying, it is essential to specify a reasonable limit and combine it with appropriate optimizations. Find out more in our guide on how to write efficient SQL queries.

How can an SQL LIMIT OFFSET query help you write a pagination query?

An SQL LIMIT OFFSET query can facilitate pagination operations by allowing you to retrieve a subset of results starting from a specific offset. This enables you to fetch data in manageable chunks. By adjusting the offset value based on the current page, you can navigate through paginated data efficiently.

What does an SQL LIMIT 1 query do?

An SQL LIMIT 1 query retrieves only the first row from a result set. It is commonly used to quickly check existence or fetch a single value from a table. That query ensures efficient and precise data retrieval for various applications and scenarios, such as finding the best match given some specific criteria.

Dbvis download link img
About the author
Antonello Zanini

Antonello is a software engineer, and often refers to himself as a technology bishop. His mission is to spread knowledge through writing.

The Table Icon
Sign up to receive The Table's roundup
More from the table
Title Author Tags Length Published
title

A Guide To the SQL DECLARE Statement

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SERVER 7 min 2024-12-12
title

SQL Upsert: Inserting a Record If It Does Not Exist

author Antonello Zanini tags MySQL ORACLE POSTGRESQL SQL SQL SERVER 8 min 2024-12-10
title

A Complete Guide to the MySQL COUNT Function

author Antonello Zanini tags MySQL 9 min 2024-12-09
title

How to Find Elements In an Array: PostgreSQL Guide

author Antonello Zanini tags POSTGRESQL 3 min 2024-12-05
title

MySQL Nullable Columns: Everything You Need to Know

author Antonello Zanini tags MySQL 6 min 2024-12-03
title

A Complete Guide to the MySQL GROUP_CONCAT Function

author Antonello Zanini tags Data aggregation MySQL 8 min 2024-12-02
title

How and Why to Add an Index in SQL

author Lukas Vileikis tags MySQL POSTGRESQL Search SQL SQL SERVER 8 min 2024-11-28
title

MySQL 9.0 and the New EXPLAIN Features

author Lukas Vileikis tags MySQL SQL 9 min 2024-11-27
title

Massive SQL DELETE Operations and Database Purging Explained

author Lukas Vileikis tags DELETE SQL 4 min 2024-11-26
title

MySQL CAST: A Guide to the Data Conversion Function

author Antonello Zanini tags MySQL 3 min 2024-11-25

The content provided on dbvis.com/thetable, including but not limited to code and examples, is intended for educational and informational purposes only. We do not make any warranties or representations of any kind. Read more here.

Cookie policy

We use cookies to ensure that we give you the best experience on our website. However you can change your cookie settings at any time in your browser settings. Please find our cookie policy here ↗