Python Tutorial
Python MySQL - Limit
Restrict how many rows a query returns, and page through large result sets.
Limit the Number of Rows
LIMIT caps how many rows come back — essential for previews and "top N" lists.
import mysql.connector
conn = mysql.connector.connect(
host="localhost", user="root", password="secret", database="mydatabase")
cursor = conn.cursor()
cursor.execute("SELECT * FROM customers LIMIT 5")
print(cursor.fetchall()) # at most 5 rowsStart From an Offset
Add OFFSET to skip rows — the basis of pagination.
cursor.execute("SELECT * FROM customers LIMIT 5 OFFSET 3")
# skip the first 3 rows, then return the next 5
# older syntax: LIMIT offset, count
cursor.execute("SELECT * FROM customers LIMIT 3, 5") # same resultPagination Pattern
Compute the offset from a page number and page size. Always pair LIMIT with ORDER BY so pages are consistent.
def get_page(cursor, page, per_page=10):
offset = (page - 1) * per_page
cursor.execute(
"SELECT id, name FROM customers ORDER BY id LIMIT %s OFFSET %s",
(per_page, offset))
return cursor.fetchall()
print(get_page(cursor, page=2, per_page=10)) # rows 11-20Unlike column names, LIMIT/OFFSET accept parameters (%s) in the connector — keep passing them as parameters, not string-formatted.
Top N With ORDER BY
cursor.execute(
"SELECT name, amount FROM orders ORDER BY amount DESC LIMIT 3")
# the three largest ordersKeyset Pagination for Big Tables
Large OFFSET values get slow because MySQL still scans and discards the skipped rows. For deep pages, remember the last id and filter instead — "keyset" (seek) pagination.
last_id = 20 # last id seen on the previous page
cursor.execute(
"SELECT id, name FROM customers WHERE id > %s ORDER BY id LIMIT %s",
(last_id, 10)) # jumps straight to the next 10 rowsBest Practices
- Always combine
LIMITwithORDER BYfor stable, repeatable pages. - Use
LIMITin development to avoid pulling millions of rows by accident. - Prefer keyset pagination over large offsets on big tables.
- Pass limit and offset as parameters.
Try It Yourself
Exercise 1: Fetch rows 11–20 (page 2, 10 per page) ordered by id.
Show solution
cursor.execute(
"SELECT * FROM customers ORDER BY id LIMIT %s OFFSET %s",
(10, 10))Exercise 2: Why is a huge OFFSET slow, and what is the fix?
Show solution
MySQL still scans and discards all skipped rows. Use keyset pagination — filter WHERE id > last_seen_id instead.
📘 Real-World Deep Dive
Knowing <strong>MySQL Limit (MySQL)</strong> well is what turns MySQL from a curiosity into a daily tool — you'll reach for it in nearly every real project.
Real-Life Scenario
An end-to-end usage of MySQL Limit that you'd actually see in a data pipeline or analytics notebook.
Real-Life Example
SELECT id, name FROM users ORDER BY id DESC LIMIT 10 OFFSET 0;Expected Output
(no output)Common mistakes
- Reading with the default cursor returns tuples — switch to
DictCursorfor named access. - Strings without parameter binding produce SQL-injection holes — never use f-strings in queries.
- Connecting through a long-lived daemon pool: make sure
pool_reset_connectionis on to avoid session state leakage. - Treating MySQL Limit as a black box without reading the docs — the API has subtle defaults that bite when you scale.
🚀 Performance & Best Practices
- Use prepared statements (
cursor.executemany) for bulk inserts. - Fetch with
cursor.fetchmany(1000)in streams instead offetchall(). - Use
pymysql's server-side cursors for very large result sets. - When working with MySQL, prefer vectorised / batched operations over Python loops.
🧪 Try It Yourself
- Reproduce the snippet on a representative slice of your own data.
- Profile the snippet with
cProfileortimeitand find the single biggest improvement. - Generalise the snippet into a small, reusable function you can drop into future projects.