21

Using knexjs only (no bookshelf) I would like to do something like the following query:

select * from table1 where column1 < column2

However, when I do this:

.table("table1").select().where("column1", "<", "column2")

The SQL that knexjs generates is:

select * from table1 where column1 < 'column2'

Which doesn't give the desired result b/c it's not comparing the value from the column, it's comparing the value of the string, 'column2'.

Anyone know how to do what I'm wanting? Thanks!

2 Answers 2

22

Ok, so after some digging, it looks like it can be done this way. Not sure if this is best practice, but at the moment, it works so until I hear otherwise...

.table("table1").select().where("column1", "<", knex.raw("table1.column2"))

Again, not ideal, but it gets the job done. Just be sure to

import knex from "knex";

at the top of whatever file you're using this in.

3
  • 8
    .whereRaw("?? = ??", ["column1", "column2"]) works too Commented Mar 21, 2017 at 1:47
  • @GregHornby it works. Could you please explain why it works only with double question marks? Commented Feb 18, 2019 at 16:02
  • 2
    ?? represents a binding for an identifier like a column or table name. ? represents a binding for a value, like a number, or string. Commented Feb 18, 2019 at 22:14
13

As of knex 0.15.0 (July 2018), we now have:

table("table1").select().where("column1", "<", knex.ref("column2"))

See https://knexjs.org/#Ref

As Greg Hornby mentions in the comment to the other answer, you can also use ?? in a raw query to bind to a column or table name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.