How to write a case in mysql query which checks for null or 0 for a particular column
CREATE TABLE tblConfirmationStatus (Confirm_Status TINY INT) INSERT INTO tblConfirmationStatus Confirm_Status VALUES (1), (0), (1), ({null}), (0), (1), ({null})
Required Output
ConfirmStatus
Confirmed Not Confirmed Confirmed Not Confirmed Not Confirmed Confirmed Not Confirmed
0 or Null - Not Confirmed, 1-Confirmed
SELECT CASE Confirm_Status WHEN NULL OR 0 THEN 'Not Confirmed' ELSE 'Confirmed' END AS ConfirmStatus FROM tblConfirmationStatus;
The MySQL CASE StatementThe CASE statement goes through conditions and returns a value when the first condition is met (like an if-then-else statement). So, once a condition is true, it will stop reading and return the result. If no conditions are true, it returns the value in the ELSE clause.
CASE can be used in any statement or clause that allows a valid expression. For example, you can use CASE in statements such as SELECT, UPDATE, DELETE and SET, and in clauses such as select_list, IN, WHERE, ORDER BY, and HAVING.
#3) With UPDATE StatementsMySQL CASE can also be used while updating an existing column in the table. Let's try to understand this with the help of an example with the test data we have. We can use the below query to achieve such updates without having to write UPDATE queries to have multiple WHERE or IF clauses.
There's two options for CASE statements - the one you posted, or:
SELECT CASE
WHEN Confirm_Status IS NULL OR Confirm_Status = 0 THEN 'Not Confirmed'
ELSE 'Confirmed'
END AS ConfirmStatus
But you could probably use:
SELECT CASE
WHEN Confirm_Status > 0 THEN 'Confirmed'
ELSE 'Not Confirmed'
END AS ConfirmStatus
NULL
is the absence of a value, so checking for values above zero should fall into the same category as zero.
SELECT IF((Confirm_Status IS NULL OR Confirm_Status = 0),
'Not Confirmed', 'Confirmed') AS ConfirmStatus
FROM tblConfirmationStatus;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With