Sling Academy
Home/Node.js/How to Select Multiple Random Records in Sequelize.js

How to Select Multiple Random Records in Sequelize.js

Last updated: December 29, 2023

Sequelize is a popular ORM for Node.js that supports multiple SQL dialects. When working with large datasets, you might sometimes need to retrieve a subset of records in a random order – for example, to display random user profiles or products. This article will walk you through the steps to select multiple random records using Sequelize, providing basic to advanced examples.

Getting Started

To begin, ensure you have Sequelize set up in your project. If not, you can install it using npm or yarn:

npm install sequelize
// OR
yarn add sequelize

You also need to set up a connection to your database and define your models as per your schema.

Basic Random Selection

The simplest way to fetch random records is by using the ORDER BY RANDOM() clause (or a similar function, depending on your database system). In Sequelize, you can order your query results randomly like this:

const YourModel = require('./models/YourModel');

async function fetchRandomRecords() {
  const records = await YourModel.findAll({
    order: Sequelize.literal('RAND()'), // Use RANDOM() for PostgreSQL
    limit: 5
  });
  return records;
}

Random Selection with Conditions

Sometimes you might want to fetch random records based on a certain condition. For instance, selecting random active users:

async function fetchRandomActiveUsers() {
  const activeUsers = await YourModel.findAll({
    where: {
      status: 'active'
    },
    order: Sequelize.literal('RAND()'),
    limit: 5
  });
  return activeUsers;
}

Efficient Random Selection

Using ORDER BY RANDOM() might not be efficient for large datasets. In such cases, you can use a different strategy such as randomly generating a set of IDs to fetch. Here’s how you can do that:

const { Op } = require('sequelize');

async function fetchEfficientRandomRecords() {
  const count = await YourModel.count();
  const randomIds = Array.from({ length: 5 }, () => Math.floor(Math.random() * count) + 1);

  const records = await YourModel.findAll({
    where: {
      id: {
        [Op.in]: randomIds
      }
    }
  });

  return records;
}

Advanced Techniques

In databases like PostgreSQL, you can use table sampling to fetch random records more efficiently. Sequelize doesn’t have built-in support for this, but you can still execute raw SQL queries:

async function fetchSampledRandomRecords() {
  const records = await sequelize.query(
    'SELECT * FROM "YourModel" TABLESAMPLE SYSTEM (1) LIMIT 5',
    { model: YourModel }
  );
  return records;
}

Conclusion

This tutorial provided various methods for selecting multiple random records with Sequelize. Remember that while ORDER BY RANDOM() is straightforward, it may not be the most performance-friendly option for larger tables. Use advanced techniques such as random ID selection or table sampling for more efficiency. Always test different strategies and keep in mind the size and nature of your dataset when choosing the best approach.

Next Article: How to Count the Number of Records in Sequelize

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

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