Replacing Nulls with the NVL Function, Explained

UPI Study › Courses › Database Programming › Free lessons › Lesson 5.7 Free with a free account

Replacing Nulls with the NVL Function

Database Programming · Chapter 5: Querying, Filtering, and Sorting DataSection 5.7 · lesson 32 of 768 min · free with a free account

← Built-In SQL Functions: How and When to Use ThemNext lesson: Conditional Logic in SQL: The CASE Statement →

A free account plays all of Chapter 1 and 3 more lessons of Database Programming. Create a free account →

Earn 3 college credits for Database ProgrammingRecommended for credit by NCCRS · Computer Science 381 · self-paced · one payment, lifetime access

In this lesson

Translating Oracle NVL and NVL2 with COALESCE, NULLIF, and CASE.

  • Explain how Oracle's NVL and NVL2 functions choose their results
  • Rewrite NVL expressions with COALESCE for MySQL, SQL Server, and SQLite
  • Use NULLIF to turn placeholders and zero denominators into NULL
  • Compare NVL, ISNULL, IFNULL, and COALESCE across database systems

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (956 words). Read along, or search it.

Opening Question

Oracle NVL Rejected by a SQLite Shell

Leo Park receives an Oracle report for Lantern Books. Its bonus calculation uses a function named N V L, but the bookstore's local SQLite shell rejects that name. Should he change the missing values, or translate the expression? The right answer depends on the report's intended replacement policy, as well as its dialect. Null-handling functions can preserve a calculation or supply a display label. They cannot tell us what an unknown value really was.

Replacement Policy

A Replacement Is a Policy Assumption

Return to our disposable staff extension. Salary is recorded for every illustrative staff member; some bonus amounts remain missing. Adding salary and a missing bonus produces a missing total. Replacing that bonus with zero produces a usable amount only if the policy permits that assumption. The stored bonus remains missing during a select. A substitution leaves the source record untouched; it does not document approval of a zero. Keep numeric replacements numeric and text replacements textual. Compatible types help avoid conversions that either fail or hide a different meaning.

Oracle Syntax

NVL and NVL2 in Oracle

Oracle's N V L takes two arguments. It returns the first when a value exists, or the replacement when the first is null. Read the first expression as salary plus the bonus, with zero substituted for a missing bonus. This listing is Oracle syntax, never a SQLite command. N V L two takes three arguments. The first is tested; a present value selects the second argument, while a missing value selects the third. That allows a label instead of merely returning the original bonus. A recorded zero still selects Recorded, because zero is present. Oracle treats empty text as null. MySQL, SQL Server, and SQLite distinguish empty text from null, so translating names alone does not settle every data difference.

Portable Replacement

COALESCE as the Portable NVL Equivalent

Coalesce is the portable replacement spelling. It returns the first argument that is not null; a two-argument call can express this N V L policy. The fallback is numeric zero, matching the bonus's numeric meaning. For a missing amount that must remain unresolved, keep null instead of choosing an unjustified default. Run the comparison. Our SQLite output demonstrates the replacement expression, without pretending to execute the Oracle function. Ben's raw total is null, and the assumed total equals salary. The other records preserve their recorded bonus amounts; coalesce does not replace present values.

Preference List

Mobile, Office, Then Home Fallbacks

Coalesce can express a preference list. These disposable contact labels stand for a mobile number, an office number, and a home number. The argument order is the preference order. Mobile wins when available; otherwise try office, then home, and finally a display fallback. Run the expression for each temporary record. The same list handles a late available value, an early available value, and a record with no contact. The results are Home A, Mobile B, and none. If every argument were null with no nonnull fallback, the result would remain null.

Reverse Direction

NULLIF for Placeholders and Zero Denominators

Null if works in the opposite direction. When its two arguments compare equal, it returns null; otherwise it returns its first argument. An empty-text placeholder can become a missing marker. A nonempty city remains present; Oracle's empty-text rule already collapses that particular distinction. A zero denominator can likewise become null before division. That avoids a zero-division failure on systems that would raise one, while preserving an unresolved rate. Run both examples. Using a noninteger numerator also makes the intended fractional division clear in SQLite and SQL Server. The zero-denominator rate is missing, while the valid rate is thirty. Replacing the unresolved rate with zero afterward would add a separate business assumption.

Translating NVL2

A Searched CASE for Recorded or Missing

A searched case expression translates the N V L two decision. It tests bonus missingness, then returns one of two text labels. Its branches return compatible values. This expression can run in Oracle, MySQL, SQL Server, or SQLite when the surrounding schema exists. Run the translated status expression. We are testing whether a value is present, rather than whether the amount is positive. Ben is Missing, while Asha and Chen are Recorded. Use is null or is not null for this decision; ordinary equality with null is not a missingness test.

Function Map

NVL, ISNULL, IFNULL, and COALESCE Compared

Keep the function map nearby when translating. Oracle N V L, SQL Server is null, and MySQL if null can express a two-value replacement. MySQL's one-argument is null function only tests missingness. Passing a replacement as a second argument is not its syntax. SQL Server is null normally retains the first expression's type, which can truncate a long text replacement. Coalesce follows different type-selection rules. Portable spelling still requires compatible arguments. Some systems may evaluate complex coalesce inputs more than once, so avoid assuming identical evaluation behavior across engines. For ordinary column fallbacks, state the preference and policy clearly. Test translation with missing, zero, empty, and ordinary values instead of checking only a typical row.

Quick Check

NULLIF Inside COALESCE Versus Plain COALESCE

A new expression first applies null if to matching zeros, then supplies a fallback. Another expression applies coalesce directly to a zero. Which pair appears, converted first and preserved second? Pause, and decide.

Answer

Results Are Seven and Zero

The answer is seven and zero. Null if converts the equal zeros to null, so the first coalesce reaches its fallback. The second expression starts with a present zero, so it never needs the fallback value. Missingness and numeric truthiness are different questions. Zero and seven reverses the effects, while seven twice incorrectly treats zero as missing. The run shows why the inner transformation changes only the first result.

Key Takeaways

Translate the Contract, Not the Name

Leo can translate the Oracle report while preserving its declared assumptions. He uses coalesce for fallbacks, null if for selected placeholders, and case for conditional labels. Choose the replacement's type and meaning deliberately. Returning a helpful display is different from learning an unknown fact. Test the target engine with missing and present values. A portable expression succeeds because its contract fits the data, rather than because its name sounds familiar.

About Database Programming at UPI Study

Database Programming (Computer Science 381) is a self-paced online course of 76 video lessons in 12 chapters, from database applications, SQL setup, schema planning and normalization to keys and constraints, data types, filtering and sorting, joins, subqueries, views, indexes, ROLLUP and PIVOT, regular expressions and database security. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: Database Fundamentals vs Database Programming

Why take it here

Why students take Database Programming with UPI Study

Write the SQL behind every appDatabase Programming teaches SQL in MySQL and SQL Server side by side: designing and normalizing tables, keys and constraints, data types, inserting, updating and deleting rows, filtering, grouping, joins, subqueries, views, indexes, transactions, and protecting data from SQL injection. It suits computer science and information technology degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Database Programming carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Replacing Nulls with the NVL Function

What does the NVL function do in Oracle?
In Oracle, NVL(expr1, expr2) returns expr2 when expr1 is NULL and expr1 otherwise, so salary + NVL(bonus, 0) treats a missing bonus as zero. Other systems use different names: SQL Server has ISNULL, MySQL has IFNULL, and COALESCE works in all of them. One Oracle difference matters when translating: Oracle treats an empty string as NULL, while MySQL, SQL Server, and SQLite treat it as known text.
What is the difference between NVL and NVL2?
NVL replaces a NULL with one value, while Oracle's NVL2 chooses between two results based on whether the first argument is NULL. NVL2(bonus, 'Recorded', 'Missing') returns 'Recorded' when bonus has a value, even zero, and 'Missing' when it is NULL. MySQL, SQL Server, and SQLite have no NVL2, so translate it with a searched CASE: CASE WHEN bonus IS NOT NULL THEN 'Recorded' ELSE 'Missing' END.
How does COALESCE work with more than two arguments?
COALESCE checks its arguments from left to right and returns the first one that is not NULL. For example, COALESCE(mobile, office, home, 'none') returns the mobile number when present, otherwise the office number, then the home number, and finally the word none. If every argument is NULL and no fixed fallback is supplied, the result is NULL. A present value such as zero stops the search, and so does empty text outside Oracle.
How do you avoid division by zero with NULLIF?
Wrap the denominator in NULLIF so a zero becomes NULL, as in sold * 1.0 / NULLIF(visits, 0) AS rate. NULLIF(a, b) returns NULL when its arguments are equal, so the division yields NULL instead of an error on systems that raise one, such as SQL Server. The 1.0 keeps the fraction in SQLite and SQL Server. Replacing the NULL result with zero afterwards is a separate reporting decision.

About the Database Programming course

How many college credits is Database Programming?
Database Programming (Computer Science 381) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Database Programming cost and what is included?
$250, paid once, with lifetime access: all 76 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Database Programming take?
It is self-paced with no deadlines. The 76 lessons total about 11 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Database Programming.

76 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Updated

Database Programming
3 credits · NCCRS
Enroll →