Monday, October 20, 2008

Oracle and null values

I have a table say Employee with the following structure
Employee ( id number, name varchar2(50) )

If i try inserting (1,'')into this above table guess what will be the name of the employee with id 1? Yeah its null. I thought that was weird, since i meant a 0-length string and not null. Alright, so i surrendered to the fact that Oracle would store a null every time I added a zero length string.

But that's not done. Now assume, my table has the following values
Id - Name
1 - null
2 - Anita
3 - null
4 - Beena
5 - Neha

What would this query return -
Select * from Employee where name not in('Anita', 'Neha');

If you thought it would return me 3 rows, you are wrong (as was I). it just returns one record -
4 Beena
Thats because when you fire a not in clause it will not consider null. So if you thought that null != Anita/Neha you are partially right but not completely

You have to explicitly change the above query as -

Select * from Employee where name not in('Anita', 'Neha') or name is null;

Morally of the story: Deal with null value columns carefully. A small mistake will be really difficult to debug