Skip to content

.sum on an empty matching set results in NaN #6299

Closed

Description

@yktv4

What you are doing?

I'm trying to use the SUM aggregate on an empty matching set

//imagine we have Payments table empty yet
Payment.sum('amount').then(console.log)
//logs NaN

What do you expect to happen?

I'd like the value in this case to be 0 since by definition, a sum is a number, not a NaN.

Why this happens?

I've quickly found that this happens due to this:

//node_modules/sequelize/lib/query-interface.js:702
//result contains null as we don't have any matching records
result = parseFloat(result);

What could be done?

since the dataType requested is dataType instanceof DataTypes.DECIMAL || dataType instanceof DataTypes.FLOAT as stated in node_modules/sequelize/lib/query-interface.js:701, we can additionally check whether the result variable contains null and in this case return 0. I can submit a PR with this fix easily though I'd first like to ensure that I'm not the only one expecting 0 in this case rather than NaN.

__Dialect: postgres
__Database version: 9.5.3
__Sequelize version: 3.19.3

Activity

  1. sushantdhiman commented on Jul 18, 2016

    @sushantdhiman
    Contributor

    Sequelize version ? I remember fixing this issue, I think we already have test for something like this.

    Edit: I remembered fixing this for count but I think other aggregate methods still have this issue. I will need Sequelize + DB version @yktv4

  2. yktv4 commented on Jul 18, 2016

    @yktv4
    Author

    @sunshinewyin sorry for not providing it initially. here it is: 3.19.3

  3. added
    type: bug
    on Jul 19, 2016
  4. janudewangga commented on Mar 14, 2018

    @janudewangga

    Is it fixed yet? I just had a same problem in 4.36.1

  5. added
    good first issue
    and removed on Mar 15, 2018
  6. bminer commented on Sep 11, 2018

    @bminer

    This is silly IMHO. sum should return null or 0. Not NaN.

  7. jdestep93 commented on Sep 11, 2018

    @jdestep93

    I agree with @bminer

  8. yktv4 commented on Sep 11, 2018

    @yktv4
    Author

    I guess mentioning any core developer could help. anyone knows their handles?

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

    good first issuetype: bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions