Python sqlite3 Cheat Sheet

Cheat Sheet for Python's sqlite3 package and basic queries

Download as .pdf

API: /api/v1/cheatsheet/python-sqlite3-cheat-sheet

Import + Connect

python

1
2
3
4
import sqlite3

conn = sqlite3.connect("app.db")
cursor = conn.cursor()

Creates or opens: app.db

In-Memory Database

python

1
conn = sqlite3.connect(":memory:")

Use for: - Testing - Temporary data - Fast disposable DBs

Create Table

python

1
2
3
4
5
6
7
8
9
cursor.execute("""
CREATE TABLE users (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL,
    age INTEGER
)
""")

conn.commit()

Insert One Row

python

1
2
3
4
5
6
cursor.execute(
    "INSERT INTO users (name, age) VALUES (?, ?)",
    ("Alice", 30)
)

conn.commit()

Insert Many Rows

python

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
users = [
    ("Bob", 25),
    ("Carol", 40)
]

cursor.executemany(
    "INSERT INTO users (name, age) VALUES (?, ?)",
    users
)

conn.commit()

Select Data

python

1
2
3
4
5
cursor.execute("SELECT * FROM users")

rows = cursor.fetchall()

print(rows)

Fetch Methods

One Row

python

1
row = cursor.fetchone()

Many Rows

python

1
rows = cursor.fetchmany(10)

All Rows

python

1
rows = cursor.fetchall()

WHERE Clause

python

1
2
3
4
cursor.execute(
    "SELECT * FROM users WHERE age > ?",
    (30,)
)

Update Data

python

1
2
3
4
5
6
cursor.execute(
    "UPDATE users SET age = ? WHERE name = ?",
    (31, "Alice")
)

conn.commit()

Delete Data

python

1
2
3
4
5
6
cursor.execute(
    "DELETE FROM users WHERE name = ?",
    ("Bob",)
)

conn.commit()

Auto Increment ID

id INTEGER PRIMARY KEY

SQLite auto-generates row IDs.

Last Inserted ID

python

1
cursor.lastrowid

Count Rows

python

1
2
3
cursor.execute("SELECT COUNT(*) FROM users")

count = cursor.fetchone()[0]

Order Results

sql

1
SELECT * FROM users ORDER BY age DESC

Limit Results

sql

1
SELECT * FROM users LIMIT 5

Search with LIKE

python

1
2
3
4
cursor.execute(
    "SELECT * FROM users WHERE name LIKE ?",
    ("%Joe%",)
)

Row as Dictionary

python

1
2
3
4
5
6
conn.row_factory = sqlite3.Row

# Then:
row = cursor.fetchone()

print(row["name"])

Transactions

python

1
2
3
4
5
6
7
8
9
conn.execute("BEGIN")

cursor.execute(...)
cursor.execute(...)

conn.commit()

# Rollback:
conn.rollback()
python

1
2
3
4
5
with sqlite3.connect("app.db") as conn:
    conn.execute(
        "INSERT INTO users (name, age) VALUES (?, ?)",
        ("Dave", 22)
    )

Auto commit / rollback.

Create Index

python

1
2
3
cursor.execute(
    "CREATE INDEX idx_users_name ON users(name)"
)

Drop Table

python

1
cursor.execute("DROP TABLE users")

Show Tables

python

1
2
3
4
5
6
cursor.execute("""
SELECT name FROM sqlite_master
WHERE type='table'
""")

print(cursor.fetchall())

Table Schema

python

1
2
cursor.execute("PRAGMA table_info(users)")
print(cursor.fetchall())

Join Example

sql

1
2
3
SELECT users.name, orders.total
FROM users
JOIN orders ON users.id = orders.user_id

Parameterized Queries

Safe:

python

1
2
3
4
cursor.execute(
    "SELECT * FROM users WHERE id = ?",
    (1,)
)

Unsafe:

python

1
2
3
cursor.execute(
    f"SELECT * FROM users WHERE id = {x}"
)

Close Connection

python

1
conn.close()

Common SQLite Types

SQLite Type Meaning
INTEGER Whole numbers
REAL Floating point
TEXT Strings
BLOB Binary data
NULL Missing value

Mini Example

python

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import sqlite3

with sqlite3.connect("notes.db") as conn:
    cur = conn.cursor()

    cur.execute("""
    CREATE TABLE IF NOT EXISTS notes (
        id INTEGER PRIMARY KEY,
        text TEXT
    )
    """)

    cur.execute(
        "INSERT INTO notes (text) VALUES (?)",
        ("Learn sqlite3",)
    )

    cur.execute("SELECT * FROM notes")

    print(cur.fetchall())

Join the Newsletter

Practical insights on Django, backend systems, deployment, architecture, and real-world development — delivered without noise.

Get updates when new guides, learning paths, cheat sheets, and field notes are published.

No spam. Unsubscribe anytime.



There is no third-party involved so don't worry - we won't share your details with anyone.