Python MySQL Limit

Limited Results

You can use the "LIMIT" statement to limit the number of records returned from the query:

Example

Select the first five records from the "customers" table:

import mysql.connector
mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  passwd="yourpassword",
  database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers LIMIT 5")
myresult = mycursor.fetchall()
for x in myresult:
  print(x)

Run Instance

Start from another location

If you want to return five records starting from the third record, you can use the "OFFSET" keyword:

Example

Return 5 records starting from position 3:

import mysql.connector
mydb = mysql.connector.connect(
  host="localhost",
  user="yourusername",
  passwd="yourpassword",
  database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers LIMIT 5 OFFSET 2")
myresult = mycursor.fetchall()
for x in myresult:
  print(x)

Run Instance