Model Querying - Basics

Sequelize provides various methods to assist querying your database for data.

Important notice: to perform production-ready queries with Sequelize, make sure you have read the Transactions guide as well. Transactions are important to ensure data integrity and to provide other benefits.

This guide will show how to make the standard CRUD queries.

Simple INSERT queries

First, a simple example:

  1. // Create a new user
  2. const jane = await User.create({ firstName: "Jane", lastName: "Doe" });
  3. console.log("Jane's auto-generated ID:", jane.id);

The Model.create() method is a shorthand for building an unsaved instance with Model.build() and saving the instance with instance.save().

It is also possible to define which attributes can be set in the create method. This can be especially useful if you create database entries based on a form which can be filled by a user. Using that would, for example, allow you to restrict the User model to set only an username and an address but not an admin flag:

  1. const user = await User.create({
  2. username: 'alice123',
  3. isAdmin: true
  4. }, { fields: ['username'] });
  5. // let's assume the default of isAdmin is false
  6. console.log(user.username); // 'alice123'
  7. console.log(user.isAdmin); // false

Simple SELECT queries

You can read the whole table from the database with the findAll method:

  1. // Find all users
  2. const users = await User.findAll();
  3. console.log(users.every(user => user instanceof User)); // true
  4. console.log("All users:", JSON.stringify(users, null, 2));
  1. SELECT * FROM ...

Specifying attributes for SELECT queries

To select only some attributes, you can use the attributes option:

  1. Model.findAll({
  2. attributes: ['foo', 'bar']
  3. });
  1. SELECT foo, bar FROM ...

Attributes can be renamed using a nested array:

  1. Model.findAll({
  2. attributes: ['foo', ['bar', 'baz'], 'qux']
  3. });
  1. SELECT foo, bar AS baz, qux FROM ...

You can use sequelize.fn to do aggregations:

  1. Model.findAll({
  2. attributes: [
  3. 'foo',
  4. [sequelize.fn('COUNT', sequelize.col('hats')), 'n_hats']
  5. 'bar'
  6. ]
  7. });
  1. SELECT foo, COUNT(hats) AS n_hats, bar FROM ...

When using aggregation function, you must give it an alias to be able to access it from the model. In the example above you can get the number of hats with instance.n_hats.

Sometimes it may be tiresome to list all the attributes of the model if you only want to add an aggregation:

  1. // This is a tiresome way of getting the number of hats (along with every column)
  2. Model.findAll({
  3. attributes: [
  4. 'id', 'foo', 'bar', 'baz', 'qux', 'hats', // We had to list all attributes...
  5. [sequelize.fn('COUNT', sequelize.col('hats')), 'n_hats'] // To add the aggregation...
  6. ]
  7. });
  8. // This is shorter, and less error prone because it still works if you add / remove attributes from your model later
  9. Model.findAll({
  10. attributes: {
  11. include: [
  12. [sequelize.fn('COUNT', sequelize.col('hats')), 'n_hats']
  13. ]
  14. }
  15. });
  1. SELECT id, foo, bar, baz, qux, hats, COUNT(hats) AS n_hats FROM ...

Similarly, it’s also possible to remove a selected few attributes:

  1. Model.findAll({
  2. attributes: { exclude: ['baz'] }
  3. });
  1. -- Assuming all columns are 'id', 'foo', 'bar', 'baz' and 'qux'
  2. SELECT id, foo, bar, qux FROM ...

Applying WHERE clauses

The where option is used to filter the query. There are lots of operators to use for the where clause, available as Symbols from Op.

The basics

  1. Post.findAll({
  2. where: {
  3. authorId: 2
  4. }
  5. });
  6. // SELECT * FROM post WHERE authorId = 2

Observe that no operator (from Op) was explicitly passed, so Sequelize assumed an equality comparison by default. The above code is equivalent to:

  1. const { Op } = require("sequelize");
  2. Post.findAll({
  3. where: {
  4. authorId: {
  5. [Op.eq]: 2
  6. }
  7. }
  8. });
  9. // SELECT * FROM post WHERE authorId = 2

Multiple checks can be passed:

  1. Post.findAll({
  2. where: {
  3. authorId: 12
  4. status: 'active'
  5. }
  6. });
  7. // SELECT * FROM post WHERE authorId = 12 AND status = 'active';

Just like Sequelize inferred the Op.eq operator in the first example, here Sequelize inferred that the caller wanted an AND for the two checks. The code above is equivalent to:

  1. const { Op } = require("sequelize");
  2. Post.findAll({
  3. where: {
  4. [Op.and]: [
  5. { authorId: 12 },
  6. { status: 'active' }
  7. ]
  8. }
  9. });
  10. // SELECT * FROM post WHERE authorId = 12 AND status = 'active';

An OR can be easily performed in a similar way:

  1. const { Op } = require("sequelize");
  2. Post.findAll({
  3. where: {
  4. [Op.or]: [
  5. { authorId: 12 },
  6. { authorId: 13 }
  7. ]
  8. }
  9. });
  10. // SELECT * FROM post WHERE authorId = 12 OR authorId = 13;

Since the above was an OR involving the same field, Sequelize allows you to use a slightly different structure which is more readable and generates the same behavior:

  1. const { Op } = require("sequelize");
  2. Post.destroy({
  3. where: {
  4. authorId: {
  5. [Op.or]: [12, 13]
  6. }
  7. }
  8. });
  9. // DELETE FROM post WHERE authorId = 12 OR authorId = 13;

Operators

Sequelize provides several operators.

  1. const { Op } = require("sequelize");
  2. Post.findAll({
  3. where: {
  4. [Op.and]: [{ a: 5 }, { b: 6 }], // (a = 5) AND (b = 6)
  5. [Op.or]: [{ a: 5 }, { b: 6 }], // (a = 5) OR (b = 6)
  6. someAttribute: {
  7. // Basics
  8. [Op.eq]: 3, // = 3
  9. [Op.ne]: 20, // != 20
  10. [Op.is]: null, // IS NULL
  11. [Op.not]: true, // IS NOT TRUE
  12. [Op.or]: [5, 6], // (someAttribute = 5) OR (someAttribute = 6)
  13. // Using dialect specific column identifiers (PG in the following example):
  14. [Op.col]: 'user.organization_id', // = "user"."organization_id"
  15. // Number comparisons
  16. [Op.gt]: 6, // > 6
  17. [Op.gte]: 6, // >= 6
  18. [Op.lt]: 10, // < 10
  19. [Op.lte]: 10, // <= 10
  20. [Op.between]: [6, 10], // BETWEEN 6 AND 10
  21. [Op.notBetween]: [11, 15], // NOT BETWEEN 11 AND 15
  22. // Other operators
  23. [Op.all]: sequelize.literal('SELECT 1'), // > ALL (SELECT 1)
  24. [Op.in]: [1, 2], // IN [1, 2]
  25. [Op.notIn]: [1, 2], // NOT IN [1, 2]
  26. [Op.like]: '%hat', // LIKE '%hat'
  27. [Op.notLike]: '%hat', // NOT LIKE '%hat'
  28. [Op.startsWith]: 'hat', // LIKE 'hat%'
  29. [Op.endsWith]: 'hat', // LIKE '%hat'
  30. [Op.substring]: 'hat', // LIKE '%hat%'
  31. [Op.iLike]: '%hat', // ILIKE '%hat' (case insensitive) (PG only)
  32. [Op.notILike]: '%hat', // NOT ILIKE '%hat' (PG only)
  33. [Op.regexp]: '^[h|a|t]', // REGEXP/~ '^[h|a|t]' (MySQL/PG only)
  34. [Op.notRegexp]: '^[h|a|t]', // NOT REGEXP/!~ '^[h|a|t]' (MySQL/PG only)
  35. [Op.iRegexp]: '^[h|a|t]', // ~* '^[h|a|t]' (PG only)
  36. [Op.notIRegexp]: '^[h|a|t]', // !~* '^[h|a|t]' (PG only)
  37. [Op.any]: [2, 3], // ANY ARRAY[2, 3]::INTEGER (PG only)
  38. // In Postgres, Op.like/Op.iLike/Op.notLike can be combined to Op.any:
  39. [Op.like]: { [Op.any]: ['cat', 'hat'] } // LIKE ANY ARRAY['cat', 'hat']
  40. // There are more postgres-only range operators, see below
  41. }
  42. }
  43. });

Shorthand syntax for Op.in

Passing an array directly to the where option will implicitly use the IN operator:

  1. Post.findAll({
  2. where: {
  3. id: [1,2,3] // Same as using `id: { [Op.in]: [1,2,3] }`
  4. }
  5. });
  6. // SELECT ... FROM "posts" AS "post" WHERE "post"."id" IN (1, 2, 3);

Logical combinations with operators

The operators Op.and, Op.or and Op.not can be used to create arbitrarily complex nested logical comparisons.

Examples with Op.and and Op.or

  1. const { Op } = require("sequelize");
  2. Foo.findAll({
  3. where: {
  4. rank: {
  5. [Op.or]: {
  6. [Op.lt]: 1000,
  7. [Op.eq]: null
  8. }
  9. },
  10. // rank < 1000 OR rank IS NULL
  11. {
  12. createdAt: {
  13. [Op.lt]: new Date(),
  14. [Op.gt]: new Date(new Date() - 24 * 60 * 60 * 1000)
  15. }
  16. },
  17. // createdAt < [timestamp] AND createdAt > [timestamp]
  18. {
  19. [Op.or]: [
  20. {
  21. title: {
  22. [Op.like]: 'Boat%'
  23. }
  24. },
  25. {
  26. description: {
  27. [Op.like]: '%boat%'
  28. }
  29. }
  30. ]
  31. }
  32. // title LIKE 'Boat%' OR description LIKE '%boat%'
  33. }
  34. });

Examples with Op.not

  1. Project.findAll({
  2. where: {
  3. name: 'Some Project',
  4. [Op.not]: [
  5. { id: [1,2,3] },
  6. {
  7. description: {
  8. [Op.like]: 'Hello%'
  9. }
  10. }
  11. ]
  12. }
  13. });

The above will generate:

  1. SELECT *
  2. FROM `Projects`
  3. WHERE (
  4. `Projects`.`name` = 'a project'
  5. AND NOT (
  6. `Projects`.`id` IN (1,2,3)
  7. OR
  8. `Projects`.`description` LIKE 'Hello%'
  9. )
  10. )

Advanced queries with functions (not just columns)

What if you wanted to obtain something like WHERE char_length("content") = 7?

  1. Post.findAll({
  2. where: sequelize.where(sequelize.fn('char_length', sequelize.col('content')), 7)
  3. });
  4. // SELECT ... FROM "posts" AS "post" WHERE char_length("content") = 7

Note the usage of the sequelize.fn and sequelize.col methods, which should be used to specify an SQL function call and a table column, respectively. These methods should be used instead of passing a plain string (such as char_length(content)) because Sequelize needs to treat this situation differently (for example, using other symbol escaping approaches).

What if you need something even more complex?

  1. Post.findAll({
  2. where: {
  3. [Op.or]: [
  4. sequelize.where(sequelize.fn('char_length', sequelize.col('content')), 7),
  5. {
  6. content: {
  7. [Op.like]: 'Hello%'
  8. }
  9. },
  10. {
  11. [Op.and]: [
  12. { status: 'draft' },
  13. sequelize.where(sequelize.fn('char_length', sequelize.col('content')), {
  14. [Op.gt]: 10
  15. })
  16. ]
  17. }
  18. ]
  19. }
  20. });

The above generates the following SQL:

  1. SELECT
  2. ...
  3. FROM "posts" AS "post"
  4. WHERE (
  5. char_length("content") = 7
  6. OR
  7. "post"."content" LIKE 'Hello%'
  8. OR (
  9. "post"."status" = 'draft'
  10. AND
  11. char_length("content") > 10
  12. )
  13. )

Postgres-only Range Operators

Range types can be queried with all supported operators.

Keep in mind, the provided range value can define the bound inclusion/exclusion as well.

  1. [Op.contains]: 2, // @> '2'::integer (PG range contains element operator)
  2. [Op.contains]: [1, 2], // @> [1, 2) (PG range contains range operator)
  3. [Op.contained]: [1, 2], // <@ [1, 2) (PG range is contained by operator)
  4. [Op.overlap]: [1, 2], // && [1, 2) (PG range overlap (have points in common) operator)
  5. [Op.adjacent]: [1, 2], // -|- [1, 2) (PG range is adjacent to operator)
  6. [Op.strictLeft]: [1, 2], // << [1, 2) (PG range strictly left of operator)
  7. [Op.strictRight]: [1, 2], // >> [1, 2) (PG range strictly right of operator)
  8. [Op.noExtendRight]: [1, 2], // &< [1, 2) (PG range does not extend to the right of operator)
  9. [Op.noExtendLeft]: [1, 2], // &> [1, 2) (PG range does not extend to the left of operator)

Deprecated: Operator Aliases

In Sequelize v4, it was possible to specify strings to refer to operators, instead of using Symbols. This is now deprecated and heavily discouraged, and will probably be removed in the next major version. If you really need it, you can pass the operatorAliases option in the Sequelize constructor.

For example:

  1. const { Sequelize, Op } = require("sequelize");
  2. const sequelize = new Sequelize('sqlite::memory:', {
  3. operatorsAliases: {
  4. $gt: Op.gt
  5. }
  6. });
  7. // Now we can use `$gt` instead of `[Op.gt]` in where clauses:
  8. Foo.findAll({
  9. where: {
  10. $gt: 6 // Works like using [Op.gt]
  11. }
  12. });

Simple UPDATE queries

Update queries also accept the where option, just like the read queries shown above.

  1. // Change everyone without a last name to "Doe"
  2. await User.update({ lastName: "Doe" }, {
  3. where: {
  4. lastName: null
  5. }
  6. });

Simple DELETE queries

Delete queries also accept the where option, just like the read queries shown above.

  1. // Delete everyone named "Jane"
  2. await User.destroy({
  3. where: {
  4. firstName: "Jane"
  5. }
  6. });

To destroy everything the TRUNCATE SQL can be used:

  1. // Truncate the table
  2. await User.destroy({
  3. truncate: true
  4. });

Creating in bulk

Sequelize provides the Model.bulkCreate method to allow creating multiple records at once, with only one query.

The usage of Model.bulkCreate is very similar to Model.create, by receiving an array of objects instead of a single object.

  1. const captains = await Captain.bulkCreate([
  2. { name: 'Jack Sparrow' },
  3. { name: 'Davy Jones' }
  4. ]);
  5. console.log(captains.length); // 2
  6. console.log(captains[0] instanceof Captain); // true
  7. console.log(captains[0].name); // 'Jack Sparrow'
  8. console.log(captains[0].id); // 1 // (or another auto-generated value)

However, by default, bulkCreate does not run validations on each object that is going to be created (which create does). To make bulkCreate run these validations as well, you must pass the validate: true option. This will decrease performance. Usage example:

  1. const Foo = sequelize.define('foo', {
  2. bar: {
  3. type: DataTypes.TEXT,
  4. validate: {
  5. len: [4, 6]
  6. }
  7. }
  8. });
  9. // This will not throw an error, both instances will be created
  10. await Foo.bulkCreate([
  11. { name: 'abc123' },
  12. { name: 'name too long' }
  13. ]);
  14. // This will throw an error, nothing will be created
  15. await Foo.bulkCreate([
  16. { name: 'abc123' },
  17. { name: 'name too long' }
  18. ], { validate: true });

If you are accepting values directly from the user, it might be beneficial to limit the columns that you want to actually insert. To support this, bulkCreate() accepts a fields option, an array defining which fields must be considered (the rest will be ignored).

  1. await User.bulkCreate([
  2. { username: 'foo' },
  3. { username: 'bar', admin: true }
  4. ], { fields: ['username'] });
  5. // Neither foo nor bar are admins.

Ordering and Grouping

Sequelize provides the order and group options to work with ORDER BY and GROUP BY.

Ordering

The order option takes an array of items to order the query by or a sequelize method. These items are themselves arrays in the form [column, direction]. The column will be escaped correctly and the direction will be checked in a whitelist of valid directions (such as ASC, DESC, NULLS FIRST, etc).

  1. Subtask.findAll({
  2. order: [
  3. // Will escape title and validate DESC against a list of valid direction parameters
  4. ['title', 'DESC'],
  5. // Will order by max(age)
  6. sequelize.fn('max', sequelize.col('age')),
  7. // Will order by max(age) DESC
  8. [sequelize.fn('max', sequelize.col('age')), 'DESC'],
  9. // Will order by otherfunction(`col1`, 12, 'lalala') DESC
  10. [sequelize.fn('otherfunction', sequelize.col('col1'), 12, 'lalala'), 'DESC'],
  11. // Will order an associated model's createdAt using the model name as the association's name.
  12. [Task, 'createdAt', 'DESC'],
  13. // Will order through an associated model's createdAt using the model names as the associations' names.
  14. [Task, Project, 'createdAt', 'DESC'],
  15. // Will order by an associated model's createdAt using the name of the association.
  16. ['Task', 'createdAt', 'DESC'],
  17. // Will order by a nested associated model's createdAt using the names of the associations.
  18. ['Task', 'Project', 'createdAt', 'DESC'],
  19. // Will order by an associated model's createdAt using an association object. (preferred method)
  20. [Subtask.associations.Task, 'createdAt', 'DESC'],
  21. // Will order by a nested associated model's createdAt using association objects. (preferred method)
  22. [Subtask.associations.Task, Task.associations.Project, 'createdAt', 'DESC'],
  23. // Will order by an associated model's createdAt using a simple association object.
  24. [{model: Task, as: 'Task'}, 'createdAt', 'DESC'],
  25. // Will order by a nested associated model's createdAt simple association objects.
  26. [{model: Task, as: 'Task'}, {model: Project, as: 'Project'}, 'createdAt', 'DESC']
  27. ],
  28. // Will order by max age descending
  29. order: sequelize.literal('max(age) DESC'),
  30. // Will order by max age ascending assuming ascending is the default order when direction is omitted
  31. order: sequelize.fn('max', sequelize.col('age')),
  32. // Will order by age ascending assuming ascending is the default order when direction is omitted
  33. order: sequelize.col('age'),
  34. // Will order randomly based on the dialect (instead of fn('RAND') or fn('RANDOM'))
  35. order: sequelize.random()
  36. });
  37. Foo.findOne({
  38. order: [
  39. // will return `name`
  40. ['name'],
  41. // will return `username` DESC
  42. ['username', 'DESC'],
  43. // will return max(`age`)
  44. sequelize.fn('max', sequelize.col('age')),
  45. // will return max(`age`) DESC
  46. [sequelize.fn('max', sequelize.col('age')), 'DESC'],
  47. // will return otherfunction(`col1`, 12, 'lalala') DESC
  48. [sequelize.fn('otherfunction', sequelize.col('col1'), 12, 'lalala'), 'DESC'],
  49. // will return otherfunction(awesomefunction(`col`)) DESC, This nesting is potentially infinite!
  50. [sequelize.fn('otherfunction', sequelize.fn('awesomefunction', sequelize.col('col'))), 'DESC']
  51. ]
  52. });

To recap, the elements of the order array can be the following:

  • A string (which will be automatically quoted)
  • An array, whose first element will be quoted, second will be appended verbatim
  • An object with a raw field:
    • The content of raw will be added verbatim without quoting
    • Everything else is ignored, and if raw is not set, the query will fail
  • A call to Sequelize.fn (which will generate a function call in SQL)
  • A call to Sequelize.col (which will quoute the column name)

Grouping

The syntax for grouping and ordering are equal, except that grouping does not accept a direction as last argument of the array (there is no ASC, DESC, NULLS FIRST, etc).

You can also pass a string directly to group, which will be included directly (verbatim) into the generated SQL. Use with caution and don’t use with user generated content.

  1. Project.findAll({ group: 'name' });
  2. // yields 'GROUP BY name'

Limits and Pagination

The limit and offset options allow you to work with limiting / pagination:

  1. // Fetch 10 instances/rows
  2. Project.findAll({ limit: 10 });
  3. // Skip 8 instances/rows
  4. Project.findAll({ offset: 8 });
  5. // Skip 5 instances and fetch the 5 after that
  6. Project.findAll({ offset: 5, limit: 5 });

Usually these are used alongside the order option.

Utility methods

Sequelize also provides a few utility methods.

count

The count method simply counts the occurrences of elements in the database.

  1. console.log(`There are ${await Project.count()} projects`);
  2. const amount = await Project.count({
  3. where: {
  4. id: {
  5. [Op.gt]: 25
  6. }
  7. }
  8. });
  9. console.log(`There are ${amount} projects with an id greater than 25`);

max, min and sum

Sequelize also provides the max, min and sum convenience methods.

Let’s assume we have three users, whose ages are 10, 5, and 40.

  1. await User.max('age'); // 40
  2. await User.max('age', { where: { age: { [Op.lt]: 20 } } }); // 10
  3. await User.min('age'); // 5
  4. await User.min('age', { where: { age: { [Op.gt]: 5 } } }); // 10
  5. await User.sum('age'); // 55
  6. await User.sum('age', { where: { age: { [Op.gt]: 5 } } }); // 50