PostgreSQL NULLIF
Summary: in this tutorial, you will learn how to use the PostgreSQL NULLIF()
function to handle null values.
Introduction to PostgreSQL NULLIF function
The NULLIF()
function is one of the most common conditional expressions provided by PostgreSQL.
Here’s the basic syntax of the NULLIF
function:
The NULLIF
function returns a null value if argument_1
equals to argument_2
, otherwise, it returns argument_1
.
PostgreSQL NULLIF function examples
Let’s take some examples of using the NULLIF()
function.
1) Basic PostgreSQL NULLIF examples
The following statements illustrate how to use the NULLIF()
function:
Output:
It returns null because the two arguments are equal.
The following example returns the first argument because the two arguments are not equal:
Output:
The following example uses the NULLIF()
function with two unequal text arguments:
Output:
2) Using the NULLIF function with table data
First, create a table called posts
:
Second, insert some sample data into the posts
table.
Output:
The goal is to retrieve data for displaying them on the post overview page that includes the title and excerpt of each post. To achieve this, you can use the first 40 characters of the post body as the excerpt.
Third, use the COALESCE function to handle NULL
in the body
column:
Output:
Unfortunately, there is a mix between null value and ” (empty) in the excerpt
column. To address this issue, you can use the NULLIF
function:
Output:
In this statement:
- First, the
NULLIF
function returns a null value if the excerpt is empty or the excerpt otherwise. The result of theNULLIF
function is used by theCOALESCE
function. - Second, the
COALESCE
function checks if the first argument, which is provided by theNULLIF
function, if it is null, then it returns the first 40 characters of the body; otherwise, it returns the excerpt in case the excerpt is not null.
Using NULLIF() function to prevent division-by-zero
Another good example of using the NULLIF
function is to prevent division-by-zero error.
First, create a new table named members:
Second, insert some rows for testing:
Output:
Third, calculate the ratio between male and female members:
In this example, we use the SUM function and CASE expression to calculate the total number of male members. Then we divide the total of male members by the total of female members to get the ratio. In this case, it returns 200%:
Fourth, delete a female member:
And execute the query to calculate the male/female ratio again:
We got the following error message:
The reason is that the number of females is zero now. To prevent this division by zero error, you can use the NULLIF
function as follows:
Output:
The NULLIF
function checks if the number of female members is zero, it returns null. The total of male members is divided by NULL
will return NULL
.
Summary
- Use the
NULLIF()
function to substitute NULL for displaying data and to prevent division by zero.