Sling Academy
Home/Node.js/Mastering the LIKE Condition in Sequelize.js

Mastering the LIKE Condition in Sequelize.js

Last updated: December 29, 2023

Introduction

The LIKE condition in Sequelize is a powerful tool for pattern matching in queries when using SQL-based databases with Sequelize, an Object-Relational Mapper (ORM) for Node.js. This tutorial aims to guide you through using the LIKE condition with multiple examples, from basic usage to more advanced techniques. With Sequelize, you can write database queries in a way that’s both easier to read and maintain.

Prerequisites

  • Basic knowledge of Node.js
  • Familiarity with relational databases and SQL
  • Sequelize installed and a Sequelize model set up

Basic Usage of LIKE

In Sequelize, the LIKE condition can be used to find records where a column matches a certain pattern. Below is how you can use the LIKE condition:

const users = await User.findAll({
  where: {
    username: {
      [Sequelize.Op.like]: '%john%'
    }
  }
});

This code will fetch all users whose username contains ‘john’.

Case Sensitivity

By default, the LIKE condition is case-insensitive in some databases and case-sensitive in others. You can use ILIKE for a case-insensitive search in databases like PostgreSQL:

const users = await User.findAll({
  where: {
    username: {
      [Sequelize.Op.iLike]: '%john%'
    }
  }
});

Using Wildcards

The percent sign (%) is used as a wildcard character in the LIKE condition, representing any sequence of characters. An underscore (_) represents a single character. Here’s an example:

const users = await User.findAll({
  where: {
    email: {
      [Sequelize.Op.like]: 'example@_%'
    }
  }
});

This will match users with an email that starts with ‘example@’ and has at least one character after the ‘@’ sign.

Escaping Special Characters

When you need to match a literal percent sign or underscore, you can escape these characters in Sequelize:

const users = await User.findAll({
  where: {
    bio: {
      [Sequelize.Op.like]: '100\% Node.js developer'
    }
  }
});

This will match users whose bio includes the exact string ‘100% Node.js developer’.

Combining Conditions

You can combine the LIKE condition with other conditions to create more complex queries:

const users = await User.findAll({
  where: {
    [Sequelize.Op.and]: [
      { username: {
        [Sequelize.Op.like]: 'john%'
      }},
      { age: {
        [Sequelize.Op.gte]: 30
      }}
    ]
  }
});

This query looks for users with usernames starting with ‘john’ and who are at least 30 years old.

Dynamic Pattern Matching

To construct dynamic LIKE patterns, you can concatenate strings to build your search criteria:

let search = 'john';
const users = await User.findAll({
  where: {
    username: {
      [Sequelize.Op.like]: '%' + search + '%'
    }
  }
});

By concatenating search with wildcards, you create a flexible search mechanism.

Advanced Techniques

For more advanced scenarios, you might need to use functions and operators to manipulate LIKE conditions. Sequelize allows you to use functions such as Sequelize.fn to achieve this.

Here is an example using the LOWER function to perform a case-insensitive search without using ILIKE:

const users = await User.findAll({
  where: {
    Sequelize.fn('LOWER', Sequelize.col('username')): {
      [Sequelize.Op.like]: Sequelize.fn('LOWER', '%john%')
    }
  }
});

This performs a case-insensitive search for ‘john’ in the username field.

Conclusion

In this tutorial, we’ve explored how to use the LIKE condition in Sequelize to create flexible and powerful queries. We started with the basics, covered case sensitivity and wildcards, and then moved on to more advanced examples like escaping special characters and dynamically building search patterns. Finally, we delved into advanced techniques that leverage Sequelize functions for even more nuanced querying.

With these skills, you’ll be able to implement complex search features in your applications quickly and efficiently. Remember to refer to the Sequelize documentation for further details and updates on the library’s features. Happy coding!

Next Article: Filtering by Multiple Conditions in Sequelize

Previous Article: How to Select Records Between Two Dates 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