5

I have a variable being passed to my stored proc and it's a filter (basically). However, that field can sometimes be null, and if it is, I want to be able to check against the rows that have that field as null.

For example,

Table A:

VALUE_COLUMN | FILTER_COLUMN
----------------------------
A            |  (NULL)
B            |  (NULL)           
C            |  (NULL)
D            |  (NULL)
A            |  1
E            |  (NULL)
F            |  (NULL)
B            |  1

The query (With inputs, val, filter):

SELECT  COUNT(1)
  FROM    TableA
WHERE 
  wrap_up_cd = val
  AND brn_brand_id = filter

Expected I/O:

val = A, filter = (null) = 1
val = A, filter = 1 = 1
val = C, filter = 1 = 0

How can I make Oracle behave this way?

Malfist
  • 31,179
  • 61
  • 182
  • 269

3 Answers3

9

How about:

SELECT  COUNT(1)
  FROM    TableA
WHERE 
  wrap_up_cd = val
  AND ((brn_brand_id = filter) OR (brn_brand_id IS NULL AND filter IS NULL))

I'm not an Oracle expert, but I'd expect that to work - basically make the query match if both the filter and the value are NULL.

Malfist
  • 31,179
  • 61
  • 182
  • 269
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I edited the sql to work correctly. But yes, this is what I was looking for, I don't know why I didn't think of it already. – Malfist Aug 08 '11 at 18:03
  • @Malfist: Sorry, the previous syntax was for SQL Server. Shows you how long it is since I've done any SQL on either platform... – Jon Skeet Aug 08 '11 at 18:04
  • I noticed, I'm used to do SQL Server also, doing all this Oracle stuff has thrown me for a loop. – Malfist Aug 08 '11 at 18:07
2

Oracle doesn't have an ISNULL function. So you'd need something like

SELECT COUNT(*)
  FROM tableA
 WHERE brn_brand_id = filter
    OR (    brn_brand_id IS NULL 
        AND filter IS NULL)
Justin Cave
  • 227,342
  • 24
  • 367
  • 384
1

This can also be handy at times:

   SELECT COUNT(*)
      FROM tableA
   WHERE
      NVL(brn_brand_id, CHR(0)) = NVL(filter, CHR(0))
elyor
  • 998
  • 9
  • 20