Can conditionals be used in a WHERE condition?
0
votes
1
answer
40
views
I am working on something and found this SQL that I am not sure how to rewrite correctly, meaning using PHP PDO.
The SQL looks like:
$sql = 'SELECT * FROM table WHERE column ' . isset($variable) ? . '=' . $variable : '>0';
Basically what the query is telling is: if $variable
is defined (within the PHP world) then use an =
for the WHERE condition, if it is not then use the >0
.
I can clean up that a little bit on PHP and do something like:
$where = $variable ? 'column = ?' : column > ?'; // ternary operator to build the proper where condition
$sql = 'SELECT * FROM table WHERE $where';
$db->row($sql, [$variable ?? 0]); // bind parameters to the query, PDO way, and the operator will use the value of $variable if it is defined otherwise it will use 0
and it will work fine, I guess. Now, I wonder if I can achieve the same using plain SQL like a condition inside the WHERE same as within the SELECT, and if so, is it optimum? Or programmatically is better and faster?
Asked by ReynierPM
(1888 rep)
Dec 27, 2023, 02:05 PM
Last activity: Dec 27, 2023, 02:32 PM
Last activity: Dec 27, 2023, 02:32 PM