ποΈ SQLite & Databases
in Python
Learn SQL and Python's sqlite3 module: CRUD, parameterised queries, SQL injection, joins, GROUP BY, indexes, transactions and a first look at SQLAlchemy, all runnable.
What this lesson is about
Almost every real application needs to remember things after it stops running: user accounts, orders, notes, scores, settings. A database is the tool built for that job, and SQLite is the easiest one to start with because it is a single file (or even just memory) and ships inside Python itself. There is no server to install, no password to configure and nothing to start before you write your first query.
SQLite is not a toy, either. It runs inside phones, browsers and desktop programs, and it is a perfectly good choice for small and medium web apps, command-line tools, caches and data analysis scratch space. The skills you learn here, which are really SQL skills, carry over almost unchanged to PostgreSQL and MySQL, so this lesson is an investment in a language you will use for your whole career.
I have organised the page as a path. We create a table and run queries, then cover the four CRUD operations, then the most important safety rule in the whole subject (parameterised queries versus SQL injection). After that come row objects, joins, aggregates, indexes, transactions, and finally a short, static look at SQLAlchemy's ORM. Every example except the last uses an in-memory database, so you can press Run in your browser and experiment freely.
What you will learn
- βCreate tables, insert rows and select data with SQL through
sqlite3 - βPerform create, read, update and delete operations and check how many rows changed
- βUse
?placeholders so user input can never rewrite your query - βRead rows by column name with
sqlite3.Row - βCombine tables with foreign keys and
JOIN - βSummarise data with
COUNT,SUM,AVG,GROUP BYandHAVING - βSpeed up lookups with indexes and confirm it with
EXPLAIN QUERY PLAN - βGroup changes into transactions, roll back on failure and use
withfor safety
Why programmers should learn this
- β Nearly every backend job involves a relational database, and SQL is one of the most durable skills in the industry: it has been in use for decades and is still everywhere.
- β Storing data in tables with constraints stops whole classes of bugs (duplicate emails, orphaned orders) that are painful to prevent with plain files or lists.
- β Understanding parameterised queries protects you from SQL injection, one of the best-known and most damaging web security flaws.
- β SQLite needs no setup, so it is ideal for prototypes, tests, desktop tools and data exploration before you ever need a bigger database server.
- β Knowing transactions and indexes explains why some programs corrupt data or crawl at scale while others stay correct and fast.
Tables, rows and your first queries
A relational database stores data in tables. A table has named columns (each with a type such as INTEGER or TEXT) and any number of rows. You talk to the database in SQL, a language made of statements like CREATE TABLE, INSERT, SELECT, UPDATE and DELETE. Python's sqlite3 module opens a connection, hands you a cursor, and sends your SQL text to the engine.
sqlite3.connect(':memory:') creates a database that lives only in RAM and disappears when the program ends, which is perfect for learning and for tests. Passing a filename such as 'app.db' instead creates a real file on disk. Everything else in this lesson works identically for both.
Two details are worth noticing straight away. First, the PRIMARY KEY column uniquely identifies each row; in SQLite an INTEGER PRIMARY KEY numbers itself automatically. Second, executemany runs one statement for a whole list of value tuples, which is the tidy way to insert many rows. A SELECT gives you a cursor you can iterate or ask for fetchall().
import sqlite3
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute("""
CREATE TABLE books (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
author TEXT NOT NULL,
year INTEGER,
price REAL
)
""")
rows = [
("Dune", "Frank Herbert", 1965, 9.99),
("Neuromancer", "William Gibson", 1984, 8.50),
("Hyperion", "Dan Simmons", 1989, 10.25),
("Snow Crash", "Neal Stephenson", 1992, 7.75),
]
cur.executemany("INSERT INTO books (title, author, year, price) VALUES (?, ?, ?, ?)", rows)
conn.commit()
for row in cur.execute("SELECT id, title, year FROM books ORDER BY year"):
print(row)
print(cur.execute("SELECT COUNT(*) FROM books").fetchone())
print(cur.execute("SELECT title FROM books WHERE price < 9").fetchall())
conn.close()(1, 'Dune', 1965)
(2, 'Neuromancer', 1984)
(3, 'Hyperion', 1989)
(4, 'Snow Crash', 1992)
(4,)
[('Neuromancer',), ('Snow Crash',)]Line by line
- 1
sqlite3is part of the standard library, so there is nothing to install. - 3-4Open an in-memory database and get a cursor, the object that sends SQL and holds results.
- 6-13
CREATE TABLEdefines the columns and their types.NOT NULLforbids empty titles and authors;idnumbers itself. - 15-20A list of tuples, one per book. The order matches the columns named in the INSERT.
- 21-22
executemanyruns the INSERT once per tuple. The four?marks are placeholders filled from each tuple.commit()makes the change permanent. - 24-25Iterating directly over
execute(...)yields rows as tuples.ORDER BY yearsorts them. - 27
fetchone()returns a single row.COUNT(*)gives a one-column row, hence the tuple(4,). - 28
fetchall()returns a list of every remaining row; theWHEREclause filters to books under 9. - 29Close the connection when you are finished with it.
SQL keywords are case-insensitive, but writing them in capitals and your own names in lowercase makes queries much easier to read.
CRUD: create, read, update, delete
Almost every database feature in an app boils down to four verbs: Create (INSERT), Read (SELECT), Update (UPDATE) and Delete (DELETE). Learning to write these four well covers a surprising amount of real work. I like to wrap them in small Python functions, because then the SQL lives in one place and the rest of the program just calls add_task or complete_task.
After a write, two attributes on the cursor are very useful. cursor.lastrowid tells you the id the database just assigned to your new row, and cursor.rowcount tells you how many rows an UPDATE or DELETE actually touched. A rowcount of zero is the clean way to notice that nothing matched, for example when someone tries to delete an id that does not exist.
The one rule I want you to burn in is that UPDATE and DELETE without a WHERE clause affect *every row*. Always write the WHERE first, and when you are experimenting, run the equivalent SELECT beforehand to see which rows you are about to change.
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE tasks (id INTEGER PRIMARY KEY, title TEXT NOT NULL, done INTEGER NOT NULL DEFAULT 0)")
def add_task(title):
cur = conn.execute("INSERT INTO tasks (title) VALUES (?)", (title,))
conn.commit()
return cur.lastrowid
def complete_task(task_id):
cur = conn.execute("UPDATE tasks SET done = 1 WHERE id = ?", (task_id,))
conn.commit()
return cur.rowcount
def delete_task(task_id):
cur = conn.execute("DELETE FROM tasks WHERE id = ?", (task_id,))
conn.commit()
return cur.rowcount
a = add_task("Write lesson")
b = add_task("Review code")
c = add_task("Deploy site")
print("new ids:", a, b, c)
print("completed:", complete_task(b))
print("completed missing id:", complete_task(99))
print("deleted:", delete_task(c))
for row in conn.execute("SELECT id, title, done FROM tasks ORDER BY id"):
print(row)new ids: 1 2 3 completed: 1 completed missing id: 0 deleted: 1 (1, 'Write lesson', 0) (2, 'Review code', 1)
Line by line
- 4A
DEFAULTvalue means new rows start withdone = 0unless told otherwise. - 6-9
add_taskinserts and returnslastrowid, the primary key SQLite just generated. Note the one-element tuple(title,): the trailing comma matters. - 11-14
complete_taskupdates exactly one row chosen byWHERE id = ?and returns how many rows changed. - 16-19
delete_taskremoves a row and also reports the row count. - 21-23Create three tasks and print their ids (1, 2, 3).
- 25-27Completing id 99 returns 0 because no row matched, which is how you detect a missing record.
- 29-30Read everything back to confirm the final state: task 3 is gone and task 2 is marked done.
conn.execute(...) is a shortcut that creates a cursor for you. It is fine for short scripts; keep an explicit cursor when you want finer control.
Parameterised queries and SQL injection
Never build SQL by pasting user text into a string with an f-string or +. If a user's text becomes part of the SQL *code*, they can change what the query does. This is SQL injection, and it has caused many serious data breaches. The attacker does not need to be clever: typing ' OR '1'='1 into a login box is the classic demonstration.
The fix is simple and always available: parameterised queries. You write the SQL with ? placeholders and pass the values separately as a tuple. The database receives the statement and the data through different channels, so data can never be interpreted as code, whatever characters it contains. You do not need to escape quotes yourself, and you should not try.
Placeholders work for *values* only. You cannot use ? for a table or column name. If you must choose a column dynamically, for example sorting by a user-selected field, check the name against a hard-coded allow-list in Python and only then insert it into the string. The example below runs both versions side by side so you can see the unsafe one leak every row.
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE users (name TEXT, secret TEXT)")
conn.executemany("INSERT INTO users VALUES (?, ?)", [
("ana", "pw-ana"), ("ben", "pw-ben"), ("cai", "pw-cai"),
])
evil = "nobody' OR '1'='1"
unsafe_sql = f"SELECT name FROM users WHERE name = '{evil}'"
print(unsafe_sql)
print("unsafe returns:", conn.execute(unsafe_sql).fetchall())
safe = conn.execute("SELECT name FROM users WHERE name = ?", (evil,)).fetchall()
print("safe returns:", safe)
ALLOWED_SORTS = {"name", "secret"}
def list_users(sort_by):
if sort_by not in ALLOWED_SORTS:
raise ValueError("bad sort column")
return conn.execute(f"SELECT name FROM users ORDER BY {sort_by}").fetchall()
print(list_users("name"))
try:
list_users("name; DROP TABLE users")
except ValueError as e:
print("rejected:", e)SELECT name FROM users WHERE name = 'nobody' OR '1'='1'
unsafe returns: [('ana',), ('ben',), ('cai',)]
safe returns: []
[('ana',), ('ben',), ('cai',)]
rejected: bad sort columnLine by line
- 4-7A small users table with three rows to protect.
- 9A malicious 'name'. The first quote closes the string early, and
OR '1'='1'is always true. - 11-13The unsafe f-string version produces SQL that matches every row, so it leaks all three users.
- 15-16The parameterised version sends the text as data, so the database looks for a user literally named
nobody' OR '1'='1and finds none. - 18-23Column names cannot be placeholders. An allow-list check makes the f-string safe because only known names can ever reach the SQL.
- 25-29The legitimate sort works; the injection attempt is rejected before it reaches the database.
The same rule applies to every database library in every language. If you see an f-string or % formatting inside execute(), treat it as a bug until proven otherwise.
Reading rows by name with row_factory
By default rows come back as plain tuples, so you must remember that column 2 is the year. That is fragile: reorder the columns in your SELECT and the code silently reads the wrong field. Setting conn.row_factory = sqlite3.Row makes each row behave like a read-only mapping that also supports index access, so row['title'] works.
sqlite3.Row objects are efficient and print compactly, but they are not dictionaries. To turn one into a real dict for JSON output, use dict(row). You can also write your own factory function that receives the cursor and the raw tuple, for instance to build dataclass instances, but sqlite3.Row is enough for most programs.
It also helps to know the three ways to pull results. Iterating a cursor streams rows one at a time without loading everything, fetchone() returns the next row or None, and fetchall() returns a list. For a query that might return millions of rows, iterate or use fetchmany(n) rather than fetchall().
import sqlite3, json
conn = sqlite3.connect(":memory:")
conn.row_factory = sqlite3.Row
conn.execute("CREATE TABLE planets (name TEXT, moons INTEGER, gas_giant INTEGER)")
conn.executemany("INSERT INTO planets VALUES (?, ?, ?)", [
("Mars", 2, 0), ("Jupiter", 95, 1), ("Saturn", 146, 1), ("Earth", 1, 0),
])
row = conn.execute("SELECT * FROM planets WHERE name = ?", ("Jupiter",)).fetchone()
print(row["name"], row[1], row.keys())
print(dict(row))
cur = conn.execute("SELECT name, moons FROM planets ORDER BY moons DESC")
print(cur.fetchone()["name"])
print([r["name"] for r in cur.fetchmany(2)])
missing = conn.execute("SELECT * FROM planets WHERE name = ?", ("Pluto",)).fetchone()
print(missing)
data = [dict(r) for r in conn.execute("SELECT name, moons FROM planets WHERE gas_giant = 1 ORDER BY name")]
print(json.dumps(data))Jupiter 95 ['name', 'moons', 'gas_giant']
{'name': 'Jupiter', 'moons': 95, 'gas_giant': 1}
Saturn
['Jupiter', 'Mars']
None
[{"name": "Jupiter", "moons": 95}, {"name": "Saturn", "moons": 146}]Line by line
- 4Assigning
sqlite3.Rowas the factory means every result row supports name access. - 9-11Look up by name or by position, list the column names with
keys(), and convert to an ordinary dict. - 13-15
fetchone()takes the first row;fetchmany(2)then takes the next two, so the cursor remembers where it is. - 17-18When nothing matches,
fetchone()returnsNone, so check for it before indexing. - 20-21A list comprehension converts each row to a dict, ready for
json.dumps.
Relating tables: foreign keys and joins
Good database design avoids repeating data. Instead of writing an author's full name on every book, you store authors in one table and give each book an author_id that refers to it. That column is a foreign key. The data is stored once, can be corrected in one place, and the relationship is explicit.
To read the data back together you use a JOIN. An INNER JOIN keeps only rows that have a match on both sides. A LEFT JOIN keeps every row from the left table and fills the missing side with NULL, which is the way to find authors who have no books yet. The ON clause says which columns must match.
SQLite has a quirk worth knowing: it does not enforce foreign keys unless you switch them on for each connection with PRAGMA foreign_keys = ON. Once enabled, inserting a book that points at a non-existent author raises sqlite3.IntegrityError, which is exactly the protection you want.
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("PRAGMA foreign_keys = ON")
conn.executescript("""
CREATE TABLE authors (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE books (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
author_id INTEGER NOT NULL REFERENCES authors(id)
);
INSERT INTO authors (id, name) VALUES (1, 'Ursula Le Guin'), (2, 'Octavia Butler'), (3, 'Newcomer');
INSERT INTO books (title, author_id) VALUES
('A Wizard of Earthsea', 1), ('The Dispossessed', 1), ('Kindred', 2);
""")
print("INNER JOIN")
q = """SELECT a.name, b.title FROM books b
JOIN authors a ON a.id = b.author_id ORDER BY a.name, b.title"""
for row in conn.execute(q):
print(" ", row)
print("LEFT JOIN")
q = """SELECT a.name, b.title FROM authors a
LEFT JOIN books b ON b.author_id = a.id ORDER BY a.name, b.title"""
for row in conn.execute(q):
print(" ", row)
try:
conn.execute("INSERT INTO books (title, author_id) VALUES ('Ghost', 42)")
except sqlite3.IntegrityError as e:
print("blocked:", e)INNER JOIN
('Octavia Butler', 'Kindred')
('Ursula Le Guin', 'A Wizard of Earthsea')
('Ursula Le Guin', 'The Dispossessed')
LEFT JOIN
('Newcomer', None)
('Octavia Butler', 'Kindred')
('Ursula Le Guin', 'A Wizard of Earthsea')
('Ursula Le Guin', 'The Dispossessed')
blocked: FOREIGN KEY constraint failedLine by line
- 4Turn on foreign-key enforcement. SQLite leaves it off by default, and the setting is per connection.
- 5-15
executescriptruns several statements at once.REFERENCES authors(id)declares the foreign key, then we add three authors and three books. - 17-21
INNER JOINpairs each book with its author using theONcondition. The aliasesaandbshorten the query. Newcomer has no books, so does not appear. - 23-27
LEFT JOINstarts from authors, so Newcomer appears withNone(SQLNULL) in the title column. - 29-32Inserting a book for author 42 violates the foreign key, so SQLite raises
IntegrityErrorand the bad row never lands.
Aggregates, GROUP BY and HAVING
An aggregate function collapses many rows into one value: COUNT, SUM, AVG, MIN and MAX. On their own they summarise a whole table. Combined with GROUP BY they summarise each *group* separately, so 'total sales' becomes 'total sales per region'. This is the SQL equivalent of a pivot table, and it is often faster to let the database do it than to pull all rows into Python.
There are two filters and they run at different moments. WHERE removes individual rows *before* grouping; HAVING removes whole groups *after* aggregation. If you want 'only regions whose total exceeds 100', that is a HAVING, because the total does not exist until the groups are formed.
Remember to give computed columns a readable alias with AS, and to add ORDER BY whenever the output order matters: without it SQL makes no promise about order, even if the rows happen to come back sorted today.
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE sales (region TEXT, product TEXT, units INTEGER, price REAL)")
conn.executemany("INSERT INTO sales VALUES (?, ?, ?, ?)", [
("north", "pen", 10, 1.5), ("north", "book", 3, 12.0),
("south", "pen", 25, 1.5), ("south", "book", 1, 12.0),
("east", "pen", 4, 1.5), ("east", "lamp", 2, 30.0),
])
print(conn.execute("SELECT COUNT(*), SUM(units), MAX(price) FROM sales").fetchone())
q = """
SELECT region, SUM(units * price) AS revenue, COUNT(*) AS lines
FROM sales
GROUP BY region
ORDER BY revenue DESC
"""
for row in conn.execute(q):
print(row)
q = """
SELECT region, SUM(units * price) AS revenue
FROM sales
WHERE product != 'lamp'
GROUP BY region
HAVING revenue > 50
ORDER BY region
"""
print(conn.execute(q).fetchall())
print(conn.execute("SELECT ROUND(AVG(price), 2) FROM sales").fetchone()[0])(6, 45, 30.0)
('east', 66.0, 2)
('north', 51.0, 2)
('south', 49.5, 2)
[('north', 51.0)]
9.75Line by line
- 4-9Six sales lines across three regions.
- 11Without
GROUP BY, aggregates return one row for the whole table: 6 lines, 45 units in total, highest price 30. - 13-21Group by region; each group gets a revenue total and a line count.
ORDER BY revenue DESCranks the biggest first. - 23-31
WHEREfirst drops the lamp row, then the rows are grouped, thenHAVINGkeeps only groups whose revenue exceeds 50. - 32
ROUND(AVG(price), 2)averages every price and rounds to two decimals.
Indexes and EXPLAIN QUERY PLAN
Without help, a query such as WHERE email = ? must examine every row in the table: a full scan. That is fine for a hundred rows and painful for ten million. An index is a separate, sorted structure (a B-tree) that lets the database jump straight to matching rows, much like a book's index lets you jump to a page instead of reading every chapter.
Indexes are not free. They take disk space and make every INSERT and UPDATE slightly slower, because the index must be maintained too. So I add them for columns that are used often in WHERE, JOIN and ORDER BY clauses, not on every column. A UNIQUE constraint creates an index automatically as a bonus, which is how the database enforces uniqueness quickly.
You do not have to guess whether an index is used. Prefix a query with EXPLAIN QUERY PLAN and SQLite describes its strategy: a line starting with SCAN means a full table scan, while SEARCH ... USING INDEX means the index is working. The exact wording differs slightly between SQLite versions, so the example below prints only stable facts about the plan rather than the raw text.
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE people (id INTEGER PRIMARY KEY, email TEXT, city TEXT)")
conn.executemany(
"INSERT INTO people (email, city) VALUES (?, ?)",
[(f"user{i}@example.com", "Manila" if i % 2 else "Cebu") for i in range(2000)],
)
def plan(sql, params=()):
rows = conn.execute("EXPLAIN QUERY PLAN " + sql, params).fetchall()
detail = " ".join(r[3] for r in rows)
return {
"uses_index": "USING INDEX" in detail or "USING COVERING INDEX" in detail,
"full_scan": detail.lstrip().startswith("SCAN"),
}
query = "SELECT id FROM people WHERE email = ?"
print("before:", plan(query, ("user77@example.com",)))
conn.execute("CREATE INDEX idx_people_email ON people(email)")
print("after: ", plan(query, ("user77@example.com",)))
print(conn.execute(query, ("user77@example.com",)).fetchone())
print("city lookup:", plan("SELECT id FROM people WHERE city = ?", ("Cebu",)))before: {'uses_index': False, 'full_scan': True}
after: {'uses_index': True, 'full_scan': False}
(78,)
city lookup: {'uses_index': False, 'full_scan': True}Line by line
- 4-8Create 2000 fake people with a generated email each; half live in Manila and half in Cebu.
- 10-16A helper that runs
EXPLAIN QUERY PLANand condenses the plan into two booleans. Column 3 of each plan row holds the description text. - 18-19Before any index exists, searching by email has to scan the table.
- 21-22
CREATE INDEXbuilds a sorted lookup onemail. The same query now reports that it uses an index. - 24The query returns the same answer as before; indexes change speed, never results.
- 25
cityhas no index, so that lookup is still a scan.
Indexes are most valuable on columns with many distinct values (emails, ids). On a column with only two values such as a yes/no flag, an index rarely helps.
Transactions, rollback and context managers
A transaction groups several statements so they succeed or fail together. The classic example is moving money: subtract from one account and add to another. If the program crashes between the two steps, you must not lose the money. Transactions give databases the property called atomicity: all of the changes happen, or none do.
In Python's sqlite3 module, a transaction opens automatically before your first data-changing statement and stays open until you call commit() (keep the changes) or rollback() (throw them away). Forgetting to commit is the number one reason beginners say their data 'disappeared'.
The neatest way to handle this is to use the connection as a context manager. with conn: commits if the block finishes normally and rolls back if an exception escapes. Note that it does *not* close the connection; it only manages the transaction. For closing, use contextlib.closing(conn) or call close() yourself. Combine this with a CHECK constraint, as below, so the database itself refuses impossible states such as a negative balance.
import sqlite3
from contextlib import closing
with closing(sqlite3.connect(":memory:")) as conn:
conn.execute("""CREATE TABLE accounts (
name TEXT PRIMARY KEY,
balance INTEGER NOT NULL CHECK (balance >= 0))""")
conn.executemany("INSERT INTO accounts VALUES (?, ?)", [("ana", 100), ("ben", 20)])
conn.commit()
def transfer(src, dst, amount):
with conn:
conn.execute("UPDATE accounts SET balance = balance + ? WHERE name = ?", (amount, dst))
conn.execute("UPDATE accounts SET balance = balance - ? WHERE name = ?", (amount, src))
def balances():
return dict(conn.execute("SELECT name, balance FROM accounts ORDER BY name"))
transfer("ana", "ben", 30)
print("after good transfer:", balances())
try:
transfer("ben", "ana", 500)
except sqlite3.IntegrityError as e:
print("failed:", e)
print("after failed transfer:", balances())
conn.execute("UPDATE accounts SET balance = 0 WHERE name = 'ana'")
conn.rollback()
print("after manual rollback:", balances())after good transfer: {'ana': 70, 'ben': 50}
failed: CHECK constraint failed: balance >= 0
after failed transfer: {'ana': 70, 'ben': 50}
after manual rollback: {'ana': 70, 'ben': 50}Line by line
- 2
closingcallsclose()for us when the block ends. - 5-6
CHECK (balance >= 0)makes the database reject any change that would leave a negative balance. - 11-14
with conn:wraps both UPDATEs in one transaction: commit on success, rollback on exception. - 16-17A helper that returns the balances as a dict; a cursor of two-column rows converts directly with
dict(). - 19-20A normal transfer: ana 70, ben 50.
- 22-26Ben has only 50, so subtracting 500 violates the CHECK. Because the credit to ana ran first, it was already applied, then the whole block rolls back, so the balances are unchanged.
- 28-30An explicit
rollback()also discards pending changes, so ana keeps her balance.
with conn: does not close the connection. A leaked connection is usually harmless in short scripts but can hold file locks in long-running programs.
A first look at SQLAlchemy ORM
Writing SQL by hand is powerful, but larger programs often use an ORM (object-relational mapper), which lets you describe tables as Python classes and rows as objects. SQLAlchemy is the standard choice. You declare a model class, create a session, add objects and query with Python expressions, and SQLAlchemy generates the SQL for you. It supports SQLite, PostgreSQL, MySQL and more, so switching databases usually means changing one connection string.
An ORM is a convenience, not a replacement for understanding SQL. When a page is slow, you will still read the SQL it generated, think about indexes and consider joins. That is why this lesson teaches sqlite3 first. The example below is static because SQLAlchemy is not available in the browser runner: install it with pip install sqlalchemy and run it on your own computer. It uses the modern 2.0 style with DeclarativeBase, Mapped and select().
Notice how the same ideas return in new clothes: a session is a transaction, session.commit() is commit(), and the where clause is parameterised automatically, so injection is prevented for you. If you later build a web API, FastAPI pairs naturally with SQLAlchemy sessions.
from sqlalchemy import create_engine, select, String
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, Session
class Base(DeclarativeBase):
pass
class Book(Base):
__tablename__ = "books"
id: Mapped[int] = mapped_column(primary_key=True)
title: Mapped[str] = mapped_column(String(100))
year: Mapped[int]
engine = create_engine("sqlite:///:memory:")
Base.metadata.create_all(engine)
with Session(engine) as session:
session.add_all([Book(title="Dune", year=1965), Book(title="Hyperion", year=1989)])
session.commit()
stmt = select(Book).where(Book.year > 1970).order_by(Book.title)
for book in session.scalars(stmt):
print(book.id, book.title, book.year)Line by line
- 1-2Import the engine factory, the
selectbuilder and the ORM pieces. - 4-5Every model inherits from one base class that tracks the table definitions.
- 7-11A
Bookclass is a table.Mapped[int]andmapped_columndescribe each column; type hints supply the column types. - 13-14The engine is the connection to the database;
create_allissues theCREATE TABLEstatements. - 16-18A
Sessionis a unit of work. We add two objects and commit, like an INSERT plus a transaction commit. - 20-22
select(Book).where(...)builds a query as Python code;session.scalarsruns it and yieldsBookobjects.
Common mistakes
β Building SQL with f-strings
Pasting user input into a query lets it become SQL code. Always pass values through ? placeholders; only use string formatting for allow-listed column or table names.
β Forgetting to commit
Changes made through sqlite3 stay in an open transaction until you call commit() or leave a with conn: block. Other connections, and the file on disk, will not see them until then.
β Writing UPDATE or DELETE without WHERE
Without a WHERE, every row changes. Write the WHERE first, check the rowcount and preview the rows with a SELECT while experimenting.
β Assuming foreign keys are enforced
SQLite ignores REFERENCES unless you run PRAGMA foreign_keys = ON on each new connection, so orphaned rows can slip in silently.
β Calling fetchall() on huge results
fetchall() loads everything into memory. For large result sets iterate the cursor or use fetchmany(n), and filter or aggregate in SQL instead of in Python.
Quick quiz
Tap an answer. I explain every one, right or wrong.
Q1. Which approach correctly protects SELECT * FROM users WHERE name = ... from SQL injection?
Q2. After cur.execute('UPDATE t SET x = 1 WHERE id = 99') matches no row, what is cur.rowcount?
rowcount reports how many rows were changed, which is zero when nothing matched.Q3. What does a LEFT JOIN from authors to books return for an author with no books?
Q4. Which clause filters groups after aggregation?
WHERE filters rows before grouping, while HAVING filters whole groups using aggregate results.Q5. What does with conn: do when an exception escapes the block?
Q6. Why might you NOT index every column?
Frequently asked questions
When should I use SQLite instead of PostgreSQL or MySQL?
+SQLite is excellent for local apps, prototypes, tests, small to medium websites and embedded data. Choose a server database when many machines must write at the same time, or you need fine-grained user permissions and network access.
Does an in-memory database keep my data?
+No. :memory: databases vanish when the connection closes. Use a filename such as app.db for persistence, or file::memory:?cache=shared for sharing one in-memory database between connections in the same process.
Is the ORM better than raw SQL?
+Neither is better in general. An ORM reduces repetitive code and keeps queries parameterised, while raw SQL gives full control for reports and tuning. Many projects use both, so it pays to understand SQL first.
How do I see the table structure of an existing database?
+Query SELECT name, sql FROM sqlite_master WHERE type = 'table' for the creation statements, or use PRAGMA table_info(tablename) to list columns and types.
What are NULL values and how do I test for them?
+NULL means 'no value known'. It is not equal to anything, even itself, so use IS NULL and IS NOT NULL rather than = NULL. In Python, NULL arrives as None.
Key takeaways
- βSQLite ships with Python;
sqlite3.connect(':memory:')gives a scratch database in one line. - βCRUD maps to INSERT, SELECT, UPDATE and DELETE; check
rowcountandlastrowidafter writes. - βAlways use
?placeholders for values. Allow-list anything that must be spliced into the SQL, such as column names. - β
sqlite3.Rowgives name-based access, and joins plus foreign keys connect tables without duplicating data. - β
GROUP BYsummarises groups;WHEREfilters rows andHAVINGfilters groups. - βIndexes speed up reads at the cost of writes,
EXPLAIN QUERY PLANshows if they are used, andwith conn:gives transactions that roll back on error.