Skip to content

CRUD - Read Record

Reading records is about querying the database.

diagram the four operations, and where each one actually writes mermaid
Only two of the four need an explicit add. Reads return objects already managed by the session, and an update is just assigning to an attribute -- SQLAlchemy notices the change and writes it on the next flush. What every write shares is the commit at the end; without it the transaction is discarded when the request finishes.
python
user = User.query.get(1)
  • Returns the user with primary key 1 or None
python
user = User.query.filter_by(username="ravi").first()
  • first() returns one row or None
python
users = User.query.all()
python
users = User.query.order_by(User.username.asc()).all()

In routes, you often want “not found” to return a 404.

Flask-SQLAlchemy provides:

python
user = User.query.get_or_404(user_id)

That’s very convenient for web apps.

all() loads everything into memory.

For very large tables, use pagination (limit/offset) or streaming approaches.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading