SQL from Python
Python programs talk to PostgreSQL through a driver, and the standard choice today is psycopg (version 3). It follows Python's database API (PEP 249): you open a connection, run SQL through it with execute, and fetch rows back as tuples or dictionaries, with PostgreSQL types turned into matching Python types. Python also ships with the sqlite3 module, which runs SQL against SQLite, a complete database stored in a single file with no server at all. In this lesson, we will connect to the Fee Tracker with psycopg, pass values safely with %s, see which Python types come back, insert a row with RETURNING, run a transaction with with, borrow connections from a pool, and then do the same kind of work in SQLite. Every program here was run against the Fee Tracker with psycopg 3.2 on Python 3.14, and the output shown is what it printed.
In One Minute
psycopg.connect(conninfo)opens a connection; use it in awithblock so it commits and closes for you.- Write
%sin the SQL and pass the values as a tuple; never use f-strings or%formatting yourself. - Rows come back as tuples (or dicts with
row_factory=dict_row), withNUMERICasDecimalandDATEasdate. with conn.transaction():makes a block all-or-nothing; errors arrive as classes such aserrors.CheckViolation.psycopg_pool.ConnectionPoollends connections in web apps.- SQLite uses
?placeholders and a file instead of a server; it's great for small tools, tests and learning.
Connecting and Querying
Install the driver with pip install "psycopg[binary]", then connect with a connection string. This program lists the courses that cost $300 or more:
import os
import psycopg
CONNINFO = "host=localhost port=5432 dbname=feetracker user=fee_app"
with psycopg.connect(CONNINFO, password=os.environ["FEE_DB_PASSWORD"]) as conn:
with conn.cursor() as cur:
cur.execute(
"SELECT title, fee_usd FROM courses"
" WHERE fee_usd >= %s ORDER BY fee_usd DESC, title",
(300,),
)
print(cur.rowcount, "courses")
for title, fee in cur.fetchall():
print(f"{title}: ${fee}")5 courses
Java Collections: $550.00
Java OOP: $500.00
Java Basics: $450.00
JavaScript Basics: $450.00
SQL Basics: $400.00Explanation: The conninfo string names the server, port, database and user; the password comes from an environment variable, never from the code (Database Hosting). with psycopg.connect(...) as conn: closes the connection at the end of the block, and commits if the block finished without an error (or rolls back if it raised one). A cursor runs SQL and holds its results; cur.rowcount is the number of rows, and fetchall() returns them as a list of tuples, which the for loop unpacks into title and fee. The ORDER BY ends with title so the two $450 courses always come back in the same order.
The SQL by itself is an ordinary query. Here it is with the value written in, so you can run it in Try it and compare the rows with the program's output:
SELECT title, fee_usd
FROM courses
WHERE fee_usd >= 300
ORDER BY fee_usd DESC, title; title | fee_usd
-------------------+---------
Java Collections | 550.00
Java OOP | 500.00
Java Basics | 450.00
JavaScript Basics | 450.00
SQL Basics | 400.00
(5 rows)%s is a placeholder, not Python string formatting. psycopg sends the SQL and the value 300 to the server separately, and it uses %s for every type: numbers, text and dates alike. The values always go in a tuple (or list), even when there's only one, which is why it's written (300,) with a comma.
The Types You Get Back
psycopg converts every PostgreSQL value into a fitting Python type. With row_factory=dict_row, each row is a dictionary keyed by column name, and conn.execute() is a shortcut that creates a cursor for you:
import os
import psycopg
from psycopg.rows import dict_row
CONNINFO = "host=localhost port=5432 dbname=feetracker user=fee_app"
with psycopg.connect(CONNINFO, password=os.environ["FEE_DB_PASSWORD"],
row_factory=dict_row) as conn:
row = conn.execute(
"SELECT payment_id, amount_usd, paid_on, method,"
" count(*) OVER () AS total_payments"
" FROM payments WHERE payment_id = %s",
(5,),
).fetchone()
for column, value in row.items():
print(f"{column:<15} {type(value).__name__:<8} {value!r}")
print(row["amount_usd"] + row["amount_usd"])payment_id int 5
amount_usd Decimal Decimal('200.00')
paid_on date datetime.date(2026, 1, 5)
method NoneType None
total_payments int 1
400.00Explanation:
| SQL type | Python type | Notes |
|---|---|---|
INTEGER, bigint, count(*) | int | Python integers have no size limit |
NUMERIC(8,2) | decimal.Decimal | Exact: Decimal('200.00') + Decimal('200.00') is 400.00 |
DATE | datetime.date | No time and no time zone, so nothing shifts |
TIMESTAMPTZ | datetime.datetime with a time zone | |
NULL | None |
Python gets these right without any extra work. Money is a Decimal, so adding two amounts gives exactly 400.00, and a date is a plain date. Compare SQL from JavaScript, where the same values arrive as strings and a Date at local midnight. When sending values, pass the same types: Decimal("200.00"), date(2026, 1, 5), or None for NULL.
Inserting with RETURNING
RETURNING sends back columns of the new row, so one statement saves it and returns its id:
import os
from datetime import date
from decimal import Decimal
import psycopg
CONNINFO = "host=localhost port=5432 dbname=feetracker user=fee_app"
with psycopg.connect(CONNINFO, password=os.environ["FEE_DB_PASSWORD"]) as conn:
payment_id, amount = conn.execute(
"INSERT INTO payments"
" (student_id, course_id, amount_usd, due_on, paid_on, method)"
" VALUES (%s, %s, %s, %s, %s, %s)"
" RETURNING payment_id, amount_usd",
(102, 4, Decimal("200.00"),
date(2026, 1, 5), date(2026, 1, 5), "card"),
).fetchone()
print("saved payment", payment_id, "for", amount)
# Leaving the "with" block committed the INSERT and closed the connection.saved payment 8 for 200.00Explanation: The six %s placeholders match the six values in the tuple, in order. fetchone() returns the one row RETURNING produced, and Python unpacks it into payment_id and amount. The Fee Tracker already had seven payments, so this one is number 8. The commit happens when the with block ends. Without the with block, you would need to call conn.commit() yourself; a program that exits without committing loses the insert.
Transactions
psycopg starts a transaction automatically before the first statement, and the connection's with block commits it at the end. For finer control, open the connection with autocommit=True and mark each transaction with with conn.transaction():, which commits when the block succeeds and rolls back if it raises:
import os
import psycopg
from psycopg import errors
CONNINFO = "host=localhost port=5432 dbname=feetracker user=fee_app"
INSERT = (
"INSERT INTO payments"
" (student_id, course_id, amount_usd, due_on, paid_on, method)"
" VALUES (%s, %s, %s, '2026-01-05', '2026-01-05', 'card')"
)
def count_payments(conn, student_id):
sql = "SELECT count(*) FROM payments WHERE student_id = %s"
return conn.execute(sql, (student_id,)).fetchone()[0]
with psycopg.connect(CONNINFO, password=os.environ["FEE_DB_PASSWORD"],
autocommit=True) as conn:
print("Advitha's payments before:", count_payments(conn, 102))
try:
with conn.transaction(): # BEGIN ... COMMIT or ROLLBACK
conn.execute(INSERT, (102, 1, "450.00"))
conn.execute(INSERT, (102, 4, "-200.00")) # a bug
except errors.CheckViolation as e:
print("Rolled back:", e.sqlstate, type(e).__name__)
print("Advitha's payments after:", count_payments(conn, 102))Advitha's payments before: 0
Rolled back: 23514 CheckViolation
Advitha's payments after: 0Explanation: The first INSERT succeeded inside the transaction block. The second broke CHECK (amount_usd > 0), and psycopg raised errors.CheckViolation, a class it creates for each PostgreSQL error code; its sqlstate is 23514. Leaving the transaction() block with an exception rolled everything back, the first payment included, so Advitha has 0 payments before and after. Because the exception is caught outside the block, the program carries on with a clean connection.
| psycopg error class | SQLSTATE | Typical cause |
|---|---|---|
errors.UniqueViolation | 23505 | A duplicate key |
errors.ForeignKeyViolation | 23503 | A payment for a student that doesn't exist |
errors.CheckViolation | 23514 | A negative amount |
errors.NotNullViolation | 23502 | A required value left out |
errors.SerializationFailure | 40001 | Retry the transaction (Isolation Levels) |
All of them are subclasses of psycopg.errors.IntegrityError or psycopg.Error, so you can catch broadly or precisely.
A Connection Pool
A web app serving many requests should borrow connections from a pool rather than connect for every request. psycopg's pool lives in a separate package, pip install psycopg-pool:
import os
from psycopg_pool import ConnectionPool
CONNINFO = "host=localhost port=5432 dbname=feetracker user=fee_app"
pool = ConnectionPool(
CONNINFO,
kwargs={"password": os.environ["FEE_DB_PASSWORD"]},
min_size=1,
max_size=5, # at most 5 connections
open=True,
)
def first_name(student_id):
with pool.connection() as conn: # borrow; returned at the end
row = conn.execute(
"SELECT first_name FROM students WHERE student_id = %s",
(student_id,),
).fetchone()
return row[0] if row else None
for sid in (101, 102, 103, 999):
print(sid, "->", first_name(sid))
pool.close()101 -> Srihitha
102 -> Advitha
103 -> Navika
999 -> NoneExplanation: The pool is created once when the program starts. with pool.connection() as conn: borrows a connection, commits (or rolls back) at the end of the block, and returns it to the pool for the next request. max_size=5 caps the connections this process may open; with many processes, those caps add up (Replication and Scaling). Student 999 doesn't exist, so fetchone() returns None. In async code, use AsyncConnectionPool and await in the same pattern.
SQLite: A Database in a File
SQLite is a complete SQL database that runs inside your program and stores everything in one file, with no server, no users and no network. Python includes it as the sqlite3 module, so there's nothing to install:
import sqlite3
conn = sqlite3.connect("study.db") # a single file; created if missing
with conn: # commits at the end, or rolls back
conn.execute(
"CREATE TABLE IF NOT EXISTS study_sessions ("
" student TEXT NOT NULL, studied_on TEXT NOT NULL,"
" minutes INTEGER NOT NULL CHECK (minutes > 0))"
)
conn.executemany(
"INSERT INTO study_sessions VALUES (?, ?, ?)",
[("Navika", "2026-01-06", 45),
("Srihitha", "2026-01-06", 90),
("Navika", "2026-01-07", 30)],
)
for student, total in conn.execute(
"SELECT student, sum(minutes) FROM study_sessions"
" GROUP BY student ORDER BY student"):
print(student, total)
try:
with conn:
conn.execute("INSERT INTO study_sessions VALUES (?, ?, ?)",
("Advitha", "2026-01-07", 0))
except sqlite3.IntegrityError as e:
print("Refused:", e)
conn.close()Navika 75
Srihitha 90
Refused: CHECK constraint failed: minutes > 0Explanation: sqlite3.connect("study.db") opens the file, creating it if needed. SQLite uses ? as its placeholder, not %s. with conn: commits the block if it succeeds and rolls it back on an exception, but, unlike psycopg, it does not close the connection, so conn.close() comes at the end. executemany runs the INSERT once per tuple. SQLite enforces the CHECK, so a 0-minute session is refused with sqlite3.IntegrityError.
| PostgreSQL with psycopg | SQLite with sqlite3 | |
|---|---|---|
| Where the data lives | A server, reached over the network | One file next to your program |
| Placeholder | %s | ? (or :name) |
| Setup | Install a server; create users | Nothing |
| Many users writing at once | Built for it | One writer at a time |
| Types | Strict: a DATE column holds dates | Flexible: a column can hold any type unless you declare the table STRICT |
| Good for | Web apps, shared data, production | Scripts, tests, phone and desktop apps, prototypes |
Common Mistakes
Building SQL with f-strings. It invites SQL injection. Pass values as the second argument to execute.
Writing (300) instead of (300,). (300) is just the number 300, not a tuple. Add the comma, or use a list: [300].
Forgetting to commit. Outside a with block, nothing is saved until conn.commit().
Using float for money. Send and receive Decimal.
Catching an error inside with conn.transaction(): and carrying on. The failed statement has already aborted the transaction; catch outside the block, or use a nested transaction() (a savepoint).
Mixing up placeholders. psycopg uses %s; sqlite3 uses ?.
Interview Corner
How do you pass parameters safely with psycopg?
Write %s placeholders in the SQL and pass the values as a tuple: cur.execute("... WHERE id = %s", (student_id,)). psycopg sends them separately from the SQL. Never use f-strings or % formatting yourself.
What happens when you leave a with psycopg.connect(...) as conn: block?
psycopg commits the open transaction if the block finished normally, rolls it back if it raised an exception, and closes the connection.
Which Python type does psycopg use for NUMERIC, and why does it matter?
decimal.Decimal, which keeps exact decimal values, so money adds up correctly. A float can't represent many decimals exactly.
When would you choose SQLite over PostgreSQL?
When one program owns the data and you want no server: local app storage, scripts, tests and prototypes. For shared, multi-user data, use PostgreSQL.
Practice
Challenge: Write a function unpaid_students(conn) that returns a list of the first names of students with no payments, in alphabetical order.
import os
import psycopg
CONNINFO = "host=localhost port=5432 dbname=feetracker user=fee_app"
def unpaid_students(conn):
rows = conn.execute(
"SELECT first_name FROM students s"
" WHERE NOT EXISTS (SELECT 1 FROM payments p"
" WHERE p.student_id = s.student_id)"
" ORDER BY first_name"
).fetchall()
return [name for (name,) in rows]
with psycopg.connect(CONNINFO, password=os.environ["FEE_DB_PASSWORD"]) as conn:
print("Unpaid:", unpaid_students(conn))Unpaid: ['Advitha']NOT EXISTS finds students without a payment (EXISTS). fetchall() returns one-element tuples such as ('Advitha',), and the list comprehension unpacks each into a plain name. The function takes the connection as a parameter, so the caller can pass a direct connection or one borrowed from a pool.
Key Takeaways
| You want to | Use |
|---|---|
| Connect | psycopg.connect("host=... dbname=... user=...", password=...) |
| Run a query with a value | conn.execute("... WHERE id = %s", (id,)) |
| Get rows as dicts | row_factory=dict_row |
| Get a new id | INSERT ... RETURNING payment_id, then fetchone() |
| Group statements | with conn.transaction(): |
| Borrow from a pool | with pool.connection() as conn: |
| Use SQLite | sqlite3.connect("file.db"), ? placeholders, conn.close() |
Was this tutorial helpful?