Sequelize union

Sequelize Union

The Sequelize library is an Object-Relational Mapping (ORM) tool for Node.js that allows you to interact with databases using JavaScript. It supports various database systems including MySQL, PostgreSQL, SQLite, and more.

Union is a set operation that combines the results of two or more SELECT statements into a single result set. In Sequelize, you can perform a union operation using the `sequelize.literal` method along with `sequelize.query`.

Example:

Let’s say we have two tables, `employees` and `customers`, in our database. We want to retrieve the names of all employees and customers in a single query result.


    const Sequelize = require('sequelize');
    const sequelize = new Sequelize('database', 'username', 'password', {
      dialect: 'mysql',
      host: 'localhost'
    });

    const Employee = sequelize.define('employee', {
      name: Sequelize.STRING
    });

    const Customer = sequelize.define('customer', {
      name: Sequelize.STRING
    });

    let results = await sequelize.query(`
      SELECT name FROM employees
      UNION
      SELECT name FROM customers
    `, { type: sequelize.QueryTypes.SELECT });

    console.log(results);
  

In the above example, we first create two Sequelize models for the `employees` and `customers` tables. Then, we use `sequelize.query` to perform the union operation by writing a raw SQL query. The `sequelize.QueryTypes.SELECT` option ensures that only the SELECT results are returned.

The `results` variable will contain an array of objects, where each object represents a row from the query result. Each object will have a `name` property, which corresponds to the column selected in the query.

Similar post

Leave a comment