Categories
josephscott

NVL, ISNULL, IFNULL and COALESCE

Welcome to a brief stop in the twilight zone of database functions.

If you want to check two (or more) fields and get the value of the first non-null field in Oracle you would use nvl. I needed to do the same thing in SQL Server 2000, which doesn’t have the function nvl (of course). After looking around SQL Server has a function that does the same exact thing called isnull.

By this point I figured I’d better be complete and find out if MySQL had a function called nvl or if they called it something else. If you guessed that it is called something else then you would be right, MySQL calls it ifnull. I was already familiar with the PostgreSQL equivalent which is called coalesce. Unlike all of the other functions mentioned above though, coalesce takes a list of fields/values/expressions instead of just two. Although the name sounds a little strange (nvl just rolls of the tongue so nicely) it certainly made more sense to have a more generalized function that would accept a list. As an additional reference the mysql compatibility project includes a ifnull function for folks porting SQL from MySQL to PostgreSQL.

So do you feel a little more enlightened now? Don’t stop now, it gets even stranger.

I got to thinking more about how much better the coalesce approach seems to be than nvl, isnull and ifnull so I did some more research to see what other databases besides PostgreSQL supported it. Guess what I found out. There is a coalesce in Oracle, a coalesce in SQL Server and a coalesce in MySQL. Huh? Why do folks even bother writing SQL that includes the use of nvl, isnull and ifnull?

That concludes our brief tour through the twilight zone of database functions for now.