Skip to content

Multiple includes + limit breaks nested ordering #8457

Open

Description

@krzysztofczernek

What are you doing?

npm install sequelize
npm install sqlite3
'use strict'

const Sequelize = require('sequelize')
const sequelize = new Sequelize({dialect: 'sqlite', storage: 'test.sqlite'})

const Review = sequelize.define('reviews', {
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true
  },
  project_id: {
    type: Sequelize.INTEGER
  },
  text: {
    type: Sequelize.STRING
  }
})

const Project = sequelize.define('projects', {
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true
  },
  author_id: {
    type: Sequelize.INTEGER
  },
  name: {
    type: Sequelize.STRING
  }
})

const Author = sequelize.define('authors', {
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true
  },
  organization_id: {
    type: Sequelize.INTEGER
  },
  name: {
    type: Sequelize.STRING,
  }
})

const Organization = sequelize.define('organizations', {
  id: {
    type: Sequelize.INTEGER,
    primaryKey: true
  },
  name: {
    type: Sequelize.STRING,
  }
})

Project.hasMany(Review, {foreignKey: 'project_id', sourceKey: 'id'})
Review.belongsTo(Project, {foreignKey: 'id'})

Author.hasMany(Project, {foreignKey: 'author_id', sourceKey: 'id'})
Project.belongsTo(Author, {foreignKey: 'id'})

Organization.hasMany(Author, {foreignKey: 'organization_id', sourceKey: 'id'})
Author.belongsTo(Organization, {foreignKey: 'id'})

sequelize
  .sync({force: true})
  .then(() => {
    return Project.findAll({
      offset: 0,
      limit: 100,
      include: [
        {model: Author, include: [{model: Organization}]}
      ],
      order: [[Author, Organization, 'name', 'ASC']]
    })
  }).then(() => {
    return Project.findAll({
      offset: 0,
      limit: 100,
      include: [
        {model: Author, include: [{model: Organization}]},
        {model: Review}
      ],
      order: [[Author, Organization, 'name', 'ASC']]
    })
  }).then(results => {
    console.log(results)
  })

What do you expect to happen?

The two queries should handle LIMIT and ORDER the same way (in the outermost scope), regardless of how many includes they have.

SELECT `projects`.`id`, `projects`.`author_id`, `projects`.`name`, `projects`.`createdAt`, `projects`.`updatedAt`, `author`.`id` AS `author.id`, `author`.`organization_id` AS `author.organization_id`, `author`.`name` AS `author.name`, `author`.`createdAt` AS `author.createdAt`, `author`.`updatedAt` AS `author.updatedAt`, `author->organization`.`id` AS `author.organization.id`, `author->organization`.`name` AS `author.organization.name`, `author->organization`.`createdAt` AS `author.organization.createdAt`, `author->organization`.`updatedAt` AS `author.organization.updatedAt` FROM `projects` AS `projects` LEFT OUTER JOIN `authors` AS `author` ON `projects`.`id` = `author`.`id` LEFT OUTER JOIN `organizations` AS `author->organization` ON `author`.`id` = `author->organization`.`id` ORDER BY `author->organization`.`name` ASC LIMIT 0, 100;

SELECT `projects`.`id`, `projects`.`author_id`, `projects`.`name`, `projects`.`createdAt`, `projects`.`updatedAt`, `author`.`id` AS `author.id`, `author`.`organization_id` AS `author.organization_id`, `author`.`name` AS `author.name`, `author`.`createdAt` AS `author.createdAt`, `author`.`updatedAt` AS `author.updatedAt`, `author->organization`.`id` AS `author.organization.id`, `author->organization`.`name` AS `author.organization.name`, `author->organization`.`createdAt` AS `author.organization.createdAt`, `author->organization`.`updatedAt` AS `author.organization.updatedAt` FROM `projects` AS `projects` LEFT OUTER JOIN `authors` AS `author` ON `projects`.`id` = `author`.`id` LEFT OUTER JOIN `organizations` AS `author->organization` ON `author`.`id` = `author->organization`.`id` LEFT OUTER JOIN `reviews` AS `reviews` ON `projects`.`id` = `reviews`.`project_id` ORDER BY `author->organization`.`name` ASC LIMIT 0, 100;

What is actually happening?

In the first case (without including Review), a correct SQL is generated. In the second case (including Review), LIMIT is applied in the subquery, breaking the ORDER.

SELECT `projects`.`id`, `projects`.`author_id`, `projects`.`name`, `projects`.`createdAt`, `projects`.`updatedAt`, `author`.`id` AS `author.id`, `author`.`organization_id` AS `author.organization_id`, `author`.`name` AS `author.name`, `author`.`createdAt` AS `author.createdAt`, `author`.`updatedAt` AS `author.updatedAt`, `author->organization`.`id` AS `author.organization.id`, `author->organization`.`name` AS `author.organization.name`, `author->organization`.`createdAt` AS `author.organization.createdAt`, `author->organization`.`updatedAt` AS `author.organization.updatedAt` FROM `projects` AS `projects` LEFT OUTER JOIN `authors` AS `author` ON `projects`.`id` = `author`.`id` LEFT OUTER JOIN `organizations` AS `author->organization` ON `author`.`id` = `author->organization`.`id` ORDER BY `author->organization`.`name` ASC LIMIT 0, 100;

SELECT `projects`.*, `author`.`id` AS `author.id`, `author`.`organization_id` AS `author.organization_id`, `author`.`name` AS `author.name`, `author`.`createdAt` AS `author.createdAt`, `author`.`updatedAt` AS `author.updatedAt`, `author->organization`.`id` AS `author.organization.id`, `author->organization`.`name` AS `author.organization.name`, `author->organization`.`createdAt` AS `author.organization.createdAt`, `author->organization`.`updatedAt` AS `author.organization.updatedAt`, `reviews`.`id` AS `reviews.id`, `reviews`.`project_id` AS `reviews.project_id`, `reviews`.`text` AS `reviews.text`, `reviews`.`createdAt` AS `reviews.createdAt`, `reviews`.`updatedAt` AS `reviews.updatedAt` FROM (SELECT `projects`.`id`, `projects`.`author_id`, `projects`.`name`, `projects`.`createdAt`, `projects`.`updatedAt` FROM `projects` AS `projects` LIMIT 0, 100) AS `projects` LEFT OUTER JOIN `authors` AS `author` ON `projects`.`id` = `author`.`id` LEFT OUTER JOIN `organizations` AS `author->organization` ON `author`.`id` = `author->organization`.`id` LEFT OUTER JOIN `reviews` AS `reviews` ON `projects`.`id` = `reviews`.`project_id` ORDER BY `author->organization`.`name` ASC;

Dialect: postgres / sqlite
Dialect version: Postgres 9.6.1 / SQLite3
Sequelize version: 4.13.8
Tested with master branch: Yes

Activity

  1. krzysztofczernek commented on Oct 10, 2017

    @krzysztofczernek
    Author

    On a side note: separate: true is not always a viable workaround - for example, if we used belongsToMany relationships instead of hasMany.

  2. MHabashy10 commented on Dec 30, 2017

    @MHabashy10

    Hi @krzysztofczernek am having the same issue did you found a solution or workaround maybe?

    Thanks.

  3. rlindgren commented on Jan 24, 2018

    @rlindgren

    I think the ORDER and LIMIT must still be applied within the subquery, since the subquery resolves to the outermost scope (projects). In cases where ORDER is determined by an association, the JOIN for that association must also occur within the subquery and ORDER should be applied to the inner SELECT before resolving and joining any additional associations (which don't affect ORDER and LIMIT. So, in this case, the JOIN for organizations to authors should also occur inside of the subquery, so that the ORDER and LIMIT are correct.

    If there are many include associations, all of them that influence the ORDER should be JOINed inside of the subquery and the ORDER and LIMIT should be applied to the subquery before joining the other associations outside of the subquery.

    I believe that the second generated query that looks like this:

    SELECT
        `projects`.*,
        `author`.`id` AS `author.id`,
        `author`.`organization_id` AS `author.organization_id`,
        `author`.`name` AS `author.name`,
        `author`.`createdAt` AS `author.createdAt`,
        `author`.`updatedAt` AS `author.updatedAt`,
        `author->organization`.`id` AS `author.organization.id`,
        `author->organization`.`name` AS `author.organization.name`,
        `author->organization`.`createdAt` AS `author.organization.createdAt`,
        `author->organization`.`updatedAt` AS `author.organization.updatedAt`,
        `reviews`.`id` AS `reviews.id`,
        `reviews`.`project_id` AS `reviews.project_id`,
        `reviews`.`text` AS `reviews.text`,
        `reviews`.`createdAt` AS `reviews.createdAt`,
        `reviews`.`updatedAt` AS `reviews.updatedAt`
    FROM (
        SELECT
            `projects`.`id`,
            `projects`.`author_id`,
            `projects`.`name`,
            `projects`.`createdAt`,
            `projects`.`updatedAt`
        FROM
            `projects` AS `projects`
        LIMIT 0, 100
    ) AS `projects`
    LEFT OUTER JOIN
        `authors` AS `author` ON `projects`.`id` = `author`.`id`
    LEFT OUTER JOIN
        `organizations` AS `author->organization` ON `author`.`id` = `author->organization`.`id`
    LEFT OUTER JOIN
        `reviews` AS `reviews` ON `projects`.`id` = `reviews`.`project_id`
    ORDER BY `author->organization`.`name` ASC;
    

    should actually look like this:

    SELECT
        `projects`.*,
        `reviews`.`id` AS `reviews.id`,
        `reviews`.`project_id` AS `reviews.project_id`,
        `reviews`.`text` AS `reviews.text`,
        `reviews`.`createdAt` AS `reviews.createdAt`,
        `reviews`.`updatedAt` AS `reviews.updatedAt`
    FROM (
        SELECT
            `projects`.`id`,
            `projects`.`author_id`,
            `projects`.`name`,
            `projects`.`createdAt`,
            `projects`.`updatedAt`,
            `author`.`id` AS `author.id`,
            `author`.`organization_id` AS `author.organization_id`,
            `author`.`name` AS `author.name`,
            `author`.`createdAt` AS `author.createdAt`,
            `author`.`updatedAt` AS `author.updatedAt`,
            `author->organization`.`id` AS `author.organization.id`,
            `author->organization`.`name` AS `author.organization.name`,
            `author->organization`.`createdAt` AS `author.organization.createdAt`,
            `author->organization`.`updatedAt` AS `author.organization.updatedAt`
        FROM
            `projects` AS `projects`
        LEFT OUTER JOIN
            `authors` AS `author` ON `projects`.`id` = `author`.`id`
        LEFT OUTER JOIN
            `organizations` AS `author->organization` ON `author`.`id` = `author->organization`.`id`
        ORDER BY `author->organization`.`name` ASC
        LIMIT 0, 100
    ) AS `projects`
    LEFT OUTER JOIN
        `reviews` AS `reviews` ON `projects`.`id` = `reviews`.`project_id`;
    

    does that look right? I'm using mssql and haven't actually tested for sqlite yet... but for mssql, this does the trick for me. I can try to run a test on sqlite in a bit to confirm...

    This way, it only JOIN reviews for projects that are actually returned.

  4. blaivs commented on Feb 14, 2018

    @blaivs

    Had a similar problem and solved by using subQuery:true . It would look like this:

    sequelize
      .sync({force: true})
      .then(() => {
        return Project.findAll({
          offset: 0,
          limit: 100,
          subQuery: false,
          include: [
            {model: Author, include: [{model: Organization}]},
            {model: Review}
          ],
          order: [
            [Author, Organization, 'name', 'ASC']
          ]
        })
      }).then(results => {
        console.log(results)
      })

    Although using mssql, had to add another order for the main model, as it wasn't generating a valid expression:

    sequelize
      .sync({force: true})
      .then(() => {
        return Project.findAll({
          offset: 0,
          limit: 100,
          subQuery: false,
          include: [
            {model: Author, include: [{model: Organization}]},
            {model: Review}
          ],
          order: [
            [Author, Organization, 'name', 'ASC'],
            ['id']
          ]
        })
      }).then(results => {
        console.log(results)
      })
  5. yonjah commented on Mar 16, 2018

    @yonjah
    Contributor

    @blaisax using subQuery: false seem great as a workaround.
    I'm just not sure what the implications are since I couldn't find any documentation for it.

    I assume in some cases some results might get duplicated but I haven't seen it happening for my use case

  6. stale commented on Jun 14, 2018

    @stale
  7. OwenLittleWhite commented on Jan 10, 2020

    @OwenLittleWhite

    When there is one-one relation, subQuery: false works, but one-many and many-many, it doesn't work. Anyone solved this problem?

  8. reopened this on Jan 17, 2020
  9. added
    topic: group & order
    topic: limit & offset
    type: bug
    on Jan 17, 2020
  10. FREEZX commented on Mar 15, 2020

    @FREEZX

    Using subQuery: false breaks the limit + offset parameters in many-to-many relations, because of repeating rows returned by the db for each association

  11. aristov commented on Mar 24, 2020

    @aristov
    Contributor

    subQuery: false helps.

  12. Leeiio commented on Apr 14, 2020

    @Leeiio

    subQuery: false helps.

    not for many-to-many relations

  13. afzalIbnSH commented on Apr 5, 2021

    @afzalIbnSH

    The below scope breaks when I apply a limit.

    Foo.addScope(
                'foobar',
                (individualTypes, types, userId) => {
                    return {
                        include: [
                            {
                                model: models.User,
                                attributes: ['id']
                            },
                        where: {
                            $or: [
                                {
                                    type: individualTypes,
                                    '$User.id$': userId
                                },
                                { type: types }
                            ]
                        }
    

    It works well without limit i.e. Foo.scope({ method: ['foobar', [ 'INDIVIDUAL-TYPE-1' ], [ 'TYPE-1', 'TYPE-2' ], 1 ] }).findAndCountAll() but breaks with limit i.e. Foo.scope({ method: ['foobar', [ 'INDIVIDUAL-TYPE-1' ], [ 'TYPE-1', 'TYPE-2' ], 1 ] ] }).findAndCountAll({ limit: 10 })

  14. caseyt commented on Jan 10, 2025

    @caseyt

    Still open? Any plans to address the biggest issue in this repo that has been reported over and over again? The maintainers of this repo are useless.

  15. added theissue type on Mar 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: group & ordertopic: limit & offsettype: bug

    Type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions