Gambit2007
Gambit2007

Reputation: 4014

MySQL ORM - conditional WHERE clause

I'm using sequelize as a MySQL ORM and i have the following code:

 mysql().lib.query("SELECT t.id, t.address
                    FROM mytable t 
                    WHERE t.fname = :fname OR t.lname = :lname",
          replacements: { fname, lname })

fname and lname are variables that are potentially not set in the code, or set to null. So my question is - how can i use one or both of them inside of the WHERE clause but only if they "exist"?

(Note: at least one of them will definitely exist)

Upvotes: 0

Views: 92

Answers (1)

juergen d
juergen d

Reputation: 204924

You can do it with simple boolean logic

WHERE (:fname is null or t.fname = :fname) 
  AND (:lname is null or t.lname = :lname)
   ^------ I used AND here since it does make more sense

Upvotes: 1

Related Questions