alferguson_JS
alferguson_JS

Reputation: 75

Orderby on Boolean column with Knex.js on Postgres

How can I use knex.js's orderBy method on a boolean column for a postgres database? Using "asc" or "desc" in the object taken by orderby doesn't work (rows with true or false appear after each other).

Here is some sample code (assuming its wrapped in an async function and the enabled column is a boolean):

const users = await knex("person").orderBy("enabled", "desc");

Is there a knex method that is better suited for this or should I run a raw query within knex's orderByRaw method? What would the raw SQL query be? I don't need to worry about null fields at the moment either but there are rows where the enabled column is null as it is neither true or false.

Upvotes: 0

Views: 1133

Answers (1)

alferguson_JS
alferguson_JS

Reputation: 75

Sorry, this line of code is actually working. In my project that I can't share, I was doing an orderBy with an array of sorts that default to "asc". When I removed all the sorts except for the boolean sort, it worked where "desc" had true show first and "asc" had false show first. I don't know how knex and/or postgres handles the orderBy array and which sorts have higher priority but I should have fixed the default issue beforehand.

I'll leave this question and answer here incase other people have this issue and maybe also have a similar situation with using an array of sorts.

Upvotes: 0

Related Questions