Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle SQL - How to build where clause with optional search parameters

There are four field in the page lets say

EMPLOYEE ID
DEPT
LOCATION
UNIT:

User might enter any of the field values all are optional, if he enter EMPLOYEE ID then the query should return rows related to that EMPLOYEE ID. If he enters only LOCATION then the query should return all the employees of that location. How to write the where clause condition with optional parameters.

like image 695
user2345743 Avatar asked May 26 '15 09:05

user2345743


People also ask

How do you handle optional parameters in SQL query?

declare type t_table is table of myTable%rowtype; n_RequiredId myTable. id_pk%type := 1; t_Output t_table := t_table(); begin select m. id_pk, m. value bulk collect into t_Output from myTable m where m.

Can we use where clause in case statement in Oracle?

You can use a CASE expression in any statement or clause that accepts a valid expression. For example, you can use the CASE expression in statements such as SELECT , UPDATE , or DELETE , and in clauses like SELECT , WHERE , HAVING , and ORDDER BY .

Can we pass parameter to WITH clause in Oracle?

You cannot do this in Oracle.

Can we use where clause in partition by Oracle?

Oracle Database will interpret the condition and fetch data from only those partitions. It is not possible to formulate such a WHERE condition for hash-partitioned data.


1 Answers

Oracle will likely build a well-optimized query if you use NVL in your predicates:

select *
  from employee
 where employee_id = nvl(:employee_id, employee_id)
   and dept = nvl(:dept, dept)
   and location = nvl(:location, location)
   and unit = nvl(:unit, unit)

The above code is mostly equivalent to LeoLozes's answer. Although his answer is more readable, in this case the cryptic version may run much faster. One important difference is that the above code will not work if the column is NULL. If you have nullable columns you'll need to use something like LeoLoze's answer, since null = null is not true.

Oracle is used to the NVL trick, and can automatically convert this static query into a dynamic query using a FILTER operation. The execution plan will have both a FULL TABLE SCAN and and INDEX RANGE SCAN, and will pick the appropriate one at run-time, depending on the value of the bind variable. See my answer here for some sample code demonstrating how this works.

like image 155
Jon Heller Avatar answered Oct 15 '22 22:10

Jon Heller