ANSI SQL Extensions  «Prev  Next»

Lesson 4Using NVL with Oracle SQL
ObjectiveUse the NVL built-in function with Oracle SQL.

Oracle NVL Function: NULL Handling in Oracle 26ai

Oracle SQL uses NULL to represent a value that is missing, unknown, or not applicable. A null value is not the same as zero, a blank character, or a datatype default. Because nulls affect comparisons, calculations, joins, and report output, SQL developers must handle them deliberately. Oracle's NVL built-in function provides a direct way to replace a null expression with a meaningful alternative.

This lesson explains how SQL's three-valued logic produces an UNKNOWN result, how NVL substitutes display and numeric values, and why null handling is especially important when an outer join preserves rows that have no match in another table.

In Oracle AI Database 26ai, NVL(expr1, expr2) returns expr2 when expr1 is null and otherwise returns expr1. It changes a query expression, not the stored value. See the NVL reference.

SQL NULL and three-valued logic

Most programming conditions are described as either true or false. SQL adds a third logical result: UNKNOWN. This three-valued logic is necessary because a condition cannot always be evaluated when one of its operands is NULL.

Consider a row in which salary is null:

salary = 50000

Oracle cannot determine whether the missing salary equals 50,000, so the condition evaluates to UNKNOWN. It does not evaluate to FALSE. This distinction matters because a WHERE clause returns only rows whose condition evaluates to TRUE. Rows that produce either FALSE or UNKNOWN are filtered out.

Use the null predicates IS NULL and IS NOT NULL when testing for missing values:

SELECT employee_name,
       salary
FROM employee
WHERE salary IS NULL;

Do not use = NULL or <> NULL. Those comparisons evaluate to UNKNOWN, so they do not identify null rows.

How UNKNOWN affects logical operators

The result of a compound condition depends on the other operands. For example:

  • TRUE AND UNKNOWN evaluates to UNKNOWN.
  • FALSE AND UNKNOWN evaluates to FALSE, because the complete condition cannot be true.
  • TRUE OR UNKNOWN evaluates to TRUE.
  • FALSE OR UNKNOWN evaluates to UNKNOWN.
  • NOT UNKNOWN remains UNKNOWN.

These rules influence filters, joins, constraints, conditional expressions, and data-quality checks. A null-handling function does not change SQL's logical model; it changes the expression supplied to that model.

Replacing a null expression with NVL

The syntax of NVL is:

NVL(expression, replacement_value)

If expression is null, Oracle returns replacement_value. Otherwise, Oracle returns the original expression. The two arguments must be the same datatype or convertible to compatible datatypes.

A null salary does not mean that an employee earns zero. It may mean that a salary has not yet been assigned. A report can preserve that meaning by returning descriptive text:

SELECT
    ename,
    NVL(
        TO_CHAR(salary, 'FM999G999G990'),
        'NOT YET ASSIGNED'
    ) AS salary
FROM employee;

Illustrative output using comma grouping characters, not a captured database run:

ENAME       SALARY
----------- ----------------
BARRETT     85,000
BURLEEZE    101,000
DAHLSTROM   NOT YET ASSIGNED

TO_CHAR converts the numeric salary to character data before NVL is evaluated. This gives both possible return values compatible character datatypes. The phrase NOT YET ASSIGNED is a presentation value; the underlying salary remains null.

The G number-format element uses the session group separator. Set appropriate formatting for your report; do not assume every session displays a comma.

Numeric substitution

For arithmetic and aggregate calculations, replacing null with zero may be appropriate:

SELECT quantity,
       unit_price,
       NVL(discount_amount, 0) AS discount_amount,
       quantity * unit_price - NVL(discount_amount, 0) AS net_amount
FROM order_item;

Without NVL, a null discount_amount would cause the entire subtraction expression to return null. With NVL, the calculation treats a missing discount as zero.

Use zero only when it accurately represents the business meaning. A missing test score, account balance, or measurement may be unknown rather than zero. Substituting zero indiscriminately can produce misleading totals and averages.

NVL and implicit datatype conversion

Oracle may implicitly convert one NVL argument to the datatype of the other. Explicit conversion is safer because it makes the intended datatype visible and avoids conversion errors that depend on session settings.

NVL(TO_CHAR(hire_date, 'YYYY-MM-DD'), 'DATE UNKNOWN')

This expression is clearer than relying on Oracle to convert a date automatically. The same principle applies to numeric formatting and localized date or number representations.

How outer joins introduce null values

An outer join preserves rows from one side of a relationship even when no matching row exists on the other side. Oracle fills the missing side's columns with nulls. This behavior is essential for complete reports, but calculations based on those null-extended columns must be handled carefully.

The data dictionary views used in this lesson illustrate the problem:

  • DBA_DATA_FILES describes permanent database data files.
  • DBA_FREE_SPACE describes free extents in tablespaces.

A data file that contains no free extents can have no matching row in DBA_FREE_SPACE. An inner join would omit that file, making a completely full file disappear from the report. A left outer join preserves the row from DBA_DATA_FILES and returns null values for the unmatched DBA_FREE_SPACE columns.

The historical images use Oracle's legacy outer-join operator (+):

FROM
    sys.dba_free_space a,
    sys.dba_data_files b
WHERE
    a.file_id (+) = b.file_id
AND
    b.status = 'AVAILABLE'

The (+) marker identifies the optional side of the join. Oracle still recognizes this syntax, but ANSI join syntax is clearer and should be used for new SQL:

FROM sys.dba_data_files b
LEFT OUTER JOIN sys.dba_free_space a
    ON a.file_id = b.file_id
WHERE b.status = 'AVAILABLE'

In both forms, DBA_DATA_FILES is the preserved side. Every qualifying data file can therefore appear even when no free extent is found.

Using NVL in a data-file space report

When no DBA_FREE_SPACE row matches a data file, expressions such as SUM(a.bytes) and MAX(a.bytes) return null. The report can convert those results to zero:

NVL(SUM(a.bytes), 0)
NVL(MAX(a.bytes), 0)

For online files with complete free-extent visibility, no matching extent can be represented as zero. Missing metadata is not universally proof of zero: offline files in locally managed tablespaces may have no visible extent information. Verify file and tablespace state before interpreting this report.

Aggregate row counting requires an additional distinction. With an outer join, COUNT(*) counts the preserved result row even when every column from the optional table is null. To count actual matching free extents, count a non-null column from DBA_FREE_SPACE:

COUNT(a.bytes) AS free_extents

This returns zero for a data file with no matching free-space row.

Outer-join illustration

The two retained historical diagrams illustrate missing matches and null replacement. Their C1/C2/C3 labels and aligned rows are schematic, not real dictionary column definitions or a complete SQL result. The query below provides the executable structure.

FROM dba_data_files b
LEFT JOIN dba_free_space a ON a.file_id = b.file_id
Preserve the data-file side. A missing match produces null-extended columns from the free-space side.
The two sample data sets flow into an outer join that can produce null values

5. The outer join preserves the data-file rows. Where no free-space row matches, the result contains null values for the DBA_FREE_SPACE columns.



NVL replaces a null column value with numeric zero
SELECT NVL(CAST(NULL AS NUMBER), 0) AS replacement_value
FROM dual;

6. The self-contained SQL returns numeric zero. In the diagram, the function represents replacing a null numeric expression; it does not create a missing joined row.

Oracle 26ai data-file free-space example

This read-only illustration requires authorized access to DBA_DATA_FILES, DBA_FREE_SPACE, and DBA_TABLESPACES in the intended container. It covers online permanent files, not temporary space or autoextend headroom. STATUS = 'AVAILABLE' alone does not prove a file is online. Do not request SYSDBA merely to run a lesson example.

WITH free_space AS (
    SELECT file_id,
           COUNT(*) AS free_extents,
           SUM(bytes) AS free_bytes,
           MAX(bytes) AS largest_free_bytes
    FROM dba_free_space
    GROUP BY file_id
)
SELECT b.tablespace_name, b.file_id, b.file_name,
       NVL(f.free_extents, 0) AS free_extents,
       ROUND(b.bytes / 1048576, 2) AS allocated_mib,
       ROUND(NVL(f.free_bytes, 0) / 1048576, 2) AS free_mib,
       ROUND(NVL(f.free_bytes, 0) /
             NULLIF(b.bytes, 0) * 100, 2) AS pct_free,
       ROUND(NVL(f.largest_free_bytes, 0) / 1048576, 2)
           AS largest_free_extent_mib
FROM dba_data_files b
JOIN dba_tablespaces t ON t.tablespace_name = b.tablespace_name
LEFT JOIN free_space f ON f.file_id = b.file_id
WHERE b.status = 'AVAILABLE'
  AND b.online_status IN ('ONLINE', 'SYSTEM')
  AND t.status = 'ONLINE'
  AND t.contents = 'PERMANENT'
ORDER BY b.tablespace_name, b.file_id;

Aggregate the free extents before joining so that each file has at most one matching summary. Missing summaries are null-extended; NVL supplies zero under the stated online-file assumptions. In the earlier direct join, use COUNT(a.bytes) to count matching extents rather than COUNT(*). A grouped COUNT already returns a number; the missing summary row is what introduces null here.

One MiB is 1,048,576 bytes. The denominator is allocated file size, not maximum potential capacity. NULLIF makes a zero denominator yield null rather than a division error. This report is not a measure of unused space inside allocated segments or a complete capacity forecast. For CDB-wide reporting, use the appropriate CDB views and include CON_ID in grouping and joins.

Consult DBA_FREE_SPACE for its visibility limits. The SQL is documentation-reviewed and has not been executed here.

Oracle Tuning Reference

NVL, COALESCE, and CASE

NVL is concise and familiar in Oracle SQL, but it is not the only null-handling construct. COALESCE returns the first non-null expression from a list:

COALESCE(work_phone, mobile_phone, home_phone, 'NO PHONE')

Use COALESCE when several fallback expressions are required. A searched CASE expression is appropriate when the replacement depends on more than a simple null check:

CASE
    WHEN salary IS NULL THEN 'NOT ASSIGNED'
    WHEN salary < 50000 THEN 'BELOW RANGE'
    ELSE 'ASSIGNED'
END

For a direct two-value substitution in Oracle-specific SQL, NVL remains clear and effective.

COALESCE documents short-circuit evaluation. Do not assume NVL provides the same evaluation guarantee or that replacing one with the other preserves every datatype conversion. Check the intended result type before substituting functions.

NVL inside or outside an aggregate

WITH amounts (amount) AS (
    SELECT 10 FROM dual UNION ALL
    SELECT CAST(NULL AS NUMBER) FROM dual
)
SELECT AVG(amount) AS known_average,
       AVG(NVL(amount, 0)) AS null_as_zero_average,
       NVL(AVG(amount), 0) AS fallback_average
FROM amounts;

The expected values are 10, 5, and 10. Replacing each missing input with zero changes the average's population; replacing a null aggregate result supplies only a fallback. These are different business rules. This example is derived from the two inline rows, not a captured run.

Performance and correctness considerations

Null-handling expressions are often inexpensive, but their placement can affect access paths. Applying a function to a column can change predicate matching and access choices. A conventional index may still be used through transformations or scans; a full scan is not inevitable, and a function-based index is not automatically beneficial.

WHERE NVL(status_code, 'N') = 'A'

For a VARCHAR2 status code in this example, the fallback N cannot equal A, so WHERE status_code = 'A' expresses the same matching requirement. A target of N would also need to account for null rows. Before using this form in a high-volume query, review the execution plan and consider whether an equivalent predicate expresses the requirement more selectively. If the expression is used frequently and is important to query performance, a function-based index may be appropriate after workload testing.

Do not add NVL merely to make every output non-null. First determine what a null means, then choose a replacement that preserves the semantics of the data. This approach prevents a visually convenient report from becoming analytically incorrect.

Key points

After learning how NVL replaces null expressions, the next lesson examines another Oracle conditional translation function: DECODE.


SEMrush Software 3 SEMrush Banner 3