Flask SQLAlchemy query, specify column names
Data Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.
Introduction
When querying with Flask-SQLAlchemy, the default Model.query.all() loads all columns for every row. For performance and clarity, you often want to select only specific columns — reducing data transfer, memory usage, and serialization overhead. Flask-SQLAlchemy provides several ways to specify columns: db.session.query(), with_entities(), load_only(), and hybrid properties.
Setup
Method 1: db.session.query() with Specific Columns
Pass column objects directly to db.session.query():
The results are Row objects (named tuples), not User model instances. You cannot access other columns or call model methods on them.
Method 2: with_entities()
Chain .with_entities() onto an existing query:
Method 3: load_only() for Deferred Loading
Load a full model instance but only fetch specific columns from the database:
Unlike with_entities(), load_only() returns actual model instances. Other columns are deferred — they trigger a separate query when accessed.
Method 4: defer() for Excluding Columns
The inverse of load_only() — exclude specific heavy columns:
This is useful when you have large text or blob columns that you rarely need.
Method 5: values() and values_list() (Flask-specific)
Using raw query with column selection:
Selecting Columns from Multiple Tables (JOINs)
Aggregation with Column Selection
Converting Results to Dictionaries
Comparison of Methods
| Method | Returns | Lazy loading | Use case |
query(Model.col) | Named tuples | No | Select specific columns |
with_entities() | Named tuples | No | Modify existing query |
load_only() | Model instances | Yes (for other cols) | Need model methods |
defer() | Model instances | Yes (for deferred cols) | Exclude heavy columns |
Common Pitfalls
- Named tuples are not model instances: Results from
query(User.username)andwith_entities()are named tuples, notUserobjects. You cannot call model methods, access relationships, or useuser.idunless you includedUser.idin the query. - Deferred column N+1: With
load_only(), accessing a deferred column triggers a separate SQL query per row. If you accessuser.bioin a loop of 100 users, it generates 100 extra queries. Either include the column inload_only()or usewith_entities(). - Column name conflicts in joins: When two tables have the same column name (e.g.,
User.idandPost.id), use.label()to disambiguate:User.id.label('user_id'). - Forgetting
.all():User.query.with_entities(User.username)returns a query object, not results. Call.all(),.first(), or iterate to execute the query. - Using db.session.query vs Model.query: Both work, but
db.session.query(User.col)is the standard SQLAlchemy way, whileUser.query.with_entities()is Flask-SQLAlchemy specific. The former is more portable.
Summary
- Use
db.session.query(User.username, User.email)to select specific columns (returns named tuples) - Use
.with_entities()to modify an existing query to return specific columns - Use
load_only()when you need model instances but want to limit loaded columns - Use
defer()to exclude large columns (text, blob) from default loading - Results from column-specific queries are named tuples — use
._asdict()for dictionary conversion
Related reading
- Flask user authentication
- Flatten an irregular arbitrarily nested list of lists
- Flatten nested dictionaries, compressing keys
- Flattening a shallow list in Python
- Float types are not supported. Use Decimal types instead
- For i 0, why is i i equal to 0?
- for line in... results in UnicodeDecodeError 'utf-8' codec can't decode byte
- Force Anaconda to install tensorflow 1.14
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.