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
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.
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.
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.
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.
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,
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With