Sling Academy
Home/Node.js/Selecting a Single Random Record in Sequelize.js (3 Ways)

Selecting a Single Random Record in Sequelize.js (3 Ways)

Last updated: December 29, 2023

Selecting a random record from a database table is a common requirement in software development. Sequelize, a popular Node.js ORM for relational databases, offers several methods to achieve this. This article will explore three different solutions to select a single random record with Sequelize.

1. Order by Random

This approach involves instructing the database to sort the results in a random order and then selecting the top result from that order.

  1. Import Sequelize and your model.
  2. Use the findAll method with the order attribute set to sequelize’s random function (sequelize.random()).
  3. Limit the query result to 1.

Code example:

const { ModelName } = require('./models');

ModelName.findAll({
    order: sequelize.random(),
    limit: 1
})
.then(record => {
    console.log(record);
})
.catch(error => {
    console.error(error);
});

Pros:

  • Simple and easy to understand.
  • Directly supported by Sequelize and most SQL databases.

Cons:

  • May not be efficient for large tables as it requires sorting the entire table.

2. Random Offset

Description: Determine the total count of records in the table, generate a random offset, and then fetch the record positioned at that offset.

  1. Import Sequelize and your model.
  2. Calculate the total number of records in the table with count.
  3. Generate a random offset.
  4. Use the findOne method with the offset attribute set to the random offset.

Code example:

const { ModelName } = require('./models');

ModelName.count()
.then(count => {
    const rand = Math.floor(Math.random() * count);
    ModelName.findOne({ offset: rand })
    .then(record => {
        console.log(record);
    })
    .catch(error => {
        console.error(error);
    });
});

Pros:

  • Avoids sorting large tables.
  • Fairly straightforward to implement.

Cons:

  • May not be efficient for large tables if indexes are not set up properly.
  • Counting total records might be expensive for large tables.

3. Raw SQL Query

Description: Use a raw SQL query with a database-specific function to fetch a random record.

  1. Import Sequelize;
  2. Use sequelize.query to execute a raw SQL statement that retrieves a random record.

Code example:

const { sequelize } = require('./models');
const randomRecordQuery = 'SELECT * FROM "ModelNames" ORDER BY RANDOM() LIMIT 1';

sequelize.query(randomRecordQuery, { type: sequelize.QueryTypes.SELECT })
.then(record => {
    console.log(record);
})
.catch(error => {
    console.error(error);
});

Pros:

  • Offers full control over the SQL query.
  • Performance can be optimized with database-specific functions.

Cons:

  • Database portability might be affected by using raw SQL.
  • Raw SQL is more prone to SQL injection attacks if not written carefully.

Conclusion

Selecting a single random record in Sequelize can be done in multiple ways, each with its own set of trade-offs. The Order by Random method is the most straightforward but may have performance issues on large datasets. The Random Offset method avoids table sorting but still carries performance considerations. Lastly, using a raw SQL query is powerful and flexible but also requires caution to prevent injection vulnerabilities. The choice of method will depend on the specific use case, table size, and database performance considerations.

Next Article: How to Select Multiple Random Records in Sequelize.js

Previous Article: Filtering by Multiple Conditions in Sequelize

Series: Sequelize.js Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates