Skip to content

SUM and include association gives "..id must appear in GROUP BY clause" #3256

Open

Description

@maplesap

I'm trying to sum up the total amount for a particular user, using a column in another table. It is similar to this issue which was resolved: #2353

But I tried to apply it, but I get an error:

user
    hasMany(models.history)

history
    amount: DataTypes.INTEGER,
    belongsTo(models.user)

Try query:

models.user.find({where: { id: 1 }, 
  group:['user.id'], 
  attributes: [[Sequelize.fn('SUM', Sequelize.col('histories.amount')), 'total']], 
  include: [{model: models.history}]
}).then(function(user) {
    console.log(user);
}).catch(function(error) { console.log(error) });

Which will throw the error:

{ name: 'SequelizeDatabaseError',
  message: 'column "histories.id" must appear in the GROUP BY clause or be used in an aggregate function',
  parent: 
   { [error: column "histories.id" must appear in the GROUP BY clause or be used in an aggregate function]
     name: 'error',
     length: 167,
     severity: 'ERROR',
     code: '42803',
     detail: undefined,
     hint: undefined,
     position: '59',
     internalPosition: undefined,
     internalQuery: undefined,
     where: undefined,
     schema: undefined,
     table: undefined,
     column: undefined,
     dataType: undefined,
     constraint: undefined,
     file: 'parse_agg.c',
     line: '911',
     routine: 'check_ungrouped_columns_walker',
     sql: 'SELECT "user"."id", SUM("histories"."amount") AS "total", "histories"."id" AS "histories.id", "histories"."amount" AS "histories.amount", "histories"."other" AS "histories.other", "histories"."createdAt" AS "histories.createdAt", "histories"."updatedAt" AS "histories.updatedAt", "histories"."userId" AS "histories.userId", "histories"."itemId" AS "histories.itemId" FROM "users" AS "user" LEFT OUTER JOIN "histories" AS "histories" ON "user"."id" = "histories"."userId" WHERE "user"."id" = 1 GROUP BY "user"."id";' },
  original: 

The sql that is generated is:

Executing (default): CREATE TABLE IF NOT EXISTS "users" ("id"   SERIAL , "name" VARCHAR(255), PRIMARY KEY ("id"));
Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND a.attnum = ANY(ix.indkey) AND t.relkind = 'r' and t.relname = 'users' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
Executing (default): DROP TABLE IF EXISTS "items" CASCADE;
Executing (default): CREATE TABLE IF NOT EXISTS "items" ("id"   SERIAL , "name" VARCHAR(255), PRIMARY KEY ("id"));
Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND a.attnum = ANY(ix.indkey) AND t.relkind = 'r' and t.relname = 'items' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
Executing (default): DROP TABLE IF EXISTS "histories" CASCADE;
Executing (default): CREATE TABLE IF NOT EXISTS "histories" ("id"  SERIAL , "amount" INTEGER, "other" VARCHAR(255), "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL, "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL, "userId" INTEGER REFERENCES "users" ("id") ON DELETE SET NULL ON UPDATE CASCADE, "itemId" INTEGER REFERENCES "items" ("id") ON DELETE SET NULL ON UPDATE CASCADE, PRIMARY KEY ("id"));
Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND a.attnum = ANY(ix.indkey) AND t.relkind = 'r' and t.relname = 'histories' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
Executing (default): INSERT INTO "users" ("id","name") VALUES (DEFAULT,'bob') RETURNING *;
Executing (default): INSERT INTO "items" ("id","name") VALUES (DEFAULT,'itme') RETURNING *;
Executing (default): INSERT INTO "histories" ("id","amount","userId","itemId","updatedAt","createdAt") VALUES (DEFAULT,5,1,1,'2015-03-03 03:38:18.110 +00:00','2015-03-03 03:38:18.110 +00:00') RETURNING *;
Executing (default): INSERT INTO "histories" ("id","amount","userId","itemId","updatedAt","createdAt") VALUES (DEFAULT,10,1,1,'2015-03-03 03:38:18.114 +00:00','2015-03-03 03:38:18.114 +00:00') RETURNING *;





Executing (default): SELECT "user"."id", SUM("histories"."amount") AS "total", "histories"."id" AS "histories.id", "histories"."amount" AS "histories.amount", "histories"."other" AS "histories.other", "histories"."createdAt" AS "histories.createdAt", "histories"."updatedAt" AS "histories.updatedAt", "histories"."userId" AS "histories.userId", "histories"."itemId" AS "histories.itemId" FROM "users" AS "user" LEFT OUTER JOIN "histories" AS "histories" ON "user"."id" = "histories"."userId" WHERE "user"."id" = 1 GROUP BY "user"."id";

I also found a similar bug report (using count instead of sum):
#3009

I think the two might be related. Is there a current workaround?

Using sequelize 2.0.3, postgres dialect

Activity

  1. added
    type: bug
    on Mar 3, 2015
  2. mickhansen commented on May 20, 2015

    @mickhansen
    Contributor

    Can be fixed with include.attributes = [] on 3.0.1

  3. ayankelevichionia commented on Jun 3, 2015

    @ayankelevichionia

    Hi mickhansen,
    I'm experiencing this same issue on version 3.1.1, postgres dialect.
    I'm not sure were to include the "include.attributes = []" or how to use it.
    Can you provide me with an example on how to use this?

  4. mickhansen commented on Jun 4, 2015

    @mickhansen
    Contributor

    @ayankelevichionia You'd have to show some code for me to show you how to use it, but you simply add attributes: [] to your include options set (include: [{ .. options .. }])

  5. ayankelevichionia commented on Jun 4, 2015

    @ayankelevichionia

    @mickhansen Here's an example of what I'm trying to do:

    models.inventory_transaction.findAll(
            {   attributes: [[models.sequelize.fn('sum', models.sequelize.col('quantity')), 'total']],
                include : [
                            {
                                model : models.product_entry,
                                attributes: [],
                                include : [
                                            {
                                                model : models.product,
                                                attributes: [['name', 'name']]
                                            }
                                        ]
                            }
                        ],
                group : ['inventory_transaction.product_entry_id', 'inventory_transaction.created_date', 'name' ]
            }
        )
    

    This is the sql query that gets generated:

    'SELECT "inventory_transaction"."id", sum("quantity") AS "total", "product_entry.product"."id" AS "product_entry.product.id", "product_entry.product"."name" AS "product_entry.product.name" FROM "inventory_transaction" AS "inventory_transaction" LEFT OUTER JOIN "product_entry" AS "product_entry" ON "inventory_transaction"."product_entry_id" = "product_entry"."id" LEFT OUTER JOIN "product" AS "product_entry.product" ON "product_entry"."product_id" = "product_entry.product"."id" GROUP BY "inventory_transaction"."product_entry_id", "inventory_transaction"."created_date", "name";'
    

    As you can see, it is including the Id of inventory_transaction and product. How would I go to exclude them so I don't recieve the error?

    Thanks & Regards.

  6. mickhansen commented on Jun 5, 2015

    @mickhansen
    Contributor

    @ayankelevichionia What version is this?

  7. ayankelevichionia commented on Jun 5, 2015

    @ayankelevichionia

    @mickhansen According to the package.json, it is version 3.1.1

  8. mickhansen commented on Jun 6, 2015

    @mickhansen
    Contributor

    @ayankelevichionia What does npm list say? you might have forgotten to npm install

  9. ayankelevichionia commented on Jun 9, 2015

    @ayankelevichionia

    @mickhansen
    npm list says:

    +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦   +-- [email protected]
    +-- [email protected] extraneous
    +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    +-- UNMET DEPENDENCY debug@~2.1.1
    +-- [email protected]
    ¦ +-- [email protected]
    ¦ ¦ +-- [email protected]
    ¦ ¦ ¦ +-- [email protected]
    ¦ ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ ¦ +-- [email protected]
    ¦ ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ ¦ +-- [email protected]
    ¦ ¦ +-- [email protected]
    ¦ ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ ¦ +-- [email protected]
    ¦ ¦ +-- [email protected]
    ¦ ¦   +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    +-- UNMET DEPENDENCY method-override@~2.1.1
    +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦   +-- [email protected]
    +-- [email protected]
    ¦ +-- [email protected]
    ¦ ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ ¦ +-- [email protected]
    ¦ ¦ ¦ +-- [email protected]
    ¦ ¦ ¦ +-- [email protected]
    ¦ ¦ ¦ +-- [email protected]
    ¦ ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ ¦ +-- [email protected]
    ¦ ¦   +-- [email protected]
    ¦ +-- [email protected]
    ¦ ¦ +-- [email protected]
    ¦ ¦   +-- [email protected]
    ¦ ¦     +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ ¦ +-- [email protected]
    ¦ ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ ¦ +-- [email protected]
    ¦ ¦ +-- [email protected]
    ¦ ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ ¦ +-- [email protected]
    ¦ ¦ ¦ +-- [email protected]
    ¦ ¦ ¦ ¦ +-- [email protected]
    ¦ ¦ ¦ ¦   +-- [email protected]
    ¦ ¦ ¦ +-- [email protected]
    ¦ ¦ ¦   +-- [email protected]
    ¦ ¦ ¦   +-- [email protected]
    ¦ ¦ ¦   +-- [email protected]
    ¦ ¦ +-- [email protected]
    ¦ ¦ +-- [email protected]
    ¦ ¦   +-- [email protected]
    ¦ ¦   +-- [email protected]
    ¦ +-- [email protected]
    +-- UNMET DEPENDENCY mysql@^2.7.0
    +-- [email protected] extraneous
    +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ ¦ +-- [email protected]
    ¦ ¦   +-- [email protected]
    ¦ +-- [email protected]
    +-- [email protected]
    ¦ +-- [email protected]
    +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    ¦ +-- [email protected]
    +-- [email protected]
      +-- [email protected]
      ¦ +-- [email protected]
      +-- [email protected]
      +-- [email protected]
      +-- [email protected]
    
    npm ERR! missing: debug@~2.1.1, required by [email protected]
    npm ERR! missing: method-override@~2.1.1, required by [email protected]
    npm ERR! missing: mysql@^2.7.0, required by [email protected]
    npm ERR! extraneous: [email protected] c:\gh\LMIVendingMachine\node_modules\path
    npm ERR! extraneous: [email protected] c:\gh\LMIVendingMachine\node_modules\config
    
  10. mickhansen commented on Jun 10, 2015

    @mickhansen
    Contributor

    Hmm that's odd.

  11. nadavoosh commented on May 4, 2016

    @nadavoosh

    Is this issue resolved? I'm running into it now.

  12. ieow commented on Dec 12, 2016

    @ieow

    any workaround on this issue?

  13. jorbascrumps commented on Jan 6, 2017

    @jorbascrumps

    Having a similar issue with v3.10.8.

  14. rajshrimohanks commented on Jan 18, 2017

    @rajshrimohanks

    Same here v3.29.0

  15. saudpunjwani101 commented on Mar 11, 2017

    @saudpunjwani101

    same here even at 4.0 +

  16. 41 remaining items

  17. rener172846 commented on Aug 13, 2019

    @rener172846

    I think this is the shortest codes:

    await models.Post.findAll({
      subQuery: false
      include: [
        { model: models.PostComment, as: 'reply', attributes: [
          [ Sequelize.fn('COUNT', Sequelize.col("reply.id")), "count" ],
        ] },
      ],
      group: ["post.id"]
    })

    So only one field - "reply"."count" is included on the post table.
    And following is the generated sql from that:

    SELECT "post"."id", "post"."title", "post"."description",
        "reply"."id" AS "reply.id", COUNT("reply"."id") AS "reply.count" 
    FROM "posts" AS "post" 
    LEFT OUTER JOIN "post_comments" AS "reply" ON "post"."id" = "reply"."post_id" 
    GROUP BY "post"."id"

    And this sql occurs error - "column \"reply.id\" must appear in the GROUP BY clause or be used in an aggregate function".
    So the purpose is just remove "reply"."id" field from the joined table post_comments.
    On the included model, if attributes is once specified, the primary key shouldn't be added automatically because it will be cause of the group by issue when there is aggregate field.

    Following sql is what I want as shorten:

    SELECT "post"."id", "post"."title", "post"."description",
        COUNT("reply"."id") AS "reply.count" 
    FROM "posts" AS "post" 
    LEFT OUTER JOIN "post_comments" AS "reply" ON "post"."id" = "reply"."post_id" 
    GROUP BY "post"."id"

    Hope is this clear and helpful for your working @papb

  18. papb commented on Aug 13, 2019

    @papb
    Member

    @rener172846 One more thing: you have posted a code snippet that shows the problem but is not entirely self-contained (i.e. I can't just copy-paste it and run it). Can you (or someone else) please provide a SSCCE (also known as MCVE/reprex)?

  19. papb commented on Oct 10, 2019

    @papb
    Member

    @rener172846 @jorbascrumps The reason I'm asking for an SSCCE is that investigating this issue as-is would need extra effort from maintainers (and our time is really short). There is a sequelize-sscce repository to assist with this now. For those hoping for a fix, doing this would greatly help and in theory is something anyone encountering this issue should be able to do. Thanks for understanding! Don't forget to link to this issue in the new issue.

  20. jorbascrumps commented on Oct 21, 2019

    @jorbascrumps

    @papb I don't recall why I 👎 your comment. Thank you for taking the initiative in creating that repo and for continuing to investigate this issue.

  21. papb commented on Oct 21, 2019

    @papb
    Member

    @jorbascrumps Ok, thanks 👍

  22. mrdulin commented on Mar 19, 2020

    @mrdulin

    same issue. I have two tables: Groups and Employees and the relationship between them is Many-to-Many. So there is a through table named GroupEmp. I want to group by Groups.groupId and count the employees for each group. Got error:

    error: column "Employees->GroupEmp.groupId" must appear in the GROUP BY clause or be used in an aggregate function

    I had tried include.attributes: [], it doesn't work.

    Here is the SSCCE: https://github.com/mrdulin/node-sequelize-examples/tree/master/src/examples/stackoverflow/59154486-todo

  23. aristov commented on Mar 21, 2020

    @aristov
    Contributor

    Probably the same issue: #12020

  24. EinfachHans commented on Feb 13, 2021

    @EinfachHans

    Same Issue here...

  25. EinfachHans commented on Apr 8, 2021

    @EinfachHans

    This issue was created 6 years ago. Some did create a SSCCE over one year ago. I get this for nearly every a bit conplex query. When can we get a fix? 😩

  26. removed
    status: awaiting response
    on Apr 8, 2021
  27. arielectron commented on Sep 5, 2021

    @arielectron

    Hi.

    I was able to solve it using raw option with true value.

          where,
          include,
          includeIgnoreAttributes: false,
          group: ['status'],
          subQuery: false,
          raw: true
        })
    
  28. marscrusader commented on Oct 7, 2021

    @marscrusader

    For anybody using through or junction tables, here's the solution:

    {
        limit,
        offset,
        where: { ... },
        subQuery: false,
        attributes: {
           include: [[Sequelize.fn('count', Sequelize.col('example_table.example_col')) ,'exampleCount']],
        },
        // includeIgnoreAttributes: false,    <- this line will ignore all attributes from all associations
        include: [
          {
            model: TableA, required: true, attributes: [], through: { attributes: [] }   <- ignore all attributes for this association
          },
          {
            model: TableB, required: true, attributes: ['name'], through: { attributes: [] }  <- retain "name" attribute for this association
          },
          {
            model: TableC, required: false, attributes: [],
          },
        ],
        group: ['TableA.id', 'TableB.id']
    }
    

    Adding through: { attributes: [] } will ignore the attributes from the through table.
    Tested for postgres

  29. cirosantilli commented on Nov 9, 2021

    @cirosantilli

    This thread a more precise related report: #5481 my minimal repro: #5481 (comment)

    The problem is database specific: SQLite allows columns that are not GROUP BY in the SELECT, which can allow for unpredictable values being selected in the output, but PostgreSQL doesn't and gives the error.

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