1

I am trying to write MySQL query if else for this table,

table name: users

user_id | username | password | status
1  | john  | 1 | 1
2  | jessi | 2 | 0
3  | mark  | 1 | 2

status: 1 - enable, 0 - disable, 2 - deleted

I wrote SQL to get status data :

SELECT username, user_id, IF( STATUS =1,  'Enable',  'Disable' ) AS user_status
FROM `users` 

how to write MySQL if elseif else statement for get all three status

3
  • That logic is most appropriately placed in a CASE Commented Jun 5, 2014 at 16:29
  • @MichaelBerkowski could you please explain how to write case for this Commented Jun 5, 2014 at 16:31
  • See answers below, something like... CASE WHEN STATUS = 1 THEN 'Enable' WHEN STATUS = 0 THEN 'Disable' WHEN STATUS = 2 THEN 'Deleted' ELSE 'Unknown Status' END Commented Jun 5, 2014 at 16:33

2 Answers 2

3

You can use a CASE statment for that. Like this:

SELECT 
   username, 
   user_id, 
   (CASE STATUS
     WHEN 1 
     THEN 'Enable'
     WHEN 0 
     THEN 'Disable'
     WHEN 2
     THEN 'Deleted'
     ELSE 'Unknowed' 
   END) AS user_status 
FROM  
   `users`

Reference:

Sign up to request clarification or add additional context in comments.

2 Comments

The OP has 3 states 1 - enalbe, 0 - disalbe, 2 - deleted
@MichaelBerkowski : Update the answer. With the cases. Thanks for pointing that out
1

You can use nested IFs:

SELECT username, user_id, IF( `status`=1,  'Enable',  IF(`status`=2, 'Deleted', 'Disabled') ) AS user_status FROM  `users`

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.