Skip to Main Content

SQL & PL/SQL

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

Tips about nulls in Oracle SQL

User_1871Jul 11 2022 — edited Feb 7 2024

What are some tips about nulls in SQL you can share?

As a novice, this is what I have so far:

  1. We can't do math on nulls: 1 + NULL = NULL.
    Sometimes, people assume nulls will be automatically treated as zero. But that's not the case. We would need to explicitly convert nulls to something else (like zero) using COALESCE(), NVL(), etc..
  2. NULL doesn't equal NULL. More specifically, null is neither equal to, nor is it not equal, to null.
    WHERE NULL = NULL won't return any results. Neither will WHERE NULL <> NULL.
    Further, be careful of cases such as WHERE Field1 <> ‘ABC’. If Field1 is null, that row won't get selected, even though it isn't ‘ABC’. Because null is neither equal to, nor is it not equal, to anything.
    Joining on null values won't work either.
  3. Aggregate functions such as AVG() will ignore nulls. AVG(4,4,4,4,4,NULL) will evaluate to 4 (not 3.33).
    But be careful when doing math on the result of aggregate functions. Example: SUM(A) + SUM(B). Remember, we can't do math on nulls. So if the result of either of those aggregate functions is null, then the entire expression will evaluate to null.
  4. Different databases concatenate nulls differently. For example, in Oracle, nulls will be ignored in this concatenation: 'FOO ' || NULL || 'BAR' …will evaluate to… FOO BAR. But in other databases, that would result in NULL.
  5. Different databases treat empty strings differently. For example, in Oracle, SELECT '' FROM MY_TABLE will result in null. That's important when comparing values. If we are attempting to get rid of nulls, we wouldn't want to replace NULL with '', since '' would simply result in null. With that said, putting a space ' ' between the single quotes would work; that won't get automatically converted to null.

Are there any other gotchas or tips about nulls you can share? Or any improvements or corrections to the points above?
Thanks.

This post has been answered by Frank Kulash on Jul 11 2022
Jump to Answer

Comments

Post Details

Added on Jul 11 2022
9 comments
3,670 views