@coockoo's answer is incorrect for both of the SQLs. Their first one would still allow %
through as Knex does not escape %
for LIKE
operations. The second SQL simply does not work as Knex wraps the bound value with quotes.
The correct way should be
const term = '10%'
const b = knex('table').where('description', 'like', `%${term.replaceAll('%', '\\%')}%`)
The output of b.toString()
is:
select * from "table" where "description" like E'%10\\%%'
Postgres will interpret E'\\%'
as '\%'
, which is an escaped percentage sign according to: https://www.postgresql.org/docs/current/functions-matching.html#FUNCTIONS-LIKE by default if you are on newer Postgres version.
This can be verified with this table:
CREATE TABLE test (
description character varying(256)
);
INSERT INTO test VALUES ('a%b');
and test the following:
- Without escaping
%
like others have suggested. This shouldn't work.
knex('test').where('description', 'like', 'a%%%b').toString()
select * from "test" where "description" like 'a%%%b'
description
-------------
a%b
(1 row)
Escaping %
before giving to Knex.
- This should return no rows:
knex('test').where('description', 'like', 'a\\%\\%\\%b').toString()
select * from "test" where "description" like E'a\\%\\%\\%b'
description
-------------
(0 rows)
- This should return
'a%b'
:
knex('test').where('description', 'like', 'a\\%b').toString()
select * from "test" where "description" like E'a\\%b'
description
-------------
a%b
(1 row)
SQL Fiddle: http://sqlfiddle.com/#!17/d2f5e/1