Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return all rows if null value is passed

I have a query like this:

select empno,name
from emp
where job = 'CLERK'
and empno = :empno

If I pass empno that is null I would like to display all the records that match the condition of job = 'CLERK'. If empno is a specific number then it should filter for job and empno.

Anyway to do this in SQL without using PLSQL?

like image 943
Nick Loach Avatar asked Mar 03 '26 18:03

Nick Loach


2 Answers

and (empno = :empno or :empno is null)
like image 197
Andomar Avatar answered Mar 06 '26 06:03

Andomar


Something like this if pass parameter is null than replace it with the actual column value ...

select empno,name from emp where 
job = 'CLERK' 
and empno = NVL(:empno ,empno)

How NVL work

The syntax for the NVL function is:

NVL( string1, replace_with )

string1 is the string to test for a null value.

replace_with is the value returned if string1 is null.
like image 28
Pranay Rana Avatar answered Mar 06 '26 07:03

Pranay Rana