Python SQLite – LIMIT Clause
The `LIMIT` clause in SQLite is used to restrict the number of rows returned by a query. It allows you to specify a maximum number of rows to be returned from the result set. In Python, you can use the `LIMIT` clause in conjunction with SQL `SELECT` statements when querying data from SQLite database tables.
Here’s how to use the `LIMIT` clause to restrict the number of rows returned in SQLite using Python:
1. Establish Connection: First, establish a connection to the SQLite database file using the `connect()` function from the `sqlite3` module.
2. Create Cursor: After establishing the connection, create a cursor object using the `cursor()` method.
3. Execute SQL Statement: Use the cursor’s `execute()` method to execute an SQL `SELECT` statement with a `LIMIT` clause. Specify the maximum number of rows to be returned in the `LIMIT` clause.
4. Fetch Data: After executing the SQL statement, fetch the limited data from the cursor using one of the fetch methods (`fetchone()`, `fetchall()`, or `fetchmany()`).
5. Process Data: Process the fetched data as needed.
6. Close Cursor and Connection: Finally, close the cursor and connection using the `close()` method to release any resources associated with them.
Here’s an example of how to use the `LIMIT` clause to restrict the number of rows returned from a table named `employees` to 5:
“`python
import sqlite3
# Establish connection to SQLite database
connection = sqlite3.connect(‘example.db’)
# Create a cursor object
cursor = connection.cursor()
# Execute SQL statement with LIMIT clause
cursor.execute(‘SELECT * FROM employees LIMIT 5’)
# Fetch limited data
rows = cursor.fetchall()
# Process fetched data
for row in rows:
print(row)
# Close cursor and connection
cursor.close()
connection.close()
“`
In this example:
– We establish a connection to an SQLite database file named `example.db`.
– We create a cursor object using the `cursor()` method.
– We execute an SQL `SELECT * FROM employees LIMIT 5` statement with a `LIMIT` clause that specifies returning only the first 5 rows.
– We fetch the limited data using the `fetchall()` method and store it in the `rows` variable.
– We iterate over the rows and print each row.
– Finally, we close the cursor and connection.