In this Python MySQL LIMIT tutorial, we are going to limit the result returned by the MySQL SELECT statement using Python MySQL Connector.
In the previous tutorial, we have seen a complete article to update the existing record by using the MySQL Update statement.
Make sure you have already installed MySQL connector in your machine using pip as well as create database and table.
Headings of Contents
Python MySQL LIMIT:
Python MySQL LIMIT statement is used to limit the result-set returned by the Python MySQL Select statement.
Example:
In this example, we will select only first 5 rows from the table.
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="root21",
database = "demodb",
port = 3308
)
cursor = mydb.cursor()
cursor.execute('SELECT * from students LIMIT 5')
all_students = cursor.fetchall()
for i in all_students:
print(i)
Output
(1, 'Vishvajit', 12)
(2, 'John', 22)
(3, 'Alex', 40)
(4, 'Peter', 12)
(5, 'Aysha', 40)
Start from another position:
Sometimes you need to select the records from the specific records, Than you can use MySQL OFFSET statement.
Example:
In this example, we want to select only five records from the 4th record.
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="root21",
database = "demodb",
port = 3308
)
cursor = mydb.cursor()
cursor.execute('SELECT * from students LIMIT 5 OFFSET 3')
all_students = cursor.fetchall()
for i in all_students:
print(i)
Output
(4, 'Peter', 12)
(5, 'Aysha', 40)
(6, 'Alsena', 40)
(7, 'Jaini', 56)
(8, 'Saini', 23)
Conclusion:
In this Python MySQL LIMIT tutorial, you have learned all about how to limit the result set returned by the Python MySQL Select statement.
Python MySQL connector is the best for connecting Python applications to the MySQL database and executes SQL queries. After created of database successfully, you can perform a query on that particular database.
If this article is helpful for you, please share and keep visiting for further Python MySQL database tutorials.
Python MySQL Tutorials