Python How to Execute SQL Query with sqlite3 Example
sqlite3 module by connecting to a database with sqlite3.connect(), creating a cursor with conn.cursor(), then run your SQL query using cursor.execute(sql_query).Examples
How to Think About It
Algorithm
Code
import sqlite3 conn = sqlite3.connect(':memory:') # Create in-memory database cursor = conn.cursor() cursor.execute('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)') cursor.execute("INSERT INTO users (name) VALUES ('Alice'), ('Bob')") conn.commit() cursor.execute('SELECT * FROM users') rows = cursor.fetchall() print(rows) cursor.close() conn.close()
Dry Run
Let's trace the example where we create a table, insert data, and select all rows.
Connect to database
conn is a connection to an in-memory database.
Create cursor
cursor is created to execute SQL commands.
Create table
Execute SQL: CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)
Insert data
Execute SQL: INSERT INTO users (name) VALUES ('Alice'), ('Bob')
Commit changes
Save changes to the database.
Select data
Execute SQL: SELECT * FROM users
Fetch results
rows = [(1, 'Alice'), (2, 'Bob')]
Close resources
Close cursor and connection.
| Step | SQL Command | Result |
|---|---|---|
| 3 | CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT) | Table created |
| 4 | INSERT INTO users (name) VALUES ('Alice'), ('Bob') | 2 rows inserted |
| 6 | SELECT * FROM users | [(1, 'Alice'), (2, 'Bob')] |
Why This Works
Step 1: Connect to database
The sqlite3.connect() function opens a connection to the database file or memory.
Step 2: Create cursor
The cursor lets you send SQL commands to the database.
Step 3: Execute and fetch
Use cursor.execute() to run SQL, and cursor.fetchall() to get results.
Alternative Approaches
from sqlalchemy import create_engine, text engine = create_engine('sqlite:///:memory:') with engine.connect() as conn: conn.execute(text('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)')) conn.execute(text("INSERT INTO users (name) VALUES ('Alice'), ('Bob')")) result = conn.execute(text('SELECT * FROM users')) print(result.fetchall())
import sqlite3 import pandas as pd conn = sqlite3.connect(':memory:') cursor = conn.cursor() cursor.execute('CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)') cursor.execute("INSERT INTO users (name) VALUES ('Alice'), ('Bob')") conn.commit() df = pd.read_sql_query('SELECT * FROM users', conn) print(df) cursor.close() conn.close()
Complexity: O(n) time, O(n) space
Time Complexity
Executing an SQL query depends on the query and data size; fetching results is O(n) where n is number of rows returned.
Space Complexity
Space depends on the size of fetched data stored in memory; the connection and cursor use minimal fixed space.
Which Approach is Fastest?
Using sqlite3 directly is fastest for simple queries; SQLAlchemy adds overhead but offers flexibility; pandas is slower but great for data analysis.
| Approach | Time | Space | Best For |
|---|---|---|---|
| sqlite3 module | O(n) | O(n) | Simple, direct SQL execution |
| SQLAlchemy ORM | O(n) + overhead | O(n) | Complex apps, multiple DBs |
| pandas read_sql_query | O(n) + overhead | O(n) | Data analysis with DataFrames |
conn.commit() after INSERT, UPDATE, or DELETE to save changes.