Home > database >  How can I use a variable inside the where clause?
How can I use a variable inside the where clause?

Time:02-01

Let's say that I have four variables named a,b,c,d which I am getting as input from the user and I want to have such query in my application:

Select * 
from TABLE 
where (TABLE.FIELD = 'a' OR a = null) 
AND (TABLE.FIELD = 'b' OR b = null) ..

Is there a way to bind my variable like this inside the query? I am using MySQL and Python.

Thanks in advance

CodePudding user response:

You can assign a variable using SET outside the query, depending on how you receive the user input. Then check the variables inside the query with IS NULL:

SET @a := my_val;

SELECT * 
FROM TABLE 
WHERE (TABLE.FIELD = @a OR @a IS NULL)...;

Doing this, in the case where variable a is null, you would get the whole table from the query.

You could also make a stored procedure that checks the variables for null before querying. In a stored procedure you can use if conditions for instance.

  •  Tags:  
  • Related