I need to return all records if input parameter is null.
I\'ve written a simple query
declare
l_sql varchar2(100);
i number := 1;
begin
l_sq
Simply use coalesce
. It is the most readable and understandable way to write this. Since the logic is contained in one predicate, it's easier to maintain and remove:
select * from job where id = coalesce(:i, id)
As requested, a 'proof' this actually uses the index:
create table x ( id number(15) null );
create unique index x_pk on x( id );
select id
from x
where id = coalesce(:x, id)
; -- Uses index
select id
from x
where id = :x or :x is null
; -- Full table scan
Plan:
SELECT STATEMENT ALL_ROWS Cost: 1 Bytes: 13 Cardinality: 1
1 INDEX FULL SCAN INDEX (UNIQUE) X_PK Cost: 1 Bytes: 13 Cardinality: 1