Databases, SQL & Flask-SQLAlchemy

Storing data and querying it from Flask.

9 lessons · 32 past questions · 101 marks in the papers collected here

Open the interactive lessons →Databases, SQL & Flask-SQLAlchemy past questions

Diagrams, animations, quizzes and checked solutions are on the interactive pages.

Contents

  1. Start here: tables, rows and keys from zero
  2. Database families, graphs and indexes
  3. SQL: WHERE, GROUP BY, HAVING, ORDER BY
  4. SQLite's own behaviour
  5. Models and column options
  6. Foreign keys and cardinality
  7. The session: add, commit, update
  8. relationship(), backref, objects and ids
  9. Queries: filter, filter_by, aggregates and dates

1. Start here: tables, rows and keys from zero

A table is a grid; a key finds one row; a foreign key points at a row in another table.

how a relational database lays out data

The question this lesson answers. Why store a number such as 10 in a student's row instead of the course's name, and how do you get the name back?

A relational database keeps data in tables. Each table is about one kind of thing. Each row is one of those things and each column is one fact about it. A web app reads and writes these rows on every request; the database is what remembers between requests.

A table, read like a grid

s_id (primary key)namecourse_id (foreign key)
1Asha10
2Ravi10
3Meera20
Definition

The primary key (here s_id) is different in every row, so it finds exactly one row. A foreign key (here course_id) stores the primary key of a row in another table (course), which links each student to one course. Two students with course 10 means one course has many students.

Picture it

A table is a class register. The roll number is the primary key: no two students share it. Writing a teacher's staff number next to each student is a foreign key: it points at a row in the staff register instead of copying the teacher's details. The analogy stops at order: a register has a fixed order, a table does not.

Follow a key from one table to the other. The course table holds (10, Web) and (20, DB). Zoya has no course yet.

Worked example: Find the keys

Problem.

Tables: course(id, title) and enrollment(id, student_name, course_id).

Idea.

Primary key = unique id of its own table; foreign key = another table's id.

  1. course.id is course's primary key.
  2. enrollment.id is enrollment's primary key.
  3. enrollment.course_id stores a course.id: it is a foreign key.

Answer.

course.id and enrollment.id are primary keys; enrollment.course_id is a foreign key

Common mistake.

Calling course_id a primary key because it ends in id.

Worked example: Read the link

Problem.

course rows: (10, Web), (20, DB). enrollment rows: (1, Asha, 10), (2, Ravi, 10), (3, Meera, 20).

Idea.

Count rows whose foreign key equals the course's id.

  1. Web has id 10.
  2. Rows with course_id 10: Asha and Ravi, so 2.
  3. Each enrollment has one course, a course has many enrollments: one-to-many.

Answer.

2 enrollments; one-to-many

Common mistake.

Counting rows by course title, which enrollment does not store.

Worked example: A name stored twice

Problem.

A table stores the course title in every enrolment row. The title of one course changes. What can go wrong?

Idea.

One fact should live in one place.

  1. Every matching row must be edited.
  2. If one row is missed, the same course now has two names.
  3. Storing the id means only the course row changes.

Answer.

The data can become inconsistent.

Common mistake.

Thinking a repeated title is harmless because it is easier to read.

Tips and tricks
  • Read a question's tables by marking the primary key of each, then draw an arrow for every foreign key.
  • A many-to-many link needs a third table that holds two foreign keys.
  • NULL is tested with IS NULL. The comparison = NULL matches nothing.
Memory line

Store the key once, follow it whenever you need the details.

Method for any exam question

StepDo this
1Find the primary key of each table.
2Find which column points to another table.
3Match values to follow the link.
4Treat NULL as no link.

2. Database families, graphs and indexes

Pick the database by the shape of the question you will ask it.

which kind of database fits which job

The question this lesson answers. Which kind of database fits a job, and why does an index make a search fast without changing the answer?

Four families

FamilyStoresBest forExample
Relational (RDBMS)tables, rows, foreign keysstructured data, many links, constraints, transactionsSQLite, MySQL, PostgreSQL
Key-valuekey → valueone quick lookup by key, caches, sessionsRedis, DynamoDB
DocumentJSON-like documentsflexible, nested recordsMongoDB
Graphnodes and edges with propertiespaths: friends of friends, routesNeo4j
Definition

An index is a sorted (or hashed) copy of one or more columns that points back to the rows, so a lookup jumps to the right rows instead of reading the whole table. Reads get faster; every insert or update also updates the index.

Picture it

A key-value store is a coat-check counter: hand over the ticket number, get the coat. A relational database is the college office's filing system, with forms that refer to each other. A graph is the map of who knows whom. The analogy stops at speed: a real RDBMS with an index is also fast for single lookups.

Worked example: Coupon check

Problem.

At checkout a shop must answer very fast: "has this coupon code already been used?"

Idea.

The question is one key in, one value out.

  1. Key: the coupon code.
  2. Value: used or not.
  3. No joins or ranges are needed.

Answer.

Key-value store

Common mistake.

Picking an RDBMS because the rest of the shop uses one.

Worked example: Which statements fit a graph?

Problem.

(A) A metro map can be stored as a graph. (B) An edge can carry a distance. (C) Finding a shortest route between stations suits a graph database. (D) A graph database stores everything as fixed rows and columns.

Idea.

A graph is nodes and edges with properties, used for following paths.

  1. A true: stations are nodes, tracks are edges.
  2. B true: edges hold properties.
  3. C true: this is a path query.
  4. D describes a relational table.

Answer.

A, B, C

Common mistake.

Rejecting B because only nodes "hold data".

Seeing an index work. SQLite can tell you how it plans to answer a query: put EXPLAIN QUERY PLAN in front of it. Without an index on the column you search, the plan says SCAN: read every row. After CREATE INDEX ix ON u(email) the same query says SEARCH ... USING INDEX: jump straight to the matching rows. (SQLite writes COVERING INDEX when the index alone holds every column the query needs.)

EXPLAIN QUERY PLAN SELECT * FROM u WHERE email = 'u5@x';
-- SCAN u
CREATE INDEX ix ON u(email);
EXPLAIN QUERY PLAN SELECT * FROM u WHERE email = 'u5@x';
-- SEARCH u USING COVERING INDEX ix (email=?)

Family by the question you ask

Question your app asks mostBest familyWhy
"Give me user 42's cart"key-valueone key, one value, very fast
"Orders with their customer and items, all or nothing"relationaljoins and transactions
"Products whose fields differ a lot"documentno fixed columns
"Friends of friends within 3 steps"graphpaths are first-class

Worked example: An index on the wrong column

Problem.

An index exists on email. The query filters on name. Does the index help?

Idea.

An index is sorted by its own columns.

  1. The search condition uses name.
  2. The index is ordered by email.
  3. It cannot be used to find a name, so the table is scanned.

Answer.

No.

Common mistake.

Assuming any index speeds up every query on that table.

Tips and tricks
  • Match the clue: transactions or joins point to RDBMS, one key to one value points to key-value, paths between things point to graph.
  • An index makes reads faster but costs extra space and slower writes.
  • Reject options that say one database family is always best.
Memory line

Choose the family by the question; index the column you search by.

Method for any exam question

StepDo this
1Name the question the application asks most.
2One key to one value suggests key-value.
3Links and constraints suggest relational.
4Relationships of relationships suggest a graph.

3. SQL: WHERE, GROUP BY, HAVING, ORDER BY

Filter rows, make groups, filter groups, sort.

the order in which a SELECT runs

The question this lesson answers. A query is written in one order but carried out in another. Which rows are still there at each stage?

Picture it

Sorting receipts: first throw away the ones you do not need, then make a pile per shop, then drop piles that are too small, then read them in order.

The sales table

shopitemqtyprice
NorthPen410
SouthBag2300
NorthRuler1215
EastLamp25220
SouthCap6120
EastFan40900
WestMug3080
SELECT Manufacturer, COUNT(*)
FROM production
WHERE Quantity > 10
GROUP BY Manufacturer
HAVING COUNT(*) = 2;

Worked example: Count per genre

Problem.

Table loans has genre Poetry on 5 rows, History on 3 and Maths on 2. SELECT genre, COUNT(id) AS n FROM loans GROUP BY genre ORDER BY n ASC;

Idea.

One row per group, sorted by the alias.

  1. Counts: Poetry 5, History 3, Maths 2.
  2. ASC puts the smallest first.

Answer.

Maths 2, History 3, Poetry 5

Common mistake.

Listing one row per loan, or sorting descending.

Worked example: HAVING after WHERE

Problem.

On sales: SELECT shop, COUNT(*) FROM sales WHERE qty > 10 GROUP BY shop HAVING COUNT(*) = 2;

Idea.

Counts are over the rows that passed WHERE.

  1. Rows with qty above 10: Ruler (North), Lamp (East), Fan (East), Mug (West).
  2. North 1, East 2, West 1.
  3. Only East has a count of 2.

Answer.

East | 2

Common mistake.

Counting all seven rows first, which would also keep North and South.

Trap

An aggregate cannot go in WHERE: WHERE COUNT(*) > 1 is an error ("misuse of aggregate"). Conditions on groups go in HAVING.

Three details that change answers. Several sort keys are applied left to right. COUNT(DISTINCT col) counts different values, not rows. And in WHERE, AND binds tighter than OR, exactly like × before + in arithmetic: brackets change the result.

On the sales table (4 shops; 7 rows)

Query partResult
ORDER BY shop DESC, qty ASCWest first; inside East, Lamp (25) before Fan (40)
SELECT COUNT(DISTINCT shop), COUNT(*)4, 7
WHERE shop='North' OR shop='South' AND qty>4Pen, Ruler, Cap (all of North, plus South with qty above 4)
WHERE (shop='North' OR shop='South') AND qty>4Ruler, Cap
ORDER BY price DESC LIMIT 2Fan, Bag

Worked example: Where do the brackets go?

Problem.

You want North or South items with quantity above 4. Someone writes WHERE shop='North' OR shop='South' AND qty>4.

Idea.

AND is applied first: shop='North' OR (shop='South' AND qty>4).

  1. Pen (North, qty 4) passes through the left side although 4 is not above 4.
  2. Fix: WHERE (shop='North' OR shop='South') AND qty>4.
  3. Now only Ruler and Cap remain.

Answer.

Without brackets: Pen, Ruler, Cap; with brackets: Ruler, Cap

Common mistake.

Reading the condition left to right as if OR came first.

Joining two tables. Data about one thing is split across tables and linked by keys, so most real questions need a JOIN. JOIN ... ON e.course_id = c.id pairs each enrollment with its course. An inner join keeps only rows that have a partner; a LEFT join keeps every row of the left table, with NULL where there is no partner, which is how you count zeros.

SELECT e.name, c.title
FROM enrollment e JOIN course c ON e.course_id = c.id;
-- Asha Web, Ravi Web, Meera DB   (Zoya has no course: left out)

SELECT c.title, COUNT(e.id)
FROM course c LEFT JOIN enrollment e ON e.course_id = c.id
GROUP BY c.id;
-- Web 2, DB 1, AI 0

Worked example: Courses with no students

Problem.

course: Web (10), DB (20), AI (30). enrollment course_ids: 10, 10, 20, NULL.

Idea.

Only a LEFT join keeps a course with no partner.

  1. Inner join drops AI (no enrollment points at 30).
  2. LEFT JOIN from course keeps AI with NULLs.
  3. COUNT(e.id) counts non-NULL ids: 0.

Answer.

LEFT JOIN; AI 0

Common mistake.

Using COUNT(*) with the left join: it counts the NULL row as 1.

Worked example: Two kinds of count

Problem.

In enrollment, one of the four rows has course_id NULL. What does SELECT COUNT(*), COUNT(course_id) FROM enrollment return?

Idea.

COUNT(column) skips NULL.

  1. COUNT(*) counts rows: 4.
  2. COUNT(course_id) counts non-NULL values: 3.

Answer.

4 and 3.

Common mistake.

Answering 4 for both.

Tips and tricks
  • Solve in running order: filter rows, group, filter groups, pick columns, sort.
  • COUNT(*) counts rows; COUNT(column) skips rows where that column is NULL.
  • Write the small intermediate table after WHERE before you group. It prevents most counting slips.
Memory line

FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY.

Method for any exam question

StepDo this
1Write the starting rows.
2Cross out rows that fail WHERE.
3Group what is left.
4Cross out groups that fail HAVING.
5Compute the columns, then sort.

4. SQLite's own behaviour

SQLite is lenient: bare columns, case-insensitive LIKE, dates as text.

what SQLite does that stricter databases refuse

The question this lesson answers. Where does SQLite behave differently from what you expect? Predict each result before revealing it: 1 means true, 0 means false.

Picture it

A relaxed shopkeeper: SQLite accepts requests that stricter databases refuse, so you must know what it hands back.

Select count(ID), Name, color from flowers
group by color HAVING count(color)<2;

Bare column in a GROUP BY

SQLitePostgreSQL / strict SQL
SELECT Name, color ... GROUP BY colorallowederror: Name must be grouped or aggregated
one-row groupthat row's Namenot run
bigger groupa Name from one of its rowsnot run

Worked example: Exact spelling

Problem.

The stored name is "Red rose". An option shows "red rose".

Idea.

SQL returns stored text unchanged.

  1. SELECT does not change case.
  2. "red rose" ≠ "Red rose".

Answer.

No

Common mistake.

Treating names as case-insensitive.

Worked example: One-row groups

Problem.

Table pets (name, kind): Bruno dog, Tommy dog, Big Ben fish, Simba dog, Milo cat. SELECT COUNT(*), name, kind FROM pets GROUP BY kind HAVING COUNT(kind) < 2;

Idea.

Keep one-row groups, then read their rows.

  1. Groups: cat 1, dog 3, fish 1.
  2. Keep cat and fish.
  3. SQLite gives the groups ordered by kind, with the stored spelling.

Answer.

1|Milo|cat, 1|Big Ben|fish

Common mistake.

Including dog, or writing big ben in lower case.

Notice

Two more SQLite habits that show up in ORM questions: LIKE 'p%' also matches 'P...' , and dates are stored as text, so fixed_at - broken_at in SQL subtracts the years only.

Types and NULL in SQLite. SQLite stores a value with its own type. A column declared INTEGER converts text that looks like a number ('5' becomes 5) and keeps other text as text. Text compares letter by letter, so '10' < '9'. And NULL is not equal to anything, not even NULL: x = NULL is never true; write x IS NULL.

Surprises, run on SQLite

ExpressionResultWhy
'10' < '9'true (1)text compares '1' with '9' first
10 < 9false (0)numbers compare as numbers
NULL = NULLNULL (unknown)nothing equals an unknown value
WHERE x = NULLno rowsuse WHERE x IS NULL
insert '5' and 'abc' into an INTEGER column5 (integer), 'abc' (text)type affinity

Worked example: Count the missing values

Problem.

Table n has x values 1, NULL, 3.

Idea.

= NULL is never true; IS NULL tests for it.

  1. x = NULL is unknown for every row, so nothing is counted: 0.
  2. x IS NULL is true for one row: 1.

Answer.

0 and 1

Common mistake.

Writing = NULL and expecting it to find the empty value.

Worked example: A number column holding text

Problem.

A column is declared INTEGER. SQLite is given '12' and then 'abc'. What types are stored?

Idea.

SQLite converts text only when it looks like a number.

  1. '12' is converted to an integer.
  2. 'abc' cannot be converted and stays text.

Answer.

integer, then text.

Common mistake.

Expecting an error for the second insert.

Tips and tricks
  • With a single MIN or MAX, SQLite takes a bare column from the row that holds that value.
  • = is case-sensitive for text, while LIKE ignores the case of ASCII letters.
  • Dates stored as YYYY-MM-DD text compare correctly as text.
Memory line

Check the type, the case and the NULL.

Method for any exam question

StepDo this
1Decide whether each value is text or a number.
2Note = against LIKE for capitals.
3Replace any NULL comparison by IS NULL.
4Then compute the result.

5. Models and column options

Class = table, attribute = column, and one column is the primary key.

how a class describes a table

The question this lesson answers. You declare rules on a column. Which inserts does the database really refuse?

Picture it

A model is a printed form: each column is a box, with rules such as "must be filled" or "no two alike".

class MaxScores(db.Model):
    course_id = db.Column(db.String(10), primary_key=True)
    high_score = db.Column(db.Integer)

MaxScores.__tablename__                  # 'max_scores'
MaxScores(course_id='cs2002', high_score=86)  # fine
MaxScores('cs2002', 86)                  # TypeError

Column options

OptionMeansDefault
primary_key=Trueidentifies the row; NOT NULLFalse (one column must be True)
nullable=Falsevalue required ("mandatory")True for other columns
unique=Trueno two rows equal (NULL still allowed)False
db.ForeignKey('table.col')value must match a row in another tablenone
autoincrementinteger key filled automaticallyinteger primary keys get one

Worked example: Mandatory and optional

Problem.

A product needs: sku integer primary key; title mandatory text; discount optional number.

Idea.

Mandatory means nullable=False; a column is optional unless you say otherwise.

  1. sku = db.Column(db.Integer, primary_key=True)
  2. title = db.Column(db.String, nullable=False)
  3. discount = db.Column(db.Float) (the same as nullable=True).

Answer.

Writing nullable=True on discount, or leaving it out, are both correct

Common mistake.

Using unique=True where primary_key=True is needed: a model with no primary key does not map.

Worked example: Match a CREATE TABLE

Problem.

CREATE TABLE "Books" ("book_id" INTEGER, "title" TEXT, "pages" INTEGER, PRIMARY KEY("book_id")). You are shown several declarative classes.

Idea.

Compare table name, column names, types and primary key, one at a time.

  1. __tablename__ must be "Books"; the Python class name may differ.
  2. The attributes are book_id, title, pages.
  3. primary_key=True sits on book_id only.

Answer.

__tablename__ = "Books", book_id (Integer, primary key), title (String), pages (Integer)

Common mistake.

Judging by the class name instead of __tablename__.

What the database actually enforces. Column options are only as strong as the database behind them. SQLite enforces primary keys, NOT NULL and UNIQUE, but it does not enforce a string length: db.String(5) happily stores a much longer text. On PostgreSQL or MySQL the same model would reject it.

Declared versus enforced on SQLite

OptionEnforced by SQLite?What happens if broken
primary_key=TrueyesIntegrityError on a duplicate
nullable=FalseyesIntegrityError on NULL
unique=TrueyesIntegrityError on a duplicate
db.String(5)nothe long text is stored as it is

Worked example: A length that is not checked

Problem.

s = db.Column(db.String(5)). You add T(s="much longer than five") and commit on SQLite.

Idea.

SQLite ignores the declared length.

  1. The commit succeeds.
  2. Reading it back gives the full text.

Answer.

much longer than five

Common mistake.

Expecting truncation to 5 characters or an error: that happens on stricter databases, not SQLite.

Worked example: A default that is not there yet

Problem.

A column has default=5. What is the attribute on a new object before it is saved?

Idea.

The default is applied when the row is inserted.

  1. The object has only been created in Python.
  2. No insert has happened.

Answer.

None

Common mistake.

Expecting 5 immediately.

The setup that comes before any model. Past questions often begin with these lines and expect you to read them at a glance.

Connect Flask to a SQLite file

import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app_dir = os.path.abspath(os.path.dirname(__file__))
db_file = os.path.join(app_dir, "school.sqlite3")
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + db_file
db = SQLAlchemy(app)

class Student(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(40))

with app.app_context():
    db.create_all()
LineWhat it does
from flask_sqlalchemy import SQLAlchemyimports the extension; the package name uses an underscore
os.path.dirname(__file__)the folder that holds this Python file
os.path.abspath(...)turns it into a full path from the root of the disk
os.path.join(app_dir, "school.sqlite3")full path of the database file
SQLALCHEMY_DATABASE_URItells the extension which database to open; sqlite:/// comes before the file path
db = SQLAlchemy(app)creates the object that gives you db.Model, db.Column and db.session
with app.app_context():database work outside a request needs to know which app it belongs to
db.create_all()creates the tables that do not exist yet; it does not change a table that already exists

Two other spellings mean the same thing. You may see db = SQLAlchemy() followed later by db.init_app(app), or app.app_context().push() in place of the with block. A short URI such as sqlite:///school.sqlite3 is a relative path; Flask-SQLAlchemy 3 places that file in the app's instance folder. You may also see SQLALCHEMY_TRACK_MODIFICATIONS = False, which only switches off change notifications and does not affect queries.

Worked example: Why does this script crash?

Problem.

A script sets the URI, creates db, defines Student and then calls db.create_all() directly at the top level, outside any route.

Idea.

Ask whether Flask knows which app is active at that line.

  1. No request is running, so no application context exists.
  2. Flask-SQLAlchemy raises a RuntimeError saying it is working outside of the application context.
  3. Wrap the call in with app.app_context():.

Answer.

RuntimeError; call create_all inside the app context.

Common mistake.

Blaming the model class. The model is fine; the context is missing.

Tips and tricks
  • Scan every column for nullable=False and unique=True before judging whether an insert fails.
  • Without __tablename__, turn the class name into lower snake case to find the table name.
  • Arguments to a model are given by name, such as Student(name="A").
Memory line

A declaration is a promise only if the database enforces it.

Method for any exam question

StepDo this
1Find the primary key.
2Mark columns that refuse NULL.
3Check for unique columns.
4Remember that SQLite ignores string length.

6. Foreign keys and cardinality

Find the foreign key; its side and its uniqueness give the answer.

reading a relationship's type from the model code

The question this lesson answers. Looking only at the model code, how can you tell whether one row links to one, to many, or many to many? The foreign key tells you.

Who carries the card

In a one-to-many link each child carries a card naming its one parent. In many-to-many neither side can carry all the cards, so a separate list records the pairs.

Read the key

What you seeRelationship
child.parent_id = Column(..., ForeignKey('parent.id'))one parent → many children
same, with unique=True (and uselist=False on the relationship)one-to-one
third table with two foreign keys (product_id, supplier_id)many-to-many
no foreign key between the tablesnot related (a matching name is not enough)
class Parent(Base):
    __tablename__ = "parent_table"
    id = Column(Integer, primary_key=True)
    children = relationship("Child")

class Child(Base):
    __tablename__ = "child_table"
    id = Column(Integer, primary_key=True)
    parent_id = Column(Integer, ForeignKey("parent_table.id"))

Worked example: Playlist and Song

Problem.

Song.playlist_id = db.Column(db.Integer, db.ForeignKey("playlist.id")), not unique.

Idea.

A plain foreign key sits on the many side.

  1. Song holds the key, so Song is the many side.
  2. Not unique, so many songs can store the same playlist id.

Answer.

One playlist to many songs

Common mistake.

Saying many-to-many from real-life playlists; this design has no association table.

Worked example: Citizen and Passport

Problem.

Passport.citizen_id = db.Column(db.Integer, db.ForeignKey("citizen.id"), unique=True).

Idea.

A unique foreign key.

  1. The key links the two tables.
  2. unique=True: each citizen id can appear once in passport.
  3. So a citizen has at most one passport, and a passport one citizen.

Answer.

One-to-one

Common mistake.

Ignoring unique=True and saying one-to-many.

Finding the relationship: find the foreign keys, then two keys in a link table: many-to-many, then unique key: one-to-one, then otherwise: one-to-many

How to answer

StepDo this
1Find every foreign key and the table that holds it.
2The table holding the key is the many side.
3A unique key makes it one-to-one.
4Two keys in a linking table make many-to-many.

Worked example: A link with its own data

Problem.

Students take many courses, and each enrolment has a grade. Where does the grade go?

Idea.

The grade belongs to the pair.

  1. One student has different grades in different courses, so it cannot sit in student.
  2. One course has many grades, so it cannot sit in course.
  3. It describes one student with one course.
  4. Put it in the linking table, written as its own model.

Answer.

In the linking (enrolment) table.

Common mistake.

Adding a grade column to student.

Check your answer in ten seconds

Ask of each side: can it have many of the other? Two yes answers mean a linking table.

Trap

db.ForeignKey('Assignment.id') fails: Flask-SQLAlchemy names the table assignment. And student_id = db.ForeignKey('student.id') without db.Column(...) is not a column at all, so the relationship finds no key.

Many-to-many in code. An association table holds pairs of keys. In Flask-SQLAlchemy you declare it with db.Table and point the relationship at it with secondary=. You then work with plain lists: a.courses = [web, db], and the pairs appear in the association table by themselves.

enroll = db.Table("enroll",
    db.Column("student_id", db.Integer, db.ForeignKey("student.id")),
    db.Column("course_id", db.Integer, db.ForeignKey("course.id")))

class Student(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    courses = db.relationship("Course", secondary=enroll, backref="students")

# a.courses = [web, dbc]; b.courses = [web]  -> enroll has 3 rows
Notice

The order of a relationship list is not guaranteed unless you ask for one (order_by= on the relationship or in the query). Compare lists as sets when the order does not matter.

Memory line

The key sits on the many side; unique makes it one; two keys in a middle table make many-to-many.

7. The session: add, commit, update

Nothing is saved until you add it and commit.

what changes in the database and when

The question this lesson answers. You changed an object. Is it in the database yet? The session holds your changes until you commit.

s = Student(roll_number="M01", first_name="Yash", last_name="Raj")
db.session.add(s)            # pending
db.session.commit()          # written, s.s_id = 1

u = Student.query.filter_by(first_name="Yash").first()
u.first_name = "Ansh"        # change the loaded object
db.session.commit()          # UPDATE ... WHERE s_id = 1
A shopping basket

Adding to the basket reserves nothing; paying at the counter does. add fills the basket and commit pays. Where the picture stops: if one item fails at the counter, nothing in the basket is bought.

Session calls

CallDoes
db.session.add(obj) / add_all([...])marks objects to insert
db.session.commit()writes everything pending and ends the transaction
db.session.rollback()throws away uncommitted changes
db.session.delete(obj)marks a row for deletion (commit to apply)
Model.query.all() / .first()list of all matches / one object or None

Worked example: Insert in the right order

Problem.

Four shell sequences for inserting MaxScores(course_id='cs2002', high_score=86, term_year='Jan-2023').

Idea.

Keywords → add → commit.

  1. Positional arguments → TypeError.
  2. db.commit() does not exist; it is db.session.commit().
  3. commit then add: the add is never committed.

Answer.

create with keywords, db.session.add(s1), db.session.commit()

Common mistake.

Accepting commit-before-add because the same lines appear.

Worked example: Rename the first match

Problem.

members has the name Divya at ids 3, 4 and 8. The code does m = Member.query.filter_by(name="Divya").first(), sets m.name = "Dia", commits, then prints every row.

Idea.

first() returns one object (or None), never all matches.

  1. first() gives one matching row; without order_by, SQLite here returns id 3.
  2. Only that object is changed and saved.
  3. Ids 4 and 8 still read Divya.

Answer.

Only id 3

Common mistake.

Renaming all three.

Trap

Check that the print line runs before tracing data: for emp1 in emp: print(first_name) raises NameError, because the loop variable is emp1.

When a commit fails. If commit() breaks a rule (say, a duplicate unique value), it raises IntegrityError and the session is left in a failed state: the next query raises PendingRollbackError. Call db.session.rollback(), and the session works again. db.session.get(Model, id) fetches one row by primary key, or None.

Worked example: Fetch by key

Problem.

Table U has one row with id 1, e = "a".

Idea.

get looks up by primary key and returns None when there is no such row.

  1. id 1 exists: its e is "a".
  2. id 9 does not: None.

Answer.

"a" and None

Common mistake.

Expecting an error for a missing id: get returns None.

A transaction is all or nothing. Everything changed since the last commit is saved together. If one change breaks a rule, the commit fails and rollback() undoes all of them. That is why a money transfer (take from one account, add to another) is safe in one commit: it can never half-happen.

Worked example: A transfer that breaks halfway

Problem.

Account 1 has 100, account 2 has 50; bal is NOT NULL. In one session: a.bal -= 30, then b.bal = None, then commit; on error, rollback.

Idea.

The NOT NULL rule fails the whole commit.

  1. The commit raises IntegrityError (bal cannot be NULL).
  2. rollback() undoes both changes, including the valid -30.
  3. Balances are still 100 and 50.

Answer.

100 and 50

Common mistake.

Expecting 70 and 50: the valid change is undone too.

Worked example: Seen before commit, gone after rollback

Problem.

A row has n = 1. In one session you set n = 9, query for rows with n == 9, then roll back. What does the query find, and what is n afterwards?

Idea.

A query in the same session first sends pending changes; rollback undoes them.

  1. The query flushes the change, so it finds the row.
  2. Rollback cancels the change.

Answer.

1 row; then n is 1.

Common mistake.

Expecting the query to find nothing before commit.

Tips and tricks
  • Follow the object: created, added, committed. Without commit the change is not saved.
  • After first() check for None before reading an attribute.
  • To update, change the attribute and commit; no second add is needed for a fetched object.
Memory line

add prepares, commit saves, rollback forgets.

Method for any exam question

StepDo this
1List the changes since the last commit.
2Find the next commit.
3If it fails, none of those changes are saved.
4Roll back before using the session again.

8. relationship(), backref, objects and ids

Columns hold ids; relationships hold objects.

what the Python attributes of a relationship hold

The question this lesson answers. Should you hand a model a number or an object, and when does a new object get its number?

Two ways to introduce people

You may hand over the parent's id number, or hand over the parent object and let the library look up the number. The key column takes a number; the relationship takes an object.

class Channel(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    videos = db.relationship("Video", backref="playlist")

class Video(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    channel = db.Column(db.Integer, db.ForeignKey("channel.id"))

Video(name="x", channel=1)        # id in the column: works
Video(name="x", playlist=ch1)     # object in the relationship: works
Video(name="x", channel=ch1)      # fails at commit
Video(name="x", playlist=1)       # AttributeError

backref vs back_populates

backref="x"back_populates="x"
Where writtenone side onlyboth sides, each naming the other
Creates the other attributeyes, automaticallyno, you write it
Resultsame pair of attributessame pair of attributes

Worked example: Which ways create the video?

Problem.

ch1 has id 1. Options: channel=ch1, channel=1, playlist=ch1, playlist=1.

Idea.

Column ← id, relationship ← object.

  1. channel=1 ✓.
  2. playlist=ch1 ✓ (fills channel with 1).
  3. The swapped two fail.

Answer.

channel=1 and playlist=ch1

Common mistake.

Choosing channel=ch1 because the column is named after the channel.

Worked example: The id that was not there yet

Problem.

a = Author(name="Ira"); b = Book(title="Tides", author_id=a.id); add both; commit; print Author.query.filter_by(name="Ira").first().books.

Idea.

a.id is None until the row is flushed or committed.

  1. When b is built, a.id is None, so b.author_id is None.
  2. The commit gives a an id, but b still points at no author.
  3. The author's list of books is empty: [].
  4. Committing a first, or building Book(title="Tides", author=a), links them.

Answer.

[]

Common mistake.

Assuming a.id is 1 as soon as a is created.

Life of a new object: created: id is None, then added to the session, then flushed: id assigned, then committed: saved

How to answer

StepDo this
1Mark each attribute as a column or a relationship.
2Give columns plain values such as an id.
3Give relationships whole objects.
4Remember that a new object gets its id only when saved.

Worked example: An id that is not there yet

Problem.

u = User() and then p = Profile(user_id=u.id), before any flush or commit. What is stored in user_id?

Idea.

The database assigns the id when the row is written.

  1. u has not been written to the database.
  2. So u.id is None at that moment.
  3. user_id receives None.
  4. Setting the relationship, as in Profile(user=u) where one is defined, avoids this.

Answer.

NULL, if the column allows it.

Common mistake.

Assuming the id exists as soon as the object is created.

Check your answer in ten seconds

If code copies .id before a commit or flush, suspect None.

Working through the list. You can link objects from either side. ch.videos.append(v) adds the video to the channel's list, and when the channel is added and committed, the video is saved too and its key column is filled. Deleting the parent by default does not delete the children: their foreign key is set to NULL.

What happens, step by step

CodeResult
ch.videos.append(v), add ch, commitv.channel = 1, v.playlist is ch
delete ch, committhe video stays, v.channel becomes NULL

Worked example: Delete the channel

Problem.

Channel c has one video. db.session.delete(c), then commit (default relationship, no cascade option).

Idea.

Default behaviour: children are kept and unlinked.

  1. The channel row is deleted.
  2. SQLAlchemy sets the child's foreign key to NULL before deleting the parent.
  3. One video remains with channel NULL.

Answer.

1 video, channel None

Common mistake.

Expecting the video to be deleted too: that needs cascade="all, delete-orphan".

Memory line

Columns take values, relationships take objects, ids appear on saving.

9. Queries: filter, filter_by, aggregates and dates

filter_by for name=value; filter for expressions, joined with & or and_.

writing conditions that really become SQL

The question this lesson answers. A query is a chain. What does each link do, and what type comes out at the end?

Picture it

Asking a librarian: name the shelf, state the condition, then say whether you want one book, all of them or just the count.

filter_by vs filter

filter_byfilter
Takeskeywords: status="PAID"expressions: Order.amount > 500
Operatorsequality only==, !=, <, >, like, in_, …
Several conditionsfilter_by(a=1, b=2) → AND&, and_(), |, or_(), or chain
Wrong usefilter_by(Order.amount > 500) → TypeErrorfilter(status="PAID") → TypeError
cond = (Order.status == "PAID") and (Order.amount > 500)
print(cond)      # orders.status = :status_1   (amount is gone)

Order.query.filter(Order.status == "PAID").filter(Order.amount > 500)   # AND
Order.query.filter((Order.status == "PAID") & (Order.amount > 500))     # AND
Order.query.filter(and_(Order.status == "PAID", Order.amount > 500))    # AND

Worked example: Cheapest order

Problem.

Order.amount holds 250, 90 and 410.

Idea.

Build the aggregate query, then run it with scalar().

  1. db.session.query(func.min(Order.amount)) only builds the SELECT.
  2. .scalar() runs it and returns the single value.
  3. Printing the query without scalar() shows SQL text.

Answer.

print(db.session.query(func.min(Order.amount)).scalar())

Common mistake.

db.session.query.min(...): query is a function and has no min.

Worked example: Repairs over 7 days

Problem.

GlassRepair with Date columns broken_at and fixed_at. Option B filters in SQL with (fixed_at - broken_at) > 7.

Idea.

SQLite subtracts date text as numbers.

  1. Dates are stored as '2024-01-20'.
  2. Text to number stops at the first dash: 2024 - 2024 = 0.
  3. 0 > 7 is false for every row, so B returns [].

Answer.

No; load rows and use (r.fixed_at - r.broken_at).days in Python

Common mistake.

Trusting SQL date subtraction because it raises no error.

Exam tip

Model.query is a ready Query object: chain on it (Model.query.filter(...)), never call it. db.session.query(...) is the function you call with columns.

The query toolkit. Most questions combine a few pieces: order_by(col.desc()) to sort, limit(n) to keep the first n, in_([...]) for "one of these", like("s%") for patterns, and func.count, func.sum, func.avg with group_by for totals.

On five products (A: Biscuits 100, Chocolate 200; B: Shoes 500, Shirts 700; C: Pen 50)

QueryResult
P.query.order_by(P.cost.desc()).limit(2)Shirts, Shoes
P.query.filter(P.m.in_(["A", "C"])).count()3
db.session.query(P.m, func.count(P.id)).group_by(P.m)(A, 2), (B, 2), (C, 1)
P.query.filter(P.name.like("s%")).count()2 (Shoes, Shirts; LIKE ignores case)
query(func.sum(P.cost)).scalar(), func.avg1550, 310.0
filter(P.cost > 150).order_by(P.name).first()Chocolate

Worked example: Count per maker

Problem.

Same five products.

Idea.

Group by the maker and count inside each group.

  1. db.session.query(P.m, func.count(P.id)).group_by(P.m).order_by(P.m).all()
  2. A has 2, B has 2, C has 1.

Answer.

[("A", 2), ("B", 2), ("C", 1)]

Common mistake.

Using P.query.count(), which counts all rows at once (5).

Joining in SQLAlchemy. Enrollment.query.join(Course) follows the foreign key, so you can filter on the other table's columns: which students are in the Web course? SQLAlchemy writes the JOIN ... ON for you from the ForeignKey.

web_students = (Enrollment.query
    .join(Course)
    .filter(Course.title == "Web")
    .order_by(Enrollment.name)
    .all())
# ['Asha', 'Ravi']

Worked example: Nothing matches

Problem.

No product is called Cup. What does P.query.filter_by(name="Cup").first().cost do?

Idea.

first() returns None when nothing matches.

  1. The filter matches no row.
  2. first() gives None.
  3. Reading .cost from None raises AttributeError.

Answer.

It raises AttributeError.

Common mistake.

Expecting 0 or an empty list.

Subtracting dates in Python. A db.Date column arrives in Python as a date object. One date minus another is a timedelta, meaning a length of time. Its .days attribute is a whole number you can compare. timedelta(days=7) goes the other way: it builds a length of time from a number.

Days between two dates

from datetime import date, timedelta

gap = date(2024, 3, 12) - date(2024, 3, 1)
print(gap.days)                 # 11
print(gap.days > 7)             # True
print(gap > timedelta(days=7))  # True
ExpressionResult
gap.days > 7works: number against number
gap > 7TypeError: a timedelta cannot be compared with a number
timedelta(days=gap)TypeError: days= needs a number, and gap is already a timedelta
Do the subtraction on loaded rows

In SQLite, subtracting two date columns inside a query does not count days. Load the objects with .all(), then use (r.fixed_at - r.broken_at).days in a loop or list comprehension.

Memory line

all() gives a list; first() gives an object or None.

Method for any exam question

StepDo this
1Start with every row.
2Apply each filter in turn.
3Apply the ordering and limit.
4Read the last call to know the type.

Practise this topic →

Weeks covering this topic

Other MAD 1 topics