📅  最后修改于: 2023-12-03 15:33:01.332000             🧑  作者: Mango
MySQL's CASE
statement is a powerful tool that allows users to perform conditional logic within their queries. However, there are some quirks to its behavior with null values that developers need to be aware of.
Suppose we have a table called employees
with three columns: id
, name
, and salary
. Some of the employees don't have a salary value, and are represented as null in the salary
column. We want to return a list of all employees, but for those without a salary, we want to display a message instead. Here's a sample query:
SELECT id, name,
CASE
WHEN salary IS NULL THEN 'No salary information available.'
ELSE salary
END AS salary
FROM employees;
This seems like it should work, and for the most part, it does! When we run this query, we see that all employees with a non-null salary have that salary displayed correctly, and all employees without a salary have the message 'No salary information available.'
displayed instead.
However, there's one gotcha: the salary
column is returned as a string! For employees with a salary, this isn't a problem, since the value is already a string. But for employees without a salary, we'd really prefer to see null displayed – after all, null
is the canonical representation of "no value".
Unfortunately, it's not as simple as changing the case statement to return null:
SELECT id, name,
CASE
WHEN salary IS NULL THEN NULL
ELSE salary
END AS salary
FROM employees;
This returns the same string value for employees without a salary: 'No salary information available.'
.
To return null, we need to explicitly cast it to the appropriate type. In this case, we want the salary
column to be numeric, so we can cast null to a numeric value using the CAST()
function. Here's the correct query:
SELECT id, name,
CASE
WHEN salary IS NULL THEN CAST(NULL AS DECIMAL(10,2))
ELSE salary
END AS salary
FROM employees;
This query returns numeric values for employees with a salary, and null values (in numeric format) for employees without a salary.
MySQL's CASE
statement is a powerful tool for performing conditional logic in our queries. However, we need to be aware of its behavior with null values. By explicitly casting null to the appropriate data type, we can ensure that our queries return the expected results, even when dealing with null values.