In one little Python tutorial, a programmer deletes the author Octavia E. Butler from a database. Her only book, Kindred, vanishes with her. That’s not a bug. It’s the lesson.
The tutorial shows how to use SQLAlchemy, a popular Python tool for talking to databases. Normally, you’d write database commands called SQL by hand. You’d also turn every row of data into something your program understands, and fix a pile of commands each time your tables change. It’s a lot of paperwork.
A translator for your data
SQLAlchemy has a helper called an ORM. Think of it as a translator between two people who speak different languages. In Python, you write a class for each table. Each object is a row. Each attribute is one value in that row. The translator turns all of that into SQL, and you can still peek at what it wrote.
The example is a tiny library with two tables, authors and books. Ursula K. Le Guin gets two books, A Wizard of Earthsea from 1968 and The Dispossessed from 1974. Octavia E. Butler gets Kindred, from 1979. The database lives only in memory, so every run starts fresh. No mess to clean up.
To save things, you use a session. The tutorial compares it to a shopping cart. You toss objects in, and “commit” is the checkout. Here’s the neat part: you add only the authors, and the books come along for the ride. Nobody has to carry them separately.
The 501 trips to the shop
The tutorial also shows a sneaky trap called the N+1 problem. By default, SQLAlchemy fetches an author’s books only when you ask for them. Loop over two authors and you make three trips to the database: one for the authors, then one per author.
Two authors is fine. With 500 authors, you’d make 501 trips. That’s like walking to the shop 501 times because you wrote your list one item at a time.
The fix is a setting called selectinload. It tells the database to bring all the books in one batch. In the example, the trips drop from three to two. Small number, but it scales nicely.
All or nothing
My favorite part is the transaction. A transaction is a bundle of changes that either all work or all fail. In the tutorial, the code tries to add two new authors at once. N. K. Jemisin is fine. But “Another Ursula” uses an email address that’s already taken.
The database says no. And because the changes were bundled, Jemisin’s perfectly good entry gets thrown out too. Afterward, the list of authors shows only Ursula K. Le Guin. Poor Jemisin was innocent, but the rule is the rule. Nothing was saved, which is exactly what the bundle is for.
Back to Kindred. Deleting Octavia removes it because of a “cascade” rule on the author’s list of books. Three books minus one leaves two, both by Ursula. The tutorial ends by suggesting you save the database to a file and try a tool called Alembic for changing tables later.
Based on reporting by Freecodecamp.


