Welcome to another tutorial on Python MySQL. Here, you will learn about Limit Clause, and how to limit the number of rows returned in a given result-set by using the LIMIT CLAUSE that is added to the query in Python.
Below is the general syntax:
SELECT {fieldname(s) | *} FROM tableName(s) [WHERE condition] LIMIT N;
In the example, we will select two rows from the students' table (i.e. the table created in the previous tutorial on create table). This is shown below:
import mysql.connector as mysql
db = mysql.connect(
host = "localhost",
user = "yourusername",
passwd = "yourpassword",
database = "mydatabase1"
)
cursor = db.cursor()
cursor.execute("SELECT * FROM students LIMIT 1")
myresult = cursor.fetchall()
for x in myresult:
print(x)
Output:
('Mike', 'Computer Science', 'London, 1)
In a situation where you do not want to start from the first position, you can use the OFFSET keyword in the LIMIT query to start from any other position. Check out the example below:
import mysql.connector as mysql
db = mysql.connect(
host = "localhost",
user = "yourusername",
passwd = "yourpassword",
database = "mydatabase1"
)
cursor = db.cursor()
cursor.execute("SELECT * FROM students LIMIT 1 OFFSET 1")
myresult = cursor.fetchall()
for x in myresult:
print(x)
Output:
('Michael', 'Computer Science', 'USA', 3)