In this article, I'll explain what the Oracle NVL function does and show a few examples of using it.
The NVL Function
In Oracle, the
NVL function allows you to replace a
NULL value with another value.
It's helpful when you want to store the fact that there is no data for a particular column, but you want to display something else.
I'll show you a few examples of this.
Example 1: End Date
A common concept in database tables is to store a start and end date for a record, which is used to track when a record is effective for.
In some cases, the end date is set to
NULL if there is no end date or if it is the active record.
Take a look at this table here:
We can see that there are a few records for this customer. The start date indicates when the record has started, and the end date indicates when the record has ended.
The active record is where the end date is
We could use a query like this:
SELECT customer_id, customer_name, status, start_date, end_date FROM customer_history;
However, we might not want to display
NULL or an empty value in the system that uses this data (i.e., a report or a website).
So, we can use the
NVL function. We first need to work out what value we want to display. This could be a static date (i.e., 31-DEC-9999), for example.
Here's an example using a static date:
SELECT customer_id, customer_name, status, start_date, NVL(end_date, '31-DEC-9999') FROM customer_history;
As you can see, the NVL function can be used to translate a NULL date value to something else.
2. Missing Data That Should Be Populated
Another example of using the
NVL function is where you are missing data for a column that you or the application believes should be there or if you're loading data from one table into another table and cannot use
NULL values for some reason.
Let's say we have the same table as above.
In this table, we see information on customers. However, let's say that we use this to populate another table in another system or a materialized view and the status column cannot be
A business rule specifies that we need a value for status, but we can't update the underlying table.
So, we can use the
NVL function here.
SELECT customer_id, customer_name, Nvl(status, 'Unknown') AS status, start_date, end_date FROM customer_history;
As you can see, the query now shows a value for the status column, even if the original value was
NULL. This now satisfies the business rule that says the status column cannot be null in your new table.
Now you know a couple of examples on how to use the
NVL function in Oracle.