Query API (Flask-SQLAlchemy)

The Flask-SQLAlchemy Query API is the chainable interface for retrieving and filtering rows. Methods like filter(), filter_by(), order_by(), join(), limit(), and offset() build a query lazily; terminal methods like all() and first() run it.

Flask

The Query API reads like a sentence. You start from Model.query and chain refinements: .filter(User.age > 18).order_by(User.name).limit(10). Nothing hits the database until you call a terminal method, so you can build queries up conditionally.

filter_by(name='Ana') is shorthand for equality on the model's own columns, while filter(User.name == 'Ana') accepts full expressions including comparisons, in_(), like(), and combinations with and_/or_. Use .join() to traverse relationships and .group_by()/.having() for aggregates.

SQLAlchemy 2.x introduces the select()-based API (db.session.execute(db.select(User)...)), which the legacy .query interface now wraps. Both produce the same SQL; pick one style and stay consistent within a project.

Syntax

Model.query.filter(...).order_by(...).limit(n).all()

Examples

Python

adults = (User.query
          .filter(User.age >= 18)
          .order_by(User.name)
          .limit(5)
          .all())

first_match = User.query.filter(User.email.like("%@example.com")).first()

Learn it in a lesson

See also

Back to the Dictionary