The LIMIT clause – Examples with MySQL.

Don’t want all records returned in the query results? Maybe you need pagination for a results set or web app… Many of these requirements can be taken of by applying the LIMIT clause to your query. Let’s look at a few examples here in MySQL…


clint-mckoy-569175-unsplash

Photo by Clint McKoy on Unsplash

Note: All data, names or naming found within the database presented in this post, are strictly used for practice, learning, instruction, and testing purposes. It by no means depicts actual data belonging to or being used by any party or organization.
OS and DB used:

  • Xubuntu Linux 16.04.5 LTS (Xenial Xerus)
  • MySQL 5.7.23

When working with large datasets, there may come a time you do not want all the query result rows returned. Maybe the results set is massive. Or, perhaps you only want to just get a ‘feel’ for the data without fear of loading too much up in memory.

SQL (including MySQL) has a clause to help with this. For these cases (among others), lean on the LIMIT clause to control the number of rows returned.
Example tables used in this blog post are part of the practice Sakila Database.

We have a customer table with these columns:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
mysql> DESC customer;
+-------------+----------------------+------+-----+-------------------+-----------------------------+
| Field       | Type                 | Null | Key | Default           | Extra                       |
+-------------+----------------------+------+-----+-------------------+-----------------------------+
| customer_id | smallint(5) unsigned | NO   | PRI | NULL              | auto_increment              |
| store_id    | tinyint(3) unsigned  | NO   | MUL | NULL              |                             |
| first_name  | varchar(45)          | NO   |     | NULL              |                             |
| last_name   | varchar(45)          | NO   | MUL | NULL              |                             |
| email       | varchar(50)          | YES  |     | NULL              |                             |
| address_id  | smallint(5) unsigned | NO   | MUL | NULL              |                             |
| active      | tinyint(1)           | NO   |     | 1                 |                             |
| create_date | datetime             | NO   |     | NULL              |                             |
| last_update | timestamp            | NO   |     | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+-------------+----------------------+------+-----+-------------------+-----------------------------+
9 rows in set (0.00 sec)

I’ll start with a query to verify how many rows are in table customer:

1
2
3
4
5
6
7
mysql> SELECT COUNT(*) FROM customer;
+----------+
| COUNT(*) |
+----------+
|      599 |
+----------+
1 row in set (0.00 sec)

Although this individual table does not contain thousands or hundreds of thousands of rows, if it did, this could be where the LIMIT clause comes in handy.

Take this common query:

1
2
mysql> SELECT first_name
    -> FROM customer

While this statement is incomplete (and may error if I do not include a semicolon (;)), should I run it without a WHERE clause to possibly filter based on column data, all records will be returned.
Maybe you only want 5 rows. Even if the WHERE clause is used to filter the data.

Here is an example of how the LIMIT clause controls the number of returned rows:

1
2
3
4
5
6
7
8
9
10
11
12
13
mysql> SELECT first_name
    -> FROM customer
    -> LIMIT 5;
+------------+
| first_name |
+------------+
| MARY       |
| PATRICIA   |
| LINDA      |
| BARBARA    |
| ELIZABETH  |
+------------+
5 rows in set (0.03 sec)

Two points worth noting about LIMIT. The LIMIT clause is the last clause executed. Additionally, it is important to mention that potentially, a query can return even less rows than that number specified in said LIMIT clause. E.g., you specify LIMIT 5 but the results set only returns 3 records due to other filters (e.g., WHERE and/or HAVING clauses) already performed in the operation order.

Let’s solidify with an example query:

1
2
3
4
5
6
7
8
9
10
11
mysql> SELECT first_name
     > FROM customer
     > WHERE first_name LIKE 'Y%'
     > LIMIT 5;
+------------+
| first_name |
+------------+
| YVONNE     |
| YOLANDA    |
+------------+
2 rows in set (0.01 sec)

To better understand this, have a look at the same query, but omitting the LIMIT clause:

1
2
3
4
5
6
7
8
9
10
mysql> SELECT first_name
     > FROM customer
     > WHERE first_name LIKE 'Y%';
+------------+
| first_name |
+------------+
| YVONNE     |
| YOLANDA    |
+------------+
2 rows in set (0.00 sec)

These query results do not have more than 2 rows available for LIMIT to ‘act on’.


Mini Information/Educational Resource:

In the list below, I have included links to great blog posts on SQL query execution order I find highly educational and interesting.


An often-seen application of LIMIT is used to return a ‘top row(s)’ results set: e.g., 10 most expensive items, 5 top-selling days, 3 lowest-priced items. Yet, LIMIT needs assistance here from the ORDER BY clause.

For this type of query, the ORDER BY clause is used to order a column (or columns) in ASC (ascending -the default) or DESC (descending) order.

Let’ look at an example query to clarify. Take the amount column from the payment table.
Say we want the highest 5 amount values ordered from greatest to least.
This query will take care of that, but to prohibit duplicates from taking up the top spots in the result set, I’ll use the DISTINCT clause on the amount column.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
mysql> SELECT DISTINCT amount
    -> FROM payment
    -> ORDER BY amount DESC
    -> LIMIT 5;
+--------+
| amount |
+--------+
|  11.99 |
|  10.99 |
|   9.99 |
|   9.98 |
|   8.99 |
+--------+
5 rows in set (0.04 sec)

From the query results, we know firsthand what the top value is, but perhaps we need to know the next continuing five values. LIMIT has another, optional argument.

An OFFSET value.
See this query for an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
mysql> SELECT distinct amount
    -> FROM payment
    -> ORDER BY amount DESC
    -> LIMIT 1, 5;
+--------+
| amount |
+--------+
|  10.99 |
|   9.99 |
|   9.98 |
|   8.99 |
|   8.97 |
+--------+
5 rows in set (0.04 sec)

When including an OFFSET value (for our query 1), that value is the offset from the first row of the results set, which starts at 0 (zero).
In the above query, the rows are returned starting after the first row of the results set.

An allowable syntax can be to explicitly provide the OFFSET value of 0, which is identical to not including a value at all:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
mysql> SELECT DISTINCT amount
     > FROM payment
     > ORDER BY amount DESC
     > LIMIT 0, 5;
+--------+
| amount |
+--------+
|  11.99 |
|  10.99 |
|   9.99 |
|   9.98 |
|   8.99 |
+--------+
5 rows in set (0.07 sec)

Optionally, specifying OFFSET as its own command is allowed in MySQL for compatibility with PostgreSQL.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
mysql> SELECT distinct amount
    -> FROM payment
    -> ORDER BY amount DESC
    -> LIMIT 5
    -> OFFSET 1;
+--------+
| amount |
+--------+
|  10.99 |
|   9.99 |
|   9.98 |
|   8.99 |
|   8.97 |
+--------+
5 rows in set (0.04 sec)

Prior to closing out the blog post, I must make mention that both options for the LIMIT clause must be positive integer constants.

I have included sources for expanded study and reading in the list below. Feel free to leave any comments, thoughts, likes, dislikes, or corrections in the comments below. Thanks for reading.

Further reading and resources:

Explore the official MySQL 5.7 Online Manual for more information.

A Call To Action!

Thank you for taking the time to read this post. I truly hope you discovered something interesting and enlightening. Please share your findings here, with someone else you know who would get the same value out of it as well.

Visit the Portfolio-Projects page to see blog post/technical writing I have completed for clients.

Have I mentioned how much I love a cup of coffee?!?!

To receive email notifications (Never Spam) from this blog (“Digital Owl’s Prose”) for the latest blog posts as they are published, please subscribe (of your own volition) by clicking the ‘Click To Subscribe!’ button in the sidebar on the homepage! (Feel free at any time to review the Digital Owl’s Prose Privacy Policy Page for any questions you may have about: email updates, opt-in, opt-out, contact forms, etc…)

Be sure and visit the “Best Of” page for a collection of my best blog posts.


Josh Otwell has a passion to study and grow as a SQL Developer and blogger. Other favorite activities find him with his nose buried in a good book, article, or the Linux command line. Among those, he shares a love of tabletop RPG games, reading fantasy novels, and spending time with his wife and two daughters.

Disclaimer: The examples presented in this post are hypothetical ideas of how to achieve similar types of results. They are not the utmost best solution(s). The majority, if not all, of the examples provided, are performed on a personal development/learning workstation-environment and should not be considered production quality or ready. Your particular goals and needs may vary. Use those practices that best benefit your needs and goals. Opinions are my own.

Hey thanks for commenting! Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.