Gayan
Gayan

Reputation: 2935

How to write MySQL Query IF ELSEIF ELSE

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

Upvotes: 1

Views: 187

Answers (2)

Arion
Arion

Reputation: 31239

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:

Upvotes: 3

marekful
marekful

Reputation: 15351

You can use nested IFs:

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

Upvotes: 1

Related Questions