Javaexercise.com

Mysql Limit

import mysql.connector
from mysql.connector import errorcode

try:
  
  # Connecting with MySql
  con = mysql.connector.connect(user='root', password='mysql', host='127.0.0.1', database='company')
	
  # Using cursor() method to create cursor object
  cursor = con.cursor()

  # SQL query to update a record.
  sql_query = "SELECT * FROM EMPLOYEE LIMIT 2"

  # Executing query
  cursor.execute(sql_query)

  rows = cursor.fetchall();

  for row in rows:
     print(row)

except mysql.connector.Error as err:
  if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
    print("Your user name or password is incorrect")
  elif err.errno == errorcode.ER_BAD_DB_ERROR:
    print("Database does not exist")
  else:
    print(err)
else:
  con.close()

 

Example: Limit using offset

import mysql.connector
from mysql.connector import errorcode

try:
  
  # Connecting with MySql
  con = mysql.connector.connect(user='root', password='mysql', host='127.0.0.1', database='company')
	
  # Using cursor() method to create cursor object
  cursor = con.cursor()

  # SQL query to update a record.
  sql_query = "SELECT * FROM EMPLOYEE LIMIT 2 OFFSET 1"

  # Executing query
  cursor.execute(sql_query)

  rows = cursor.fetchall();

  for row in rows:
     print(row)

except mysql.connector.Error as err:
  if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
    print("Your user name or password is incorrect")
  elif err.errno == errorcode.ER_BAD_DB_ERROR:
    print("Database does not exist")
  else:
    print(err)
else:
  con.close()

 


Conclusion

Well, in this topic, we have learnt to use limit in MySQL select query. The limit keyword is used to set the limit of select records while reading data from table. For example, a table has 10 rows and we want to get only 5 row then we can set limit to the query to fetch 5 rows only.

In our next topic, we will learn to update table inside this database. Till then keep learning and practice.

 

Previous
Next