Home > Mobile >  Syntax error when using from as a column name in sequelize raw query
Syntax error when using from as a column name in sequelize raw query

Time:10-26

I want to save some data to postgres database using sequelize but getting syntax error. One of my column name is 'from'.

let sql = await db.sequelize.query(INSERT INTO chats ( from, msg, chat_room_id) VALUES (${sender},'${msg}',${chat_room_id}));

The syntax error is caused by 'from' column as syntax error at or near "from"

I tried this

let sql = await db.sequelize.query(INSERT INTO chats ( from, msg, chat_room_id) VALUES (${sender},'${msg}',${chat_room_id}));

Expected: Data to be saved into database What I got: syntax error at or near "from"

CodePudding user response:

If you use reserved PostgreSQL keywords as column names (I don't recommend to do so) then you need to wrap them into "":

let sql = await db.sequelize.query(INSERT INTO chats ( "from", msg, chat_room_id) VALUES (${sender},'${msg}',${chat_room_id}));

The same goes for column names with special characters or with mixed case like chatRoomId.

  • Related