Skip to content

CRUD - Read Record

Reading records is about querying the database.

Basic lookups

user = User.query.get(1)
user = User.query.get(1)
  • Returns the user with primary key 11 or NoneNone

Filter by column

user = User.query.filter_by(username="ravi").first()
user = User.query.filter_by(username="ravi").first()
  • first()first() returns one row or NoneNone

Get all rows

users = User.query.all()
users = User.query.all()

Ordering

users = User.query.order_by(User.username.asc()).all()
users = User.query.order_by(User.username.asc()).all()

Common pattern: 404 if not found

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

Flask-SQLAlchemy provides:

user = User.query.get_or_404(user_id)
user = User.query.get_or_404(user_id)

That’s very convenient for web apps.

Performance note

all()all() loads everything into memory.

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

If this helped you, consider buying me a coffee ☕

Buy me a coffee

Was this page helpful?

Let us know how we did