Search code examples
sqliteexpresssequelize.js

How to concat columns in Sequelize with SQLite database


I'm using Sequelize for a express project I'm working on.
In one query I want to retrieve a concatenated result of two columns.

Like:

SELECT first_name || ' ' || last_name AS full_name FROM table

I tried the following syntax and got an error

router.get('/persons', function(req, res, next) {
  models.Person.findAll({
    attributes: [models.sequelize.fn('CONCAT', 'first_name', 'last_name')]
  })
    .then(function(persons) {
      res.send(persons);
    });
});

The error message:

SELECT CONCAT('first_name', 'last_name') FROM `Persons` AS `Person`;
Possibly unhandled SequelizeDatabaseError: Error: SQLITE_ERROR: no such function: CONCAT

Solution

  • I used models.sequelize.literal, that creates a object representing a literal, inside nested array to give it an alias.

    The result:

    router.get('/persons', function(req, res, next) {
      models.Person.findAll({
        attributes: [models.sequelize.literal("first_name || ' ' || last_name"), 'full_name']
      })
        .then(function(persons) {
          res.send(persons);
        });
    });