Home >>Python Tutorial >Python SQL Query Limit

Python SQL Query Limit

To Limit the Result

This is the python sql query limit module of our entire Python MySQL Tutorial. And while using this programming language, if you wish to limit the number of records that are being returned from a query then you can do that too.

And to accomplish that task it is suggested that you should use the “LIMIT” statement. For example, if you wish to select only the first 5 records that are present in the ‘customers’ table then  

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 )

 

To Start from another Position

If you wish to return the first five records of a table but you also want those returned records to start from the third place or the third record then you can do that too. And to accomplish that task it is recommended that you should use the “OFFSET” keyword. For example  

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 )

With this, we finish the python sql query limit part of our entire Python MySQL Tutorial.


No Sidebar ads