1

I'm using an NVL function in my WHERE clause like this.

... AND NVL(FIRST_DATE, SECOND_DATE) BETWEEN (SYSDATE - 7) and SYSDATE 

What I'm doing is this: If FIRST_DATE is null then use the SECOND_DATE for comparison. The problem with this is that it prevents index usage on the column first_date or second_date. So I rewrote the condition into this:

... AND 
((FIRST_DATE BETWEEN (SYSDATE-7)  AND SYSDATE) 
OR 
(FIRST_DATE IS NULL AND SECOND_DATE BETWEEN (SYSDATE-7) AND SYSDATE))

I tested it by running it with different dates and it always returned the same results as with the NVL Function. But I want to make sure and check if I didn't miss any exceptions where the result may differ. Can anyone confirm that what I did is semantically equivalent to the NVL Function?

Victor O
  • 91
  • 6

1 Answers1

1

The issue isn't really the NVL() per se. It is simply the complication of the WHERE clause. Oracle supports indexes on expressions, so I would recommend a new index:

create index idx_t_dates on t(coalesce(first_date, second_date))

Then, if you use the same expression in the where clause, then the index should be used:

and coalesce(first_date, second_date) between sysdate - 7 and sysdate

I prefer coalesce()over nvl() because it is the standard function with the same functionality.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • I was also thinking about creating a function based index but I didn't want to go that route, since it's once of our biggest tables. – Victor O Apr 28 '20 at 12:09