Skip to content
Related Articles

Related Articles

Python SQLite – LIMIT Clause

View Discussion
Improve Article
Save Article
  • Last Updated : 27 Apr, 2021
View Discussion
Improve Article
Save Article

In this article, we are going to discuss the LIMIT clause in SQLite using Python. But first, let’s get a brief about the LIMIT clause.

If there are many tuples satisfying the query conditions, it might be resourceful to view only a handful of them at a time. LIMIT keyword is used to limit the data given by the SELECT statement.

Syntax:

         SELECT column1, column2, column n  

         FROM table_name

         LIMIT [no of rows];

where no of rows is an integer value specified as the no of rows to get as output from table.

Let’s create a database.

Python3




# importing sqlite module
import sqlite3
  
# create connection to the database 
# geeks_database
connection = sqlite3.connect('geeks_database.db')
  
# create table named address of customers
# with 4 columns id,name age and address
connection.execute('''CREATE TABLE customer_address
         (ID INT PRIMARY KEY     NOT NULL,
         NAME           TEXT    NOT NULL,
         AGE            INT     NOT NULL,
         ADDRESS        CHAR(50)); ''')
  
# close the connection
connection.close()

Output:

Now, Insert 5 records into the customer_address table.

Python3




# importing sqlite module
import sqlite3
  
# create connection to the database 
# geeks_database
connection = sqlite3.connect('geeks_database.db')
  
# insert records into table
connection.execute(
    "INSERT INTO customer_address VALUES (1, 'nikhil teja', 22, 'hyderabad' )")
  
connection.execute(
    "INSERT INTO customer_address VALUES (2, 'karthik', 25, 'khammam')")
  
connection.execute(
    "INSERT INTO customer_address VALUES (3, 'sravan', 22, 'ponnur' )")
  
connection.execute(
    "INSERT INTO customer_address VALUES (4, 'deepika', 25, 'chebrolu' )")
  
connection.execute(
    "INSERT INTO customer_address VALUES (5, 'jyothika', 22, 'noida')")
  
# close the connection
connection.close()

Output:

After adding data let’s perform the limit operation. In this example, we are going to display the top 4 data from the table.

Python3




# importing sqlite module
import sqlite3
  
# create connection to the database 
# geeks_database
connection = sqlite3.connect('geeks_database.db')
  
# sql query to display top4 data from table
cursor = connection.execute("SELECT * FROM customer_address LIMIT 4")
  
# display data row by row
for i in cursor:
    print(i)
  
# close the connection
connection.close()

Output:

In this way, we can restrict the rows in the output and print the top N rows by setting the LIMIT as N.


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!