點燈坊

失くすものさえない今が強くなるチャンスよ

Using Knex to Execute Raw SQL

Sam Xiao's Avatar 2021-11-05

Knex allow us to execute partial raw SQL, but we can also use knex.raw to execute whole raw SQL.

Version

MySQL 8.0.18
Knex 0.20.2

SQL

REPLACE INTO books (title, price, categoryId) 
VALUES ('Learning Haskell', 500, 1)

REPLACE INTO is a famous SQL statement in MySQL. The difference between REPLACE INTO and INSERT INTO is that if the record exists in table, REPLACE INTO will delete first then insert to avoid INSERT INTO runtime error.

Knex

knex.raw (`
  replace into books (title, price, categoryId) 
  values ('Learning Haskell', 500, 1)
`)

But REPLACE INTO is just for MySQL, so we can use knex.raw to execute raw SQL.

Conclusion

  • I use raw SQL for DQL in practical, because SELECT is often very complex. But I use Knex to generate DML for me, since INSERT, UPDATE, DELETE is simple but verbose