Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle : sql select query if condition parameter is null then ignore the parameter

Tags:

java

sql

oracle

suppose I have a oracle query

SELECT *
FROM EMPLOYEE
WHERE DEPARTMENT = ?
    AND DESIGNATION = ?
    AND DISTRICT = ?
    AND CIRCLE = ?

And quite possible any 1 or 2 or 3 of the parameter (?) can be empty or null.
so what should I do so that the empty parameters are totally "ignore" in the where clause and only search for the non-empty parameter in the table.
How can I achieve this

Please help.. The query must be compatible oracle 10g. Thanks

like image 523
anikesh sharma Avatar asked Aug 25 '17 12:08

anikesh sharma


People also ask

Can we pass NULL as a parameter in SQL?

In SQL, null acts a bit differently to other values - you can't just evaluate things as being = null, as this doesn't really work, you need to use "myColumn is null" instead. In your case, when you need to match either a value or a null, you might need to use a case statement in your where clause.

IS NULL in if condition in Oracle?

If expression is a NULL value, the condition evaluates to TRUE. If expression is not a NULL value, the condition evaluates to FALSE.

How check parameter is not null in SQL?

The IS NOT NULL condition is used in SQL to test for a non-NULL value. It returns TRUE if a non-NULL value is found, otherwise it returns FALSE. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement.


2 Answers

You can rewrite query like:

select * 
  from EMPLOYEE 
  where (DEPARTMENT  = p1 or p1 is null)  
    and (DESIGNATION = p2 or p2 is null) 
    and (DISTRICT    = p3 or p3 is null)
    and (CIRCLE      = p4 or p4 is null)

or:

select * 
  from EMPLOYEE 
  where DEPARTMENT  = nvl(p1, department)
    and DESIGNATION = nvl(p2, designation)
    and DISTRICT    = nvl(p3, district)
    and CIRCLE      = nvl(p4, circle)

As @mathguy mentioned in comments second version will not show null values. Please use first version.

like image 134
Ponder Stibbons Avatar answered Nov 13 '22 05:11

Ponder Stibbons


NVL will be your friend here.

This function takes two input parameters and returns either the first one, or the second one if the first one is NULL.

This would work :

SELECT *
FROM EMPLOYEE
WHERE DEPARTMENT = NVL(yourParam1,DEPARTMENT)
    AND DESIGNATION = NVL(yourParam2,DESIGNATION )
    AND DISTRICT = NVL(yourParam3,DISTRICT )
    AND CIRCLE = NVL(yourParam4,CIRCLE )
like image 41
Dessma Avatar answered Nov 13 '22 06:11

Dessma