Skip to content
Advertisement

How to pass a seed value to random order function in Sequelize

In SQL dialects you can sort by random and you can pass a seed to the random function in order to get a repeatable random order of rows.

In MySQL you’d do it like this:

SELECT * FROM `users` ORDER BY RAND("192.168.1.1")

I’m aware of how to use the RAND function when querying with Sequelize:

users.findAll({
  order: [sequelize.random()],
});

I can’t seem to figure out how to pass a seed to the random function.

I’ve looked at the docs: https://sequelize.org/master/class/lib/sequelize.js~Sequelize.html#instance-method-random

And it looks like the sequelize.random() function doesn’t take any parameters.

Is this possible?

Advertisement

Answer

If you wish your query will work only in MySQL then just use sequelize.fn:

users.findAll({
  order: [sequelize.fn('RAND', '192.168.1.1')],
});
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement