Skip to main content

SQL Fundamentals

intermediate15 min readLesson 88 of 169

Tables, SELECT, INSERT, WHERE, ORDER BY, JOIN โ€” the vocabulary of persistence.

A relational database stores tables of rows with typed columns. SQL is the query language; SQLite is the zero-config engine built into Python:

import sqlite3

conn = sqlite3.connect(":memory:")     # or "app.db" for a real file
conn.execute(
    """
    CREATE TABLE tasks (
        id INTEGER PRIMARY KEY,
        title TEXT NOT NULL,
        done INTEGER DEFAULT 0
    )
    """
)
conn.execute("INSERT INTO tasks (title) VALUES (?)", ("write lesson",))
conn.commit()

rows = conn.execute("SELECT id, title FROM tasks WHERE done = 0").fetchall()

The vocabulary that matters:

  • SELECT ... FROM ... WHERE โ€” read rows matching a condition.
  • ORDER BY ... LIMIT โ€” sort and take the top rows.
  • INSERT INTO ... VALUES โ€” add rows; UPDATE ... SET ... WHERE โ€” modify matched rows.
  • DELETE FROM ... WHERE โ€” remove rows. (The WHERE on UPDATE/DELETE is not optional in practice โ€” forgetting it changes every row.)
  • COUNT, SUM, AVG, GROUP BY โ€” aggregate per group: SELECT region, SUM(amount) FROM sales GROUP BY region.

conn.row_factory = sqlite3.Row makes rows behave like dicts (row["title"]) โ€” better than bare tuples for readability.

Now practice

SQL DrillsCreate, insert, select, aggregate.2 challenges ยท ยท ~30 min