Select specific fields with Sequelize
How Sequelize's attributes option limits the columns a query returns, how include, exclude, aliases and association fields work, and when to select only some fields.
In Sequelize, you choose which columns a query returns with the attributes option. It works with finder methods such as findAll, findOne and findByPk. This review explains what the option changes, shows its common forms, and covers when a narrower selection helps or causes problems.
What selecting fields actually changes
The attributes option controls the SELECT clause that Sequelize generates. It does not change stored rows or the model definition. Sequelize does not fetch columns that are left out, so those columns are missing on the returned instances. This is different from loading full rows and then trimming them in JavaScript, such as in a serializer or a toJSON override. In that case every column still travels from the database to your application.
const users = await User.findAll({
attributes: ['id', 'firstName', 'email']
});
// Generates a query along the lines of:
// SELECT id, firstName, email FROM Users AS User;
Identifier quoting and table naming depend on the SQL dialect and the model options, so the generated SQL in your project will look slightly different. To see the exact statement, enable query logging through the logging option.
Common forms of the attributes option
- An array of column names returns only those columns.
- A two-element array, written as [column, alias], renames a column in the result.
- sequelize.fn and sequelize.col build computed values, such as counts, which usually need an alias.
- An object with include adds computed fields to the model's default columns instead of replacing them.
- An object with exclude returns every column except the ones you list.
// Alias a column and add an aggregate
const rows = await Post.findAll({
attributes: [
'authorId',
['title', 'headline'],
[sequelize.fn('COUNT', sequelize.col('id')), 'postCount']
],
group: ['authorId', 'title']
});
// Keep all columns and add one computed field
const withExtra = await Post.findAll({
attributes: {
include: [[sequelize.fn('LENGTH', sequelize.col('body')), 'bodyLength']]
}
});
// Return every column except one
const safeUsers = await User.findAll({
attributes: { exclude: ['passwordHash'] }
});
Function names such as LENGTH vary by database, so check that a computed expression is valid for your dialect. Grouping rules also differ between databases. An aggregate example that runs on one dialect may be rejected on another.
Selecting fields on associated models
Each entry in an include can have its own attributes. For many-to-many associations, the join table's columns are returned under the through key. An empty array there leaves the join-table columns out of the result.
const authors = await User.findAll({
attributes: ['id', 'firstName'],
include: [
{ model: Post, attributes: ['id', 'title'] },
{ model: Group, through: { attributes: [] } }
]
});
Is selecting specific fields the right choice?
Selecting specific fields is a good fit for read paths that feed API responses, reports or lists. Its main benefits are moving less data and keeping sensitive columns out of results by default. The main tradeoff is that the returned instances are partial. Any code that later relies on an omitted column will see it as missing. Instance methods such as save, reload and destroy find the row by its primary key, so keep the key in the list if you plan to call them. Getters or virtual fields that read omitted columns will also not have the data they expect.
Fetching full rows is the simpler choice in several cases: when you will modify and save the instance, when the table is small and has no sensitive columns, or while the schema is still changing and a hard-coded list would need constant updates. If you do not need model instances at all, the raw: true option returns plain objects. Raw results drop instance methods and change how associated data is nested.
Choose carefully between exclude and an explicit list when security matters. An exclude list is convenient, but any sensitive column added to the table later is returned automatically until someone adds it to the exclusions. An explicit list of allowed columns fails safe: new columns stay hidden until you add them. If many queries share the same restriction, a default scope can apply it centrally, with an unscoped query for the few places that need the full row.
Gaps in this review
No version-specific documentation, benchmarks or test results were supplied for this review, so it makes no performance claims. The behavior described here reflects the generally documented use of the attributes option. Details can differ between Sequelize major versions and between database dialects. Check the documentation for the version you run, and confirm the generated SQL through query logging before relying on a particular result shape.