Sling Academy
Home/Node.js/Sequelize.js: How to Count Distinct Rows

Sequelize.js: How to Count Distinct Rows

Last updated: December 29, 2023

Introduction

Sequelize.js is a powerful Node.js ORM for interacting with databases such as PostgreSQL, MySQL, MariaDB, SQLite, and MSSQL. One of the challenges in database management is efficiently counting distinct rows based on specific criteria. This tutorial will guide you through several methods to count distinct rows using Sequelize.js, starting from a simple count to more advanced scenarios utilizing associations and complex queries.

Basic Usage of Count

Let’s begin by looking at the basic syntax for counting rows in a Sequelize model:

const count = await Model.count();
console.log(`There are ${count} rows in the Model table.`);

However, if we want to count distinct values for a particular column, we can use the distinct option:

const distinctCount = await Model.count({
  distinct: true,
  col: 'columnName'
});
console.log(`There are ${distinctCount} distinct values for columnName.`);

Counting with Conditions

Often, you’ll need to count rows that match a specific condition. You can achieve this by using the where option:

const conditionalCount = await Model.count({
  where: {
    column: 'desiredValue'
  },
  distinct: true,
  col: 'columnName'
});
console.log(`There are ${conditionalCount} distinct values for columnName with the specified condition.`);

Advanced Counting: Associations and Grouping

Sequelize.js allows for complex counting by leveraging associations and grouping. Let’s say we have a User model and a Post model where a user can have many posts. If we want to count the number of distinct users who have created a post, we can do something like the following:

const userPostCount = await Post.count({
  distinct: true,
  col: 'userId'
});
console.log(`There are ${userPostCount} distinct users who have posted.`);

Additionally, we can use the group option for more granular statistics, like counting distinct posts per user:

const postsPerUser = await Post.count({
  attributes: ['userId'],
  group: ['userId'],
  distinct: true,
  col: 'id'
});
postsPerUser.forEach(result => {
  console.log(`User ${result.userId} has ${result.count} distinct posts.`);
});

Counting with Joins

Counting distinct rows sometimes requires joining tables. Using Sequelize, we can apply include to join models and count distinct rows based on the joined fields:

const countWithJoin = await User.count({
  include: [{
    model: Post,
    attributes: []
  }],
  distinct: true,
  col: 'User.id'
});
console.log(`There are ${countWithJoin} users with distinct posts.`);

Note that we’ve left the attributes array empty to avoid including Post model’s columns in the count.

Handling Large Datasets

When dealing with large datasets, performance can become a concern. It’s essential to optimize your queries and index your database appropriately. Make sure to review your query plans and use database profiling to identify and mitigate bottlenecks.

Conclusion

In this tutorial, we explored several methods for counting distinct rows in Sequelize.js, ranging from basic counting to advanced scenarios involving conditions, associations, grouping, and joining tables. These techniques are valuable for generating reports, analytics, and understanding the diversity of data in your database. As with any database operations, always pay attention to performance implications and optimize as necessary.

Next Article: Sequelize.js: Optimize Queries to Boost Performance

Previous Article: Using afterDelete and afterDestroy Hooks in Sequelize.js

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