General Functions: Nvl, Nvl2, Decode, Coalesce, Nullif, Lnnvl And Nanvl in SQL
Sure! Here's a clear explanation of those general functions related to handling NULLs and conditional logic in SQL:
General Functions: NVL, NVL2, DECODE, COALESCE, NULLIF, LNNVL, NANVL
1. NVL(expr1, expr2)
Replaces NULL value
expr1withexpr2.Returns
expr1if it is not NULL; otherwise, returnsexpr2.
SELECT NVL(NULL, 'Default') FROM dual; -- Returns 'Default'SELECT NVL('Hello', 'Default') FROM dual; -- Returns 'Hello'Common in Oracle.
2. NVL2(expr1, expr2, expr3)
If
expr1is not NULL, returnsexpr2;Otherwise, returns
expr3.
SELECT NVL2('Test', 'Not Null', 'Is Null') FROM dual; -- Returns 'Not Null'SELECT NVL2(NULL, 'Not Null', 'Is Null') FROM dual; -- Returns 'Is Null'3. DECODE(expr, search, result [, search, result ...] [, default])
Compares
exprto eachsearchvalue; returns correspondingresultif matched; otherwise, returnsdefault(or NULL if default is not given).Works like a simple IF-THEN-ELSE or CASE statement.
SELECT DECODE(2, 1, 'One', 2, 'Two', 'Other') FROM dual; -- Returns 'Two'SELECT DECODE(3, 1, 'One', 2, 'Two', 'Other') FROM dual; -- Returns 'Other'4. COALESCE(expr1, expr2, ..., exprN)
Returns the first non-NULL expression in the list.
More flexible than
NVLbecause it can take multiple arguments.
SELECT COALESCE(NULL, NULL, 'Third', 'Fourth') FROM dual; -- Returns 'Third'5. NULLIF(expr1, expr2)
Returns NULL if
expr1 = expr2; otherwise, returnsexpr1.Useful to avoid division by zero or similar conditions.
SELECT NULLIF(10, 10) FROM dual; -- Returns NULLSELECT NULLIF(10, 5) FROM dual; -- Returns 106. LNNVL(condition)
Logical Negation of Null Value Logic.
Returns TRUE if condition is FALSE or UNKNOWN (NULL).
Returns FALSE if condition is TRUE.
Mainly used in WHERE clauses to handle three-valued logic with NULLs.
SELECT * FROM employees WHERE LNNVL(salary > 5000);-- Returns rows where salary <= 5000 or salary IS NULL7. NANVL(expr1, expr2)
Returns
expr2ifexpr1is NaN (Not a Number); otherwise returnsexpr1.Used to handle NaN values in floating-point operations.
SELECT NANVL(0/0, 0) FROM dual; -- Returns 0 (since 0/0 is NaN)Summary Table:
| Function | Purpose | Returns |
|---|---|---|
NVL | Replace NULL with a value | expr2 if expr1 is NULL else expr1 |
NVL2 | Conditional on NULL | expr2 if expr1 NOT NULL, else expr3 |
DECODE | Simple if-then-else (like CASE) | Corresponding result based on matching expr |
COALESCE | First non-NULL value | First non-NULL expression |
NULLIF | Return NULL if two expressions equal | NULL if equal, else first expression |
LNNVL | Logical negation with NULL logic | TRUE if condition FALSE or NULL, else FALSE |
NANVL | Handle NaN values | Second expr if first is NaN, else first expr |
If you want examples with your data or specific SQL dialect (Oracle, PostgreSQL, etc.), just ask!