Getting started with SQLite in Python

SQLite is a self-contained SQL engine that stores a whole database in one file and runs inside your application process. This guide walks through the essentials from Python, and every snippet below was executed to produce the output shown.

Database profile: SQLite (license, deployment options, alternatives and benchmarks).

Prerequisites

Steps

  1. Check that SQLite is available

    Python ships with the sqlite3 module, which embeds the SQLite library, so there is no server to install. Print the library version to see which SQLite release you are running.

    bash
    python3 -c "import sqlite3; print(sqlite3.sqlite_version)"
    Expected output
    3.53.1
  2. Open a database file and create a table

    Connecting to a path creates the database file if it does not exist yet. A table is created with ordinary SQL; here the attrs column will hold JSON text.

    python
    import sqlite3
    
    con = sqlite3.connect("shop.db")
    con.execute("""
        CREATE TABLE products (
            id       INTEGER PRIMARY KEY,
            name     TEXT NOT NULL,
            category TEXT NOT NULL,
            price    REAL NOT NULL,
            attrs    TEXT              -- JSON document
        ) STRICT
    """)
    print(con.execute("SELECT name FROM sqlite_master WHERE type = 'table'").fetchall())
    Expected output
    [('products',)]
  3. Insert rows with parameters

    Use ? placeholders instead of string formatting so values are escaped safely. Writes happen inside a transaction, so call commit() to make them durable.

    python
    rows = [
        ("Mechanical keyboard", "peripherals", 89.0, '{"color": "black", "switch": "brown", "wireless": false}'),
        ("Wireless mouse",      "peripherals", 29.5, '{"color": "white", "wireless": true}'),
        ("27-inch monitor",     "displays",   249.0, '{"color": "black", "resolution": "2560x1440"}'),
        ("USB-C hub",           "accessories", 39.9, '{"ports": ["hdmi", "usb-a", "sd"]}'),
        ("Laptop stand",        "accessories", 24.0, '{"color": "silver"}'),
    ]
    con.executemany(
        "INSERT INTO products (name, category, price, attrs) VALUES (?, ?, ?, ?)", rows
    )
    con.commit()
    print(con.execute("SELECT count(*) FROM products").fetchone()[0], "rows inserted")
    Expected output
    5 rows inserted
  4. Query and aggregate

    Filtering, sorting and grouping work as in any SQL database. Setting row_factory to sqlite3.Row lets you read columns by name.

    python
    con.row_factory = sqlite3.Row
    for r in con.execute("SELECT name, price FROM products WHERE price < ? ORDER BY price", (50,)):
        print(r["name"], r["price"])
    
    for r in con.execute("""
        SELECT category, count(*) AS n, round(avg(price), 2) AS avg_price
        FROM products GROUP BY category ORDER BY category
    """):
        print(dict(r))
    Expected output
    Laptop stand 24.0
    Wireless mouse 29.5
    USB-C hub 39.9
    {'category': 'accessories', 'n': 2, 'avg_price': 31.95}
    {'category': 'displays', 'n': 1, 'avg_price': 249.0}
    {'category': 'peripherals', 'n': 2, 'avg_price': 59.25}
  5. Add an index and confirm it is used

    An index on a frequently filtered column avoids a full table scan. EXPLAIN QUERY PLAN shows whether SQLite picks the index for a query.

    python
    con.execute("CREATE INDEX idx_products_category ON products(category)")
    plan = con.execute(
        "EXPLAIN QUERY PLAN SELECT name FROM products WHERE category = ?", ("displays",)
    ).fetchall()
    for row in plan:
        print(row["detail"])
    Expected output
    SEARCH products USING INDEX idx_products_category (category=?)
  6. Read JSON with the built-in JSON functions

    SQLite can parse JSON stored in text columns. The ->> operator extracts a value as plain SQL text or number, and json_each turns a JSON array into rows you can join against.

    python
    for r in con.execute("""
        SELECT name, attrs ->> '$.color' AS color
        FROM products
        WHERE attrs ->> '$.wireless' = 1
    """):
        print(dict(r))
    
    for r in con.execute("""
        SELECT p.name, port.value AS port
        FROM products AS p, json_each(p.attrs, '$.ports') AS port
    """):
        print(dict(r))
    Expected output
    {'name': 'Wireless mouse', 'color': 'white'}
    {'name': 'USB-C hub', 'port': 'hdmi'}
    {'name': 'USB-C hub', 'port': 'usb-a'}
    {'name': 'USB-C hub', 'port': 'sd'}
  7. Index a JSON field

    An expression index can cover a value inside the JSON document, so lookups by that field no longer need to scan and parse every row.

    python
    con.execute("CREATE INDEX idx_products_color ON products(attrs ->> '$.color')")
    for row in con.execute(
        "EXPLAIN QUERY PLAN SELECT name FROM products WHERE attrs ->> '$.color' = 'black'"
    ):
        print(row["detail"])
    print([r["name"] for r in con.execute(
        "SELECT name FROM products WHERE attrs ->> '$.color' = 'black' ORDER BY name")])
    Expected output
    SEARCH products USING INDEX idx_products_color (<expr>=?)
    ['27-inch monitor', 'Mechanical keyboard']
  8. Use a transaction for safe multi-step changes

    Using the connection as a context manager commits on success and rolls back if an exception escapes, so partial updates never persist.

    python
    try:
        with con:
            con.execute("UPDATE products SET price = price * 0.9 WHERE category = 'accessories'")
            raise RuntimeError("something went wrong mid-update")
    except RuntimeError as e:
        print("rolled back:", e)
    
    print([r["price"] for r in con.execute(
        "SELECT price FROM products WHERE category = 'accessories' ORDER BY id")])
    con.close()
    Expected output
    rolled back: something went wrong mid-update
    [39.9, 24.0]

Next steps

FAQ

Do I need to install a server to use SQLite?
No. SQLite is a library linked into the program that uses it, and the database is a regular file on disk. Python, most mobile platforms and many languages bundle it already.
Can several processes use the same SQLite file at once?
Yes, many readers can work in parallel, but only one writer can commit at a time. WAL mode lets readers continue while a write is in progress, which suits most small and medium applications.
Does SQLite have a JSON column type?
JSON is stored as TEXT (or as the binary JSONB format in newer releases), and built-in functions such as json_extract, json_each and the -> and ->> operators read and modify it. Expression indexes can make queries on JSON fields fast.

More tested tutorials

All tutorials

Sources

Last verified:

  1. sqlite.org/docs.html sqlite.org
  2. docs.python.org/3/library/sqlite3.html docs.python.org
  3. sqlite.org/json1.html sqlite.org
  4. sqlite.org/eqp.html sqlite.org
  5. sqlite.org/stricttables.html sqlite.org
  6. sqlite.org/expridx.html sqlite.org

Found an error? See how to report a correction.