Oracle. Select all if parameter is null else return specific item issue

后端 未结 3 1056
自闭症患者
自闭症患者 2021-01-26 05:43

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         


        
3条回答
  •  有刺的猬
    2021-01-26 06:15

    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

提交回复
热议问题