Skip to content
Streak:0Loading your progress…Sign in

Module 6 · Lesson 2 of 3

SQL from Python

sqlite3/psycopg, parameterised queries, joins and transactions. ~30 min

Lesson notes

DB-API: the same shape for sqlite3, psycopg (Postgres), etc.
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE users (id INTEGER PRIMARY KEY, email TEXT UNIQUE NOT NULL)")
with conn:   # transaction: commits on success, rolls back on exception
    conn.execute("INSERT INTO users (email) VALUES (?)", ("ada@example.com",))
rows = conn.execute("SELECT id, email FROM users WHERE email = ?", (email,)).fetchall()

N+1 queries: fetching a list, then querying once per row for related data. Fix with a JOIN or a single WHERE id IN (...) query. ORMs (SQLAlchemy, SQLModel) make N+1 easy to write by accident — interviewers ask about it.

Practice

  1. 1. Safe queries & a join

    medium25 XP

    Using the provided schema, implement add_user(conn, email) (returns new id; parameterised), add_order(conn, user_id, cents), and spend_by_user(conn) returning [(email, total_cents)] for all users (0 if no orders), sorted by total desc then email — in a single query.

    Ctrl/⌘ + Enter runs the tests · Esc then Tab leaves the editor