Fall 2026
  • Discord
  • Gradescope
  • Syllabus

On this page

  • Tables and Keys
  • Selecting Rows
  • Conditions and Ordering
  • Joins and Summaries
  • Changing Data
  • SQL in an App

SQL

Applications use a database to save information and look it up later. We’ll use SQL (Structured Query Language) to organize data in tables, ask questions about it, and update it from a Python program.

Tables and Keys

A relational database stores data in tables. Each row describes one record, and each column holds one kind of information about it. Keys let us connect a record in one table with a related record in another.

A schema defines the structure of a database: its tables, columns, data types, and constraints. Constraints are rules that the database enforces when records are added or changed, such as requiring a value or preventing duplicates. CREATE TABLE defines a table’s structure, and INSERT adds rows.

A primary key is a column, or combination of columns, that uniquely identifies each row in a table. A foreign key is a column, or combination of columns, whose values refer to a key in a related table. This allows a record to refer to information stored elsewhere without copying it.

We will build a sample calendar around CMC places and traditions: Ath tea and dinner, Monte Carlo Night, W.O.A., and the thesis celebration. A venue has a name and capacity while an event has a title, date, and venue. We keep venues in their own table so that changing a venue’s capacity does not require editing every event held there.

We use SQLite, which keeps a whole database in a single file. In a new practice folder, run:

sqlite3 calendar.db

When the sqlite> prompt appears, enter these settings to show column names, line up results, and check foreign keys:

.headers on
.mode column
PRAGMA foreign_keys = ON;

Then enter the SQL below. Each statement ends with a semicolon. The following examples all use these two tables.

CREATE TABLE venues (
    id INTEGER PRIMARY KEY,
    name TEXT NOT NULL UNIQUE,
    capacity INTEGER
);

CREATE TABLE events (
    id INTEGER PRIMARY KEY,
    venue_id INTEGER NOT NULL REFERENCES venues(id),
    title TEXT NOT NULL,
    day TEXT NOT NULL
);

INSERT INTO venues (name, capacity) VALUES
    ('Athenaeum', 200),
    ('Chodosh Social Stairs', 40),
    ('Kravis Center', 20),
    ('Roberts Pavilion', NULL);

INSERT INTO events (venue_id, title, day) VALUES
    (1, 'Ath tea', '2026-11-12'),
    (2, 'W.O.A. reunion', '2026-11-13'),
    (1, 'Ath dinner', '2026-11-13'),
    (3, 'Monte Carlo Night', '2026-11-14'),
    (2, 'Thesis celebration', '2026-11-14');

In the table definitions, INTEGER and TEXT tell us which columns hold whole numbers and strings. The rules follow the type: NOT NULL requires a value, and UNIQUE prevents duplicate values in that column. We didn’t supply the ids, so SQLite assigned them starting at 1. The first event’s venue_id is 1, connecting it to the Athenaeum. For Roberts Pavilion, we haven’t recorded a capacity, so we use NULL to represent the missing value.

We store dates as text in YYYY-MM-DD order so that sorting them puts the earliest date first. Use single quotes around SQL strings. To include an apostrophe in a SQL string, write it twice: 'Founders'' Day'.

Selecting Rows

A query is a request for data from a database. Its result has rows and columns. Use SELECT to choose the columns, FROM to name the table, and WHERE to limit the result to rows that meet a condition.

SQL is a declarative language: a query describes the desired result rather than the steps for computing it. The database chooses how to find the matching records. An index is an additional data structure that helps it locate rows by particular column values without searching the whole table.

The table below shows SQL commands, constraints, and query clauses. (All the cheatsheets from this reading are available as a PDF here.)

SQL form Meaning
CREATE TABLE t (...) Define a table and its columns.
INTEGER, TEXT Whole-number and text column types.
PRIMARY KEY Uniquely identify each row.
NOT NULL, UNIQUE Require a value; reject duplicate values.
REFERENCES t(id) Refer to a key in another table.
INSERT INTO t (a, b) VALUES (x, y) Add a row with values for the named columns.
SELECT a, b FROM t Return the named columns; * returns all columns.
WHERE condition Keep only rows satisfying the condition.
ORDER BY a ASC, ORDER BY a DESC Sort by a column, ascending or descending.
LIMIT n Return at most n rows.
JOIN t ON condition Combine pairs of rows that satisfy the condition.
count(*) Count the selected rows.
UPDATE t SET a = value WHERE condition Change a column in matching rows.
DELETE FROM t WHERE condition Remove matching rows.

To choose a venue for an event, we can search by capacity. The first query shows the full venue table. The second narrows the result to names of venues with room for at least 40 people:

SELECT * FROM venues ORDER BY id;
SELECT name FROM venues WHERE capacity >= 40 ORDER BY id;
-- Athenaeum, then Chodosh Social Stairs

For a schedule of events at one venue, we need both the event titles and their dates. Selecting title, day returns those two columns, while WHERE venue_id = 2 limits the schedule to the Chodosh Social Stairs:

SELECT title, day FROM events WHERE venue_id = 2 ORDER BY id;
-- W.O.A. reunion | 2026-11-13
-- Thesis celebration | 2026-11-14

Columns appear in the order we put them after SELECT: here, the title comes before the day.

Conditions and Ordering

A condition is an expression used to test a row’s values. The WHERE clause keeps rows for which the condition is true. Comparisons such as = and >= test individual values. AND requires both conditions to be true, while OR requires at least one. Parentheses group conditions to control how they are evaluated.

NULL represents a missing or unknown value. An ordinary comparison with NULL has an unknown result, so it does not satisfy a WHERE condition. Use IS NULL to test for missing values and IS NOT NULL to test for values that are present.

Condition Meaning
=, != Equal; not equal.
<, <=, >, >= Less than, at most, greater than, at least.
a AND b, a OR b Both conditions hold; at least one holds.
IS NULL, IS NOT NULL A value is missing; a value is present.
LIKE 'A%' Text starts with A; % matches any number of characters.
LIKE '%a%' Text contains a; SQLite’s default LIKE ignores ASCII letter case.

LIKE compares text with a pattern, allowing searches for part of a name or phrase. In the pattern, % matches any sequence of characters, including an empty sequence. Putting % after a phrase matches text that starts with it, while putting % on both sides matches text containing it. SQLite’s default LIKE treats uppercase and lowercase English letters as equivalent.

These queries illustrate three kinds of filtering in the calendar. The first uses AND to select capacities within a range, the second uses LIKE to search event titles, and the third uses IS NULL to find venue records with missing capacity information:

SELECT name FROM venues
WHERE capacity >= 20 AND capacity < 100
ORDER BY id;

SELECT title FROM events WHERE title LIKE 'Ath%' ORDER BY id;
SELECT name FROM venues WHERE capacity IS NULL;

The pattern 'Ath%' finds titles starting with Ath. To find titles containing either tea or dinner, combine two searches with OR:

SELECT title FROM events
WHERE title LIKE '%tea%' OR title LIKE '%dinner%'
ORDER BY id;
-- Ath tea, then Ath dinner

Use = when you want an exact text match, including letter case.

ORDER BY sorts the result by one or more columns. The default direction is ascending (ASC), from smaller values to larger ones, while DESC reverses it. When rows have equal values in the first column, the next column determines their order. Without ORDER BY, SQL does not guarantee a particular row order. LIMIT n returns at most n rows. Combined with sorting, it selects the first n results in that order.

For a short calendar listing, we can sort events by date and keep the first three. Adding title to ORDER BY puts events on the same day in alphabetical order:

SELECT title, day FROM events ORDER BY day, title LIMIT 3;

Sorting by capacity in descending order puts the largest venue first. LIMIT 1 then returns just that venue, with missing capacities excluded by WHERE:

SELECT name FROM venues
WHERE capacity IS NOT NULL
ORDER BY capacity DESC LIMIT 1;
-- Athenaeum

SQLite places NULL before other values in ascending order and after them in descending order.

Joins and Summaries

A join lets us look up related information from two tables in one query. The ON condition specifies which rows go together, often by matching a foreign key in one table to the primary key in the other. An inner join gives one result row for each matching pair. A row with no match is left out.

An event listing needs the venue’s name, not just its numeric id. Match each event’s venue_id with the venue’s id:

SELECT events.title, venues.name
FROM events
JOIN venues ON events.venue_id = venues.id
ORDER BY events.id;

The Athenaeum matches two events, so its name appears beside both Ath tea and Ath dinner. Roberts Pavilion has no events and doesn’t appear in the result. We write events.title to select the title column from events. This table-and-column notation also lets us distinguish events.id from venues.id, since both tables have an id column.

The joined rows contain both event details and venue capacities, so we can filter events by the size of their venue. This query lists events at venues with capacity below 100, ordered by date and title:

SELECT events.title, venues.capacity
FROM events
JOIN venues ON events.venue_id = venues.id
WHERE venues.capacity < 100
ORDER BY events.day, events.title;

An aggregate function calculates a single summary value from a collection of rows. count(*) returns the number of rows selected by a query, or zero if none match. Applied to a join, it counts the matching pairs in the result.

To find how many events take place at the Chodosh Social Stairs, use the same venue condition as before but select count(*) instead of event details:

SELECT count(*) FROM events WHERE venue_id = 2;
-- 2

To count events at venues with capacity below 100, first join the tables so that the query has access to each venue’s capacity. WHERE selects the matching events, and count(*) counts them:

SELECT count(*)
FROM events
JOIN venues ON events.venue_id = venues.id
WHERE venues.capacity < 100;
-- 3

The Chodosh Social Stairs have two events and Kravis Center has one, so the count is three.

Changing Data

UPDATE changes values in existing rows. Its SET clause specifies the columns to change and their new values, which can be calculated from the current values. DELETE removes rows from a table. Both statements use WHERE to select the affected rows. Without it, they affect every row. Running a SELECT with the same condition first provides a way to check which records will change.

Updating a capacity

Editing a venue’s capacity requires changing its existing row. First, use SELECT to inspect the record. Then use UPDATE with the same condition to increase its stored capacity by five. The expression capacity + 5 calculates the new value from the current one:

SELECT name, capacity
FROM venues
WHERE name = 'Chodosh Social Stairs';

UPDATE venues
SET capacity = capacity + 5
WHERE name = 'Chodosh Social Stairs';

Deleting an event

Removing an event from the calendar requires deleting its row from events. Here, WHERE selects Monte Carlo Night by title, and the final query counts the events left in the table:

DELETE FROM events
WHERE title = 'Monte Carlo Night';

SELECT count(*) FROM events;
-- 4

Deleting a row does not renumber the others. After deleting event 4, the remaining event ids are 1, 2, 3, and 5.

SQL in an App

Python’s built-in sqlite3 module allows a program to run SQL statements in a SQLite database. A connection represents an open session with the database. A cursor executes statements and provides access to their results. The cursor’s fetchall() method returns the remaining result rows as a list of tuples, with values in the column order specified by SELECT.

Download calendar.sql and calendar_create.py into your practice folder. The SQL file contains the original tables and rows above, before the update and deletion. Run python3 calendar_create.py to create calendar.db if it does not already exist. Enter .quit to leave the SQL console before running Python commands.

The Python program below retrieves the event titles and dates, then loops over the returned rows to print a schedule. Save it as inspect_db.py beside calendar.db:

import sqlite3

connection = sqlite3.connect('calendar.db')
cursor = connection.cursor()
cursor.execute('SELECT title, day FROM events ORDER BY day, title')
for row in cursor.fetchall():
    print(row[0], row[1])
connection.close()

row[0] is the title and row[1] is the day. The setup program uses executescript() to run all the statements in calendar.sql. In the example above, execute() runs one statement.

A parameterized query uses placeholders for values supplied when the statement runs. In Python’s sqlite3 module, ? marks a placeholder, and the second argument to execute() supplies the values in order. Keeping these values separate from the SQL prevents user input from being interpreted as SQL code, a vulnerability known as SQL injection.

A calendar search needs to use the person’s search term in a query. Here, term stands in for text entered in a search box. We put % on either side to match titles containing that text and pass the resulting pattern separately from the SQL:

import sqlite3

term = 'tea'
pattern = '%' + term + '%'
connection = sqlite3.connect('calendar.db')
rows = connection.execute(
    'SELECT title FROM events WHERE title LIKE ? ORDER BY id',
    (pattern,),
).fetchall()
print(rows)  # [('Ath tea',)]
connection.close()

A transaction is a group of database operations treated as one unit: its changes are saved together or discarded together. This prevents a partly completed operation from leaving related records inconsistent. commit() saves the transaction’s changes, and rollback() discards them. With the connection settings used below, an update remains pending until committed. Closing the connection discards pending changes.

To save a change made in the app, Python runs an UPDATE and commits the transaction. This example changes the date stored for Ath tea, using placeholders for the new date and the event title:

import sqlite3

title = 'Ath tea'
new_day = '2026-11-15'
connection = sqlite3.connect('calendar.db')
connection.execute('PRAGMA foreign_keys = ON')
connection.execute(
    'UPDATE events SET day = ? WHERE title = ?',
    (new_day, title),
)
connection.commit()
connection.close()

The first ? receives new_day, and the second receives title. We turn on foreign-key checks again because this is a new connection.

A web server receives requests from a browser or another program and sends back responses. It can use a database to retrieve or save information while handling a request. An API (application programming interface) defines how programs interact. A web API specifies the requests a program can send to a server and the responses it can expect. GET requests retrieve information, while POST requests submit data for the server to process, such as a form submission or a new chat message.

FastAPI is a Python framework for building web APIs. A route associates a URL path and request method with a Python function that handles matching requests.

The server below makes the calendar’s event data available through a URL. Each time a browser requests /, the calendar() function queries the database and returns the event titles and dates.

In the folder containing calendar.db, activate your Python environment in the current terminal, then install the server dependencies:

python -m pip install fastapi uvicorn

Save this as webserver.py:

import sqlite3
import uvicorn
from fastapi import FastAPI

app = FastAPI()

@app.get('/')
def calendar():
    connection = sqlite3.connect('calendar.db')
    rows = connection.execute(
        'SELECT title, day FROM events ORDER BY day, title'
    ).fetchall()
    connection.close()
    return [{'title': title, 'day': day} for title, day in rows]

if __name__ == '__main__':
    uvicorn.run('webserver:app', host='127.0.0.1', port=8080)

Run python webserver.py, leave that terminal running, and open http://127.0.0.1:8080/. @app.get('/') tells FastAPI to call calendar for a GET request at /. FastAPI sends the returned list of dictionaries as JSON, a text format for sharing data between programs. Refresh the page after changing the database to see the updated events. Stop the server with Ctrl+C.