MySQL COALESCE Function?
Summary: this tutorial introduces you to the MySQL COALESCE function that allows you to substitute NULL values.
Introduction to MySQL COALESCE function
The following illustrates the
COALESCE
function syntax:
The
COALESCE
function takes a number of arguments and returns the first non-NULL argument. In case all arguments are NULL, the COALESCE
function returns NULL.
The following shows some simple examples of using the
COALESCE
function:MySQL COALESCE function examples
See the following
customers
table in the sample database.
The following query returns customer name, city, state, and country of all customers in the
customers
table.
As you see, the state column has NULL values because some this information is not applicable to the country of some customers.
To substitute the NULL value in the result set, you can use the
COALESCE
function as follows:
In this example, if the value in the state column is NULL, the
COALESCE
function will substitute it by the N/A
string. Otherwise, it returns the value of the state column.
Another typical example of using the
COALESCE
function is to substitute value in one column by another when the first one is NULL.
Suppose you have an
articles
table with the following structure:
Let’s insert some data into the
articles
table.
Imagine you have to display articles on an overview page where each article contains the title, expert, and publish date (and also the read more link the article page). The first task you need to do is to query this data from the
articles
table:
As you see the article with id 2 does not have the excerpt, which is not nice for displaying.
A typical solution is to get the first number of characters in the
body
of the article for displaying as the excerpt. This is why the COALESCE
function comes into play.
In this example, if the value in the excerpt column is NULL, the
COALESCE
function returns the first 150 characters of the content in the body
column.MySQL COALESCE and CASE expression
Besides using the
COALESCE
function, you can use the CASE
expression to achieve the same effect.
The following query uses the
CASE
expression to achieve the same result as the example above:
In this example, the
CASE
expression is more lengthy than using the COALESCE
function.MySQL COALESCE vs. IFNULL
The
IFNULL
function takes two arguments and returns the first argument if it is not NULL, otherwise, it returns the second argument.
The
IFNULL
function works great with two arguments whereas the COALESCE
function works with n
arguments. In case the number of arguments is two, both functions are the same.
In this tutorial, you have learned how to use the MySQL COALESCE function to substitute NULL values.
0 comments:
Post a Comment