Skip to content

Postgres: jsonb columns do not order ints correctly #9040

Open

Description

@joeybaker

What are you doing?

When trying to use the order operation on a jsonb column that has number values, the results are ordered as text, not numbers.

const model = sequelize.define('Model', { data: DataTypes.JSONB })
model.create({data: {number: 1}})
model.create({data: {number: 101}})
model.create({data: {number: 2}})
model.findAll({order: ['data.number']})
  .then(r => r.map(m => m.data.number))
  .then(console.log)

// expected
[1, 2, 101]

// actual
[1, 101, 2]

What do you expect to happen?

The data is stored as numbers, so the resulting order should be numerically sorted.

This does work:

const model = sequelize.define('Model', { data: DataTypes.JSONB })
model.create({data: {number: 1}})
model.create({data: {number: 101}})
model.create({data: {number: 2}})
model.findAll({order: db.sequelize.literal(`"Model"."data"->'number'`)}) // ← custom order sql
  .then(r => r.map(m => m.data.number))
  .then(console.log)

// expected
[1, 2, 101]

// actual
[1, 2, 101]

What is actually happening?

The resulting order is based on sorting the JSON data as though it were text. This results in the wrong order.

This appears to be the line that's causing the problem:

return `(${quotedColumn}#>>${pathStr})`;

If it's changed to:

return `(${quotedColumn}->${pathStr})`;

…the order returns as expected. However, this change breaks a bunch of integration tests.

Dialect: postgres
Dialect version: 6.4.2
Database version: 10.1
Sequelize version: 4.32.2
Tested with latest release: Yes (If yes, specify that version)

Note : Your issue may be ignored OR closed by maintainers if it's not tested against latest version OR does not follow issue template.

Activity

  1. added
    type: bug
    on Feb 13, 2018
  2. mytharcher commented on Jun 11, 2020

    @mytharcher

    Same here in 2020. And even more, sequelize generated more braces in SQL.

    From:

    order: [
      ['stats.count', 'desc']
    ]

    To:

    ORDER BY ("Customer"."stats"#>>'{count}') DESC

    Don't know why the braces appears.

    For now I can only change that columns into literal:

    order: [
      [sequelize.literal('"Customer"."stats"->\'count\'', 'desc']
    ]

    and this works.

    BTW, I am using v4.44.3.

  3. added theissue type on Mar 9, 2025
  4. removed
    type: bug
    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

    No labels
    No labels

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions