The Wayback Machine - https://web.archive.org/web/20240121031822/https://www.geeksforgeeks.org/python-mysql-limit-clause/
Open In App
Related Articles

Python MySQL – Limit Clause

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

A connector is employed when we have to use MySQL with other programming languages. The work of mysql-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and MySQL Server.

Python-MySQL-Connector

This is a MySQL Connector that allows Python to access MySQL Driver and implement SQL queries in its programming facility. Here we will try implementing Limit clause on our Database and will study the output generated.

LIMIT Clause Of SQL

The Limit clause is used in SQL to control or limit the number of records in the result set returned from the query generated. By default, SQL gives out the required number of records starting from the top but it allows the use of OFFSET keyword. OFFSET allows you to start from a custom row and get the required number of result rows. 

Syntax:

SELECT * FROM tablename LIMIT limit;

SELECT * FROM tablename LIMIT limit OFFSET offset;

The following programs will help you understand this better. DATABASE IN USE: python-join-db22 

Example 1: program to display only 2 records 

Python3




import mysql.connector
  
# Connecting to the database
mydb = mysql.connector.connect(
  host ='localhost',
  database ='College',
  user ='root',
)
  
cs = mydb.cursor()
 
# STUDENT and STudent are
# two different database
statement ="SELECT * FROM STUDENT LIMIT 2"
 
cs.execute(statement)
result_set = cs.fetchall()
 
for x in result_set:
    print(x)


OUTPUT: python-limit-1 

Example 2:program to start from the second record and display the first two records 

Python3




import mysql.connector
  
# Connecting to the database
mydb = mysql.connector.connect(
  host ='localhost',
  database ='College',
  user ='root',
)
  
cs = mydb.cursor()
 
# STUDENT and STudent are
# two different database
statement ="SELECT * FROM STUDENT LIMIT 2 OFFSET 1"
 
cs.execute(statement)
result_set = cs.fetchall()
 
for x in result_set:
    print(x)


OUTPUT: python-limit-2


Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills, become a part of the hottest trend in the 21st century.
Dive into the future of technology - explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.

Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated : 30 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads
Complete Tutorials