Skip to content

Columns of join table are always selected, which breaks aggregation in PostgresSQL #5481

Open

Description

@MrOrz

Dialect: PostgresSql
Sequelize version: 3.19.3

I have two tables that are n:m associated with a joining table. Whenever I use .findAll and include the other table, all fields in the joining table would also be selected in the generated SQL queries. The fields in the joining table would cause problems when I try to use the aggregate functions.

include[].through.attributes: [] does not stops the columns from going into the SQL query.

The example below is modified from the one in #3938.

Setup:

// MODELS
var Group = sequelize.define('Group', {
  name: sequelize.Sequelize.STRING
});

var Person = sequelize.define('Person', {
  name: sequelize.Sequelize.STRING
});

var GroupPerson = sequelize.define('GroupPerson', {
  status: sequelize.Sequelize.STRING
});

// RELATIONS
Group.belongsToMany(Person, {through: GroupPerson, as: 'Persons'});
Person.belongsToMany(Group, {through: GroupPerson, as: 'Groups'});

sequelize.sync({force: true}).then(function(){
  // EXAMPLE
  Person.findAll({
    attributes: [[sequelize.fn('ARRAY_AGG', sequelize.col('Groups.id')), 'groupIds']],
    include: [{
      model: Group,
      as: 'Groups',
      through:{
        attributes: [],
        where: {status: 'done'}
      },
      attributes: []
    }],
    group: [sequelize.col('Person.id')]
  });
})

Expected SQL generated:

SELECT ARRAY_AGG("Groups"."id") AS "groupIds"
FROM "People" AS "Person"
LEFT OUTER JOIN (
  "GroupPeople" AS "Groups.GroupPerson" 
  INNER JOIN 
    "Groups" AS "Groups" ON "Groups"."id" = "Groups.GroupPerson"."GroupId" AND "Groups.GroupPerson"."status" = 'done'
) ON "Person"."id" = "Groups.GroupPerson"."PersonId"
GROUP BY "Person"."id";

Actual SQL generated:

SELECT "Person"."id", ARRAY_AGG("Groups"."id") AS "groupIds",
  "Groups.GroupPerson"."status" AS "Groups.GroupPerson.status", "Groups.GroupPerson"."createdAt" AS "Groups.GroupPerson.createdAt", 
  "Groups.GroupPerson"."updatedAt" AS "Groups.GroupPerson.updatedAt", "Groups.GroupPerson"."PersonId" AS "Groups.GroupPerson.PersonId",
  "Groups.GroupPerson"."GroupId" AS "Groups.GroupPerson.GroupId"
FROM "People" AS "Person"
LEFT OUTER JOIN (
  "GroupPeople" AS "Groups.GroupPerson"
  INNER JOIN
    "Groups" AS "Groups" ON "Groups"."id" = "Groups.GroupPerson"."GroupId" AND "Groups.GroupPerson"."status" = 'done'
) ON "Person"."id" = "Groups.GroupPerson"."PersonId"
GROUP BY "Person"."id";

...which gives the following error:

Unhandled rejection SequelizeDatabaseError: column "Groups.GroupPerson.status" must appear in the GROUP BY clause or be used in an aggregate function
    at Query.formatError (/Users/mrorz/workspace/gis-inner/node_modules/sequelize/lib/dialects/postgres/query.js:443:14)
    at null.<anonymous> (/Users/mrorz/workspace/gis-inner/node_modules/sequelize/lib/dialects/postgres/query.js:118:19)
    at emitOne (events.js:77:13)
    at emit (events.js:169:7)
    at Query.handleError (/Users/mrorz/workspace/gis-inner/node_modules/pg/lib/query.js:108:8)
    at null.<anonymous> (/Users/mrorz/workspace/gis-inner/node_modules/pg/lib/client.js:171:26)
    at emitOne (events.js:77:13)
    at emit (events.js:169:7)
    at Socket.<anonymous> (/Users/mrorz/workspace/gis-inner/node_modules/pg/lib/connection.js:109:12)
    at emitOne (events.js:77:13)
    at Socket.emit (events.js:169:7)
    at readableAddChunk (_stream_readable.js:146:16)
    at Socket.Readable.push (_stream_readable.js:110:10)
    at TCP.onread (net.js:523:20)

Activity

  1. mickhansen commented on Feb 24, 2016

    @mickhansen
    Contributor

    Odd, that should simply work.

  2. added
    type: bug
    on Feb 24, 2016
  3. joewood commented on Feb 26, 2016

    @joewood

    I'm seeing something similar with the MSSQL provider. When any associations are used with an aggregate function all the fields seem to be included in the query, irrespective of the attributes/include/exclude list.

  4. dojiboy9 commented on Mar 9, 2016

    @dojiboy9

    ditto for mysql

  5. chillichicken commented on Jun 14, 2016

    @chillichicken

    can confirm this too for mysql

  6. mickhansen commented on Jun 14, 2016

    @mickhansen
    Contributor

    There's a confirmed issue with through.attributes

  7. yocontra commented on Jul 4, 2016

    @yocontra
    Contributor

    Can also confirm this for postgres on a belongsTo relationship, so definitely not just for through attributes

  8. dongseok0 commented on Mar 6, 2017

    @dongseok0

    Any workaround or updates there?
    It was fine with MySQL but I getting this error after I changed to MSSQL.

  9. saudpunjwani101 commented on Mar 11, 2017

    @saudpunjwani101

    Any solutions so far? the problem is a big pain in Postgres too

  10. doublerebel commented on Apr 25, 2017

    @doublerebel

    Count query generates the expected SQL, while min/max do not. v3.30.4:

    This is an actual example only user id has been anonymized.

    Count

    Query
    query =
      include: [
        {model: UserModel, as: "users", where: {id: user.id}, attributes: []}
      ]
      group: "users.id"
    
    LeadModel.count(query)
    SQL generated
    SELECT count("Lead"."id") AS "count" FROM "Leads" AS "Lead"
      INNER JOIN ("user_leads" AS "users.user_lead"
        INNER JOIN "Users" AS "users"
        ON "users"."id" = "users.user_lead"."UserId")
      ON "Lead"."id" = "users.user_lead"."LeadId" AND "users"."id" = 'sadlkjfsaljsl1234'
      GROUP BY users.id;
    Result
    [ { count: '22' } ]

    Min

    Query
    query =
      include: [
        {model: UserModel, as: "users", where: {id: user.id}, attributes: []}
      ]
      group: "users.id"
    
    LeadModel.min("LastModifiedDate", query)
    SQL generated
    SELECT min("LastModifiedDate") AS "min", "users.user_lead"."userId" AS "users.user_lead.userId", "users.user_lead"."leadId" AS "users.user_lead.leadId", "users.user_lead"."createdAt" AS "users.user_lead.createdAt", "users.user_lead"."updatedAt" AS "users.user_lead.updatedAt", "users.user_lead"."UserId" AS "users.user_lead.UserId", "users.user_lead"."LeadId" AS "users.user_lead.LeadId"
      FROM "Leads" AS "Lead"
      INNER JOIN ("user_leads" AS "users.user_lead"
        INNER JOIN "Users" AS "users"
        ON "users"."id" = "users.user_lead"."UserId")
      ON "Lead"."id" = "users.user_lead"."LeadId" AND "users"."id" = 'sadlkjfsaljsl1234'
      GROUP BY users.id;
    Result

    SequelizeDatabaseError: column "users.user_lead.userId" must appear in the GROUP BY clause or be used in an aggregate function

  11. doublerebel commented on Apr 25, 2017

    @doublerebel

    Found a Fix!

    By changing the query to add {includeIgnoreAttributes: false}, I now get the correct result:

    query =
      includeIgnoreAttributes: false
      include: [
        {model: UserModel, as: "users", where: {id: user.id}}
      ]
      group: "users.id"
    
    LeadModel.min("LastModifiedDate", query)
    SQL generated
    SELECT min("LastModifiedDate") AS "min"
      FROM "Leads" AS "Lead"
      INNER JOIN ("user_leads" AS "users.user_lead"
        INNER JOIN "Users" AS "users"
        ON "users"."id" = "users.user_lead"."UserId")
      ON "Lead"."id" = "users.user_lead"."LeadId" AND "users"."id" = 'sadlkjfsaljsl1234'
      GROUP BY users.id;
    Result

    2017-03-14T00:28:11.000Z

    Hope this helps someone else! I found the clue to (the undocumented feature) includeIgnoreAttributes in #6711, grepped the source and found it was being set to false in Model.count.

    EDIT: includeIgnoreAttributes: false makes attributes: [] superfluous, but if you do need any attributes from included Models, include them explicitly in the attributes array.

  12. stale commented on Jun 29, 2017

    @stale

    This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. If this is still an issue, just leave a comment 🙂

  13. yocontra commented on Jun 29, 2017

    @yocontra
    Contributor

    Still an issue, so yes keep it open.

  14. 24 remaining items

  15. self-assigned this
    on Oct 8, 2019
  16. Relequestual commented on Mar 30, 2020

    @Relequestual

    I found this previously merged PR which appeared to fix it in the event you use raw:true #4029

    However, at a guess, the test is bad because it didn't define the joining table to have a primary column in the definition. =/

  17. carlosingles commented on May 7, 2020

    @carlosingles

    This is still an issue for me, however I have found a workaround if you are using a Model definition for your join table.

    Using: [email protected]

    The following is a stripped down example of what I have (using Typescript):

    const User = sequelize.define('User', {
      active: sequelize.Sequelize.BOOLEAN
    });
    
    const Tenancy = sequelize.define('Tenancy', {
      name: sequelize.Sequelize.STRING
    });
    
    const TenancyUser = sequelize.define('TenancyUser', {
      isAdmin: sequelize.Sequelize.BOOLEAN
    })
    
    User.belongsToMany(Tenancy, through: { model: TenancyUser })
    Tenancy.belongsToMany(User, through: { model: TenancyUser })
    
    TenancyUser.belongsTo(User)
    TenancyUser.belongsTo(Tenancy)
    
    // Find how many active users for a Tenancy.id
    const id = 'someid'
    TenancyUser.findOne({
      attributes: [
        [
          sequelize.Sequelize.fn(
            'count',
            sequelize.Sequelize.col('User.id')
          ),
          'activeUsers'
        ]
      ],
      include: [
        {
          model: Models.Tenancy,
          where: {
            id: id
          },
          attributes: ['id'],
        },
        {
          model: Models.User,
          where: {
            active: true
          },
          attributes: [],
          required: false
        }
      ],
      group: [
        'Tenancy.id'
      ],
      // bypasses loading this into a Model and gives you a raw row
      // if you don't use this, `activeUsers` is not attached to the model
      raw: true
    }) as unknown as {
      // activeUsers is returned as a string NOT a number
      activeUsers: string;
      'Tenancy.id': string;
    }

    This ends up generating the following SQL:

    SELECT
        count("User"."id") AS "activeUsers"
        "Tenancy"."id" AS "Tenancy.id"
    FROM
        "TenancyUsers" AS "TenancyUsers"
        INNER JOIN "Tenancies" AS "Tenancy" ON "TenancyUsers"."TenancyId" = "Tenancy"."id"
            AND("Tenancy"."id" = 'someid')
        LEFT OUTER JOIN "Users" AS "User" ON "TenancyUsers"."UserId" = "User"."id"
        AND("User"."active" = TRUE)
    GROUP BY
        "Tenancy"."id"
    LIMIT 1;

    Which gives me a single row only with 'Tenancy.id' and 'activeUsers'.

  18. EinfachHans commented on Mar 1, 2021

    @EinfachHans

    It's 2021, i use Version 6.5.0 and this is still an issue

  19. laurelgr commented on Mar 12, 2021

    @laurelgr

    Same problem, got saved by the above workaround of includeIgnoreAttributes: false. I too believe this workaround should be documented until the issue is resolved!
    Between root attributes, include attributes and through attributes (plus trying out exclude magic) on top of group/aggregate it was a pain to debug and search a correct workaround.

  20. cirosantilli commented on Nov 9, 2021

    @cirosantilli

    Here's a more directly runnable repro with some assertions:

    const assert = require('assert');
    const { DataTypes, Sequelize } = require('sequelize');
    const sequelize = new Sequelize('tmp', undefined, undefined, Object.assign({
      dialect: 'postgres',
      host: '/var/run/postgresql',
    }));
    ;(async () => {
    const User = sequelize.define('User', {
      name: { type: DataTypes.STRING },
    }, {});
    const Post = sequelize.define('Post', {
      body: { type: DataTypes.STRING },
    }, {});
    User.belongsToMany(Post, {through: 'UserLikesPost'});
    Post.belongsToMany(User, {through: 'UserLikesPost'});
    await sequelize.sync({force: true});
    const user0 = await User.create({name: 'user0'})
    const user1 = await User.create({name: 'user1'})
    const user2 = await User.create({name: 'user2'})
    const post0 = await Post.create({body: 'post0'})
    const post1 = await Post.create({body: 'post1'})
    const post2 = await Post.create({body: 'post2'})
    // user0 likes post0.
    await user0.addPost(post0)
    // user1 likes post0 and post2
    await post1.addUsers([user0, user2])
    
    // Count how many posts each user has liked.
    let rows;
    rows = await User.findAll({
      attributes: [
        'name',
        [sequelize.fn('COUNT', sequelize.col('Posts.id')), 'count'],
      ],
      include: [
        {
          model: Post,
          attributes: [],
          required: false,
          through: {attributes: []},
        },
      ],
      group: ['User.name'],
      order: [[sequelize.col('count'), 'DESC']],
    })
    assert.strictEqual(rows[0].name, 'user0')
    assert.strictEqual(parseInt(rows[0].get('count'), 10), 2)
    assert.strictEqual(rows[1].name, 'user2')
    assert.strictEqual(parseInt(rows[1].get('count'), 10), 1)
    assert.strictEqual(rows[2].name, 'user1')
    assert.strictEqual(parseInt(rows[2].get('count'), 10), 0)
    assert.strictEqual(rows.length, 3)
    })().finally(() => { return sequelize.close() });
    

    package.json

    {
      "name": "tmp",
      "private": true,
      "version": "1.0.0",
      "dependencies": {
        "pg": "8.5.1",
        "pg-hstore": "2.3.3",
        "sequelize": "6.5.1",
        "sqlite3": "5.0.2"
      }
    }
    

    on PostgreSQL 13.4 Ubuntu 21.10 Node.js v14.17.0.

    Generated query:

    SELECT
      "User"."id",
      "User"."name",
      COUNT("Posts"."id") AS "count"
    FROM
      "Users" AS "User"
      LEFT OUTER JOIN (
        "UserLikesPost" AS "Posts->UserLikesPost"
        INNER JOIN "Posts" AS "Posts" ON "Posts"."id" = "Posts->UserLikesPost"."PostId"
      ) ON "User"."id" = "Posts->UserLikesPost"."UserId"
    GROUP BY
      "User"."name"
    ORDER BY
      "count" DESC;
    

    PostgreSQL disallows the Users.id from SELECT as it is not grouped by, and could lead to a random value being selected if there were different possible values. Some databases like SQLite allow that though, so it doesn't blow up there.

    Here's a similar older thread: #3256

    I can then work around as others mentioned by using BOTH raw and includeIgnoreAttributes: false as in:

    let rows;
    rows = await User.findAll({
      attributes: [
        'name',
        [sequelize.fn('COUNT', sequelize.col('Posts.id')), 'count'],
      ],
      raw: true,
      includeIgnoreAttributes: false,
      include: [
        {
          model: Post,
          required: false,
        },
      ],
      group: ['User.name'],
      order: [[sequelize.col('count'), 'DESC']],
    })
    assert.strictEqual(rows[0].name, 'user0')
    assert.strictEqual(parseInt(rows[0].count, 10), 2)
    assert.strictEqual(rows[1].name, 'user2')
    assert.strictEqual(parseInt(rows[1].count, 10), 1)
    assert.strictEqual(rows[2].name, 'user1')
    assert.strictEqual(parseInt(rows[2].count, 10), 0)
    assert.strictEqual(rows.length, 3)
    

    Another workaround: GROUP BY PK instead of by another non-PK UNIQUE field

    This is not always possible, sometimes you just want to GROUP BY non-UNIQUE fields. But if the field is unique, you can do this.

    The example above can be fixed by replacing:

      group: ['User.name'],
    

    by:

      group: ['User.id'],
    

    which is the most common use case for this type of action, full working querry:

    rows = await User.findAll({
      attributes: [
        'name',
        [sequelize.fn('COUNT', sequelize.col('Posts.id')), 'count'],
      ],
      include: [
        {
          model: Post,
          attributes: [],
          required: false,
          through: {attributes: []},
        },
      ],
      group: ['User.id'],
      order: [[sequelize.col('count'), 'DESC']],
    })
    

    It appears that as long as the GROUP BY uniquely defines the row, you can SELECT other rows according to SQL 99: https://dba.stackexchange.com/a/141600/33332

    TODO but then why:

    const User = sequelize.define('User', {
      name: {
        type: DataTypes.STRING,
        unique: true,
        allowNull: false,
      },
    }, {});
    

    doesn't fix it as well?

    EDIT: Postgresql have a TODO here for that: https://github.com/postgres/postgres/blob/REL_13_5/src/test/regress/sql/functional_deps.sql#L27 they want it to work, but it doesn't yet, as of 13.5 only GROUP BY PRIMARY KEY allows you to access other columns. Also relevant: https://dba.stackexchange.com/questions/158015/why-can-i-select-all-fields-when-grouping-by-primary-key-but-not-when-grouping-b

  21. liorsion commented on Feb 4, 2022

    @liorsion

    I can try to help solve this, the issue is with this line, but it's not clear why it's needed:

      if (options.attributes && !options.raw && this.primaryKeyAttribute && !options.attributes.includes(this.primaryKeyAttribute) && (!options.group || !options.hasSingleAssociation || options.hasMultiAssociation)) {
    
  22. moda20 commented on Jul 23, 2022

    @moda20

    Hey, This is 2022 and i am getting an error where sequelize will add an 'id' out of nowhere and break my group query.
    here is the query :

    const truncWithIntervalLiteral = Sequelize.literal("CONCAT ( week(checkDate, 0), '_', year(checkDate) )")
            const averagePrice = Sequelize.literal("AVG (COALESCE(price, minPrice))")
            return item
                .findAndCountAll({
                    include: [
                        {
                            model: price,
                            as: "prices",
                            attributes: [
                                [truncWithIntervalLiteral, "weekly"],
                                [averagePrice, "AveragePricePerWeek"],
                            ],
                            separate: true,
                            group: ["weekly", "product_id"],
                        },
                    ],
                })
    

    the resulting sql query is :

    SELECT **`id`,** CONCAT ( week(checkDate, 0), '_', year(checkDate) ) AS `weekly`, AVG (COALESCE(price, minPrice)) AS `AveragePricePerWeek`, `product_id` FROM `price` AS `price` WHERE `price`.`product_id` IN ('30133', '35526', '35040') GROUP BY `weekly`, `product_id`;
    

    That bold id is not supposed to be there. I tried all the solutions above and it still creates the same sql query with an extra id
    Why is this an issue are we doing it the """wrong""" way ?

  23. laurelgr commented on Aug 4, 2022

    @laurelgr

    @moda20 you are using findAndCountAll instead of findAll so that may be why the previous solutions don't work for you. I'm not familiar enough with it to tell if there is any relevant difference, so you should first try with a findAll to make sure the problem is not unrelated. And I am even less familiar with the separate option.

    Also, your resulting query only uses one table price without any join, and you only have 1 undesired column id instead of all the existing columns of your table, so I believe your issue might be related specifically to the use of separate.

    This issue is about generated join queries selecting all columns. If you run separate queries, there is no JOIN in the database query itself since Sequelize will do the join instead.

    I see you created your own issue though so I won't go further here. :)

  24. 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

    type: bug

    Type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions