Categories: python

Limit Clause – MySQL

In SQL, the Limit clause is used to restrict or control the number of records in the result set that is generated by the query. SQL by default displays the necessary number of records beginning at the top, but it also supports the use of the OFFSET keyword. You can use OFFSET to get the necessary number of result rows by starting from a custom row.

Syntax:

SELECT * FROM tablename LIMIT N;

SELECT * FROM tablename LIMIT N OFFSET offset;

LIMIT N: It’s used to restrict the number of records returned. N here starts at 0, but if you exceed LIMIT 0 ( then it does not return any record).

Example: a program to display only 2 records

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)
Using OFFSET Keyword with LIMIT clause:

By using the OFFSET keyword in the LIMIT query, you can start from any position if you don’t want to start from the first. Let’s look at the corresponding code example:

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)

In the code above, OFFSET 1 indicates that the resultset should start from the first row and LIMIT 2 indicates that only row 2 will be returned.

Note: The OFFSET keyword is used to specify the starting point. For example, if a query returned 100 rows of data and we have specified the OFFSET as 31, then data starting from the 52nd row till the 100th row will be returned.

Note: also read about Order by Clause – MySQL

Follow Me

Please follow me to read my latest post on programming and technology if you like my post.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Recent Posts

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

10 months ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

10 months ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

12 months ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

12 months ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

12 months ago

Binary Search Tree (BST)

A Binary Search Tree (BST) is a type of binary tree that satisfies the following…

12 months ago