Querying the Database (Flask-SQLAlchemy)
Querying in Flask-SQLAlchemy retrieves rows as Python objects. The classic style uses Model.query with filters like filter_by() and methods like all(), first(), and get(); newer code uses db.session.execute(select(...)).
Flask
Reading data is the most common database operation. Model.query.all() returns every row as a list of model instances, .filter_by(name='Ana') narrows by equality, .filter(Model.age > 18) allows expressions, and .order_by() sorts.
Terminal methods decide what you get back: .all() gives a list, .first() gives one object or None, .get(id) (now db.session.get) fetches by primary key, and .count() gives a number. Chaining filters builds up the SQL lazily until a terminal method runs it.
SQLAlchemy 2.x promotes the select() construct: db.session.execute(db.select(User).where(User.name == 'Ana')).scalars().all(). Both styles are valid; the legacy .query API remains widely used in tutorials.
Syntax
User.query.filter_by(active=True).all()
db.session.get(User, 1)Examples
Python
# legacy query API
active = User.query.filter_by(active=True).order_by(User.name).all()
one = User.query.filter(User.age > 18).first()
by_id = db.session.get(User, 1)