Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelize with Postgresql order by with null values first

I would like to construct a sequelize query that returns rows in ascending order with NULL values first.

I have a timestamp when an email is sent, which is NULL if an email has never been sent.

Here's the Postgres query that does what I want:

SELECT quote, quote_id
FROM quotes
WHERE book_id = '${book_id}'
ORDER BY last_emailed ASC NULLS FIRST
LIMIT 5

The sequelize query I have is:

const res = await Quote.findAll({
  attributes: ['quote', 'quote_id'],
  where: { book_id },
  order: [
    ['last_emailed', 'ASC']
  ],
  limit: 5,
})

But this returns all NULL values last. It otherwise does what I want

like image 761
Ryan Avatar asked Jun 02 '19 03:06

Ryan


People also ask

How are NULLs sorted by default in the ORDER BY clause?

How Are NULLs Sorted by Default? The SQL standard does not define the default ordering of NULLs. What does this mean? If you apply the ORDER BY clause to a column with NULLs, the NULL values will be placed either first or last in the result set.

How do you ORDER BY in Sequelize?

To add an ORDER BY clause to the Sequelize query methods, you need to specify the order option inside the query methods you used for retrieving data from your database. Now you are tasked with retrieving the data from the table, ordering the result with the following rules: Sort by population column in descending order.

Can you use Sequelize with Postgres?

The simplest way to think of Object Relational Mapping is as a process for accessing a relational database — Postgres in our instance — from an object-oriented language like JavaScript. Sequelize allows us to interact with a Postgres database using JavaScript instead of SQL.

How do you use OP in Sequelize?

You need to import the object from Sequelize to use it in your code: const { Sequelize, Op } = require("sequelize"); When you call the query methods from your model, you can use the Op object properties to create SQL queries with operators.


1 Answers

Adding NULLS FIRST after ASC should give you the expected result :

const res = await Quote.findAll({
   attributes: ['quote', 'quote_id'],
   where: { book_id },
   order: [
      ['last_emailed', 'ASC NULLS FIRST']
   ],
   limit: 5,
})
like image 107
Murat Avatar answered Nov 15 '22 01:11

Murat