Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql Case with Or condition

Tags:

sql

php

mysql

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;
like image 729
user1187 Avatar asked Jul 30 '12 04:07

user1187


People also ask

Can we use case in MySQL?

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.

Can we use case in where condition in SQL?

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.

Can we use case in update statement in MySQL?

#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.


2 Answers

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.

like image 198
OMG Ponies Avatar answered Oct 05 '22 22:10

OMG Ponies


SELECT IF((Confirm_Status IS NULL OR Confirm_Status = 0), 
           'Not Confirmed', 'Confirmed') AS ConfirmStatus
FROM tblConfirmationStatus;
like image 38
Omesh Avatar answered Oct 05 '22 22:10

Omesh