NVL functions are used in SQL (primarily in Oracle) to handle NULL values by replacing them with a specified value. Here’s how they work:
1. NVL Function (Oracle)
The NVL function replaces NULL with a specified value.
Syntax:
- expression: The value or column to be checked.
- replacement_value: The value to replace
NULLif the expression isNULL.
Example:
- If
salaryisNULL, it is replaced with0.
2. NVL2 Function
The NVL2 function provides more flexibility by allowing different values based on whether the expression is NULL or not.
NVL2(expression, value_if_not_null, value_if_null)
- If
expressionis NOT NULL, it returnsvalue_if_not_null. - If
expressionis NULL, it returnsvalue_if_null.
Example:
- If
commissionisNULL, it returns"No Commission", otherwise"Has Commission".
3. COALESCE Function (Alternative)
The COALESCE function returns the first non-null value from a list of expressions.
COALESCE(expression1, expression2, ..., expressionN)
- Returns the first non-null value from the list.
Example:
- If
salaryisNULL, it checksbonus; if both areNULL, it returns0.
4. NULLIF Function
The NULLIF function returns NULL if both expressions are equal; otherwise, it returns the first expression.
Syntax:
Example:
- If
salesequalstarget, it returnsNULL, otherwisesales.
Which One to Use?
| Function | Use Case |
|---|---|
| NVL | Replace NULL with a specific value |
| NVL2 | Return different values based on NULL status |
| COALESCE | Return the first non-null value from multiple columns |
| NULLIF | Compare two values and return NULL if they are equal |
Tags:
Oracle