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
- Python 3.10 or newer (the sqlite3 module is part of the standard library)
- No database server or extra package is required
- The ->> JSON operator needs SQLite 3.38 or newer; STRICT tables need 3.37 or newer
Steps
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.
bashpython3 -c "import sqlite3; print(sqlite3.sqlite_version)"Expected output3.53.1Open 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.
pythonimport 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',)]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.
pythonrows = [ ("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 output5 rows insertedQuery and aggregate
Filtering, sorting and grouping work as in any SQL database. Setting row_factory to sqlite3.Row lets you read columns by name.
pythoncon.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 outputLaptop 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}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.
pythoncon.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 outputSEARCH products USING INDEX idx_products_category (category=?)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.
pythonfor 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'}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.
pythoncon.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 outputSEARCH products USING INDEX idx_products_color (<expr>=?) ['27-inch monitor', 'Mechanical keyboard']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.
pythontry: 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 outputrolled back: something went wrong mid-update [39.9, 24.0]
Next steps
- Turn on write-ahead logging with PRAGMA journal_mode=WAL for better read/write concurrency
- Try the FTS5 extension for full-text search over text columns
- Read about SQLite's type affinity rules and when STRICT tables help
- Compare SQLite with other embedded engines such as DuckDB for analytical workloads
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
- Getting started with ClickHouse SQL using chDB
- Getting started with DuckDB in Python
- Getting started with LanceDB in Python
- Getting started with PostgreSQL
- Getting started with Redis
Sources
Last verified:
- sqlite.org/docs.html sqlite.org
- docs.python.org/3/library/sqlite3.html docs.python.org
- sqlite.org/json1.html sqlite.org
- sqlite.org/eqp.html sqlite.org
- sqlite.org/stricttables.html sqlite.org
- sqlite.org/expridx.html sqlite.org
Found an error? See how to report a correction.