maciek ☁️

How to speed up Sequelize with complicated includes

Sometimes queries can get complicated with many include statements. This can significantly slow down the response.

const stageWithMeta = await db.stage.findOne({
      where: { id },
      include: [
        {
          model: db.workTimeLog,
          include: [{ model: db.user }],
        },
        {
          model: db.incomeExpense,
        },
      ],
    });

One way to make thing faster is to add separate: true to the include.

const stageWithMeta = await db.stage.findOne({
      where: { id },
      include: [
        {
          model: db.workTimeLog,
          separate: true,
          include: [{ model: db.user }],
        },
        {
          model: db.incomeExpense,
          separate: true,
        },
      ],
    });

This is only supported for hasMany associations.

doc

If true, runs a separate query to fetch the associated instances, only supported for hasMany associations

Sequelize will run separate queries and merge the result in memory, instead of making a huge query with many JOIN statements.

#code #note