Skip to content
Advertisement

How to unset or make condition true, If passed variable is empty or null

I have a query…

SELECT * FROM table_name WHERE id = '$id'

if the $id is empty or null, then I need to get all data from table where id is not null

I already tried like following,

SELECT
  * 
FROM
  table_name 
WHERE
( 
  ('$id' != '' AND id = '$id') 
  OR 
  ('$id' = '' AND id IS NOT NULL)
)

But looking for the better solution without if condition, because I have lot of and conditions

Thanks in advance…

Advertisement

Answer

Thank you so much @Akina for the comment…

Here is the solution…

SELECT * FROM table_name WHERE id = COALESCE(NULLIF($id, ''), id)

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement