2

I want to run a query with results sort using the primary key and also limit the number of return results. For example:

return Things.findAll({ attributes: [ 'id', 'status', 'otherField' ], limit: 2, order: [['id', 'DESC']] })

when the query is build, it generate the following SQL statement:

... ORDER BY [Source].[id] DESC, [id] OFFSET 0 ROWS FETCH NEXT 2 ROWS ONLY

Because id is the primary key and the sort parameter is also id I get the following error:

'A column has been specified more than once in the order by list. Columns in the order by list must be unique.'

I am using sequelize 3.30.4 with tedious 2.0.0 connecting to a Microsoft SQL server 2017.

Thank you.

Jerome Kelly
  • 151
  • 1
  • 10

2 Answers2

0

The order array should contain arrays/tuples. Try this:

return Things.findAll({
  attributes: [
    'id',
    'status',
    'otherField'
  ],
  limit: 2,
  order: [ 
    ['id', 'DESC']
  ]
})
ivo
  • 1,103
  • 10
  • 13
0

By the default, Sequelize create createdAt column in each table. So you can handle this issue by doing like this:

return Things.findAll({
  attributes: [
    'id',
    'status',
    'otherField'
  ],
  limit: 2,
  order: [ 
    ['createdAt', 'DESC']
  ]
})

Do the sorting by using column createdAt as the param, the sorting result have same result as you do with id column

Blackjack
  • 1,016
  • 1
  • 20
  • 51