简体   繁体   中英

Difference between NVL and OR in SQL oracle

Hej guys, could someone explain to me difference between NVL() and OR in below query :

Select 
count(*)                         
from SHIPMENTSTATUS  
WHERE insert_date  between  trunc(sysdate) -2 and  trunc(sysdate) -1  or  update_date BETWEEN trunc(sysdate) -2 and  trunc(sysdate) -1

Number of rows: 44937

and

Select 
count(*)
from SHIPMENTSTATUS  
where NVL(UPDATE_DATE, INSERT_DATE) between  trunc(sysdate) -2 and  trunc(sysdate) -1

Number of rows: 44782

Why we have this difference: 155 rows? i built a few query based on nvl and notice that issue and going to switch to OR , but I really want to know, why it such a difference. Thank you for explanation

When UPDATE_DATE is not null NVL(UDATE_DATE, INSERT_DATE) evalulates to UPDATE_DATE and INSERT_DATE will not be used at all. Records with INSERT_DATE in the range, but a non null UPDATE_DATE outside of that range will be included in the first query, but excluded in the second.

The first conditional expression checks if either of the two columns is in the target date range.

The second expression checks the second column only if the first column is null . So if the first column is not null and not in the range, the condition is not fulfilled. This is more restrictive.

Something equivalent to:

nvl(update_date, insert_date) 
    between  trunc(sysdate) - 2 and  trunc(sysdate) - 1

Would be:

update_date between  trunc(sysdate) - 2 and trunc(sysdate) - 1  
or ( 
    update_date is null 
    and insert_dateBETWEEN trunc(sysdate) - 2 and  trunc(sysdate) - 1
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM