Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knex.js multiple orderBy() columns

Is it possible to do multiple orderBy() columns?

knex
  .select()
  .table('products')
  .orderBy('id', 'asc')

The orderBy() chainable only takes a single column key and a sort value, but how can I order by multiple columns?

like image 488
Ian Jones Avatar asked Aug 31 '25 15:08

Ian Jones


2 Answers

You can call .orderBy multiple times to order by multiple columns:

knex
  .select()
  .table('products')
  .orderBy('name', 'desc')
  .orderBy('id', 'asc')
like image 129
Kevin Avatar answered Sep 08 '25 06:09

Kevin


The Knex orderBy function also receives an array:

knex('users').orderBy(['email', 'age', 'name'])

or

knex('users').orderBy(['email', { column: 'age', order: 'desc' }])

or

knex('users').orderBy([{ column: 'email' }, { column: 'age', order: 'desc' }])
like image 31
Rafael Zeffa Avatar answered Sep 08 '25 07:09

Rafael Zeffa