Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

How can I use CASE in a MySQL query? I'd like to perform something like this, where the value of one column on the table/view is used to create another column in the result set.

I don't know the correct syntax. How can this be done?

SELECT CASE WHEN sex = 1 THEN 'Boy' ELSE THEN 'Girl' sex 
FROM user
share|improve this question
 
Don't you mean update? –  Mihai Aug 26 '13 at 16:33
 
May I just add that the username and question are one in the same. –  DevlshOne Aug 26 '13 at 16:34
add comment

closed as unclear what you're asking by DevlshOne, Slater Tyranus, iCodez, Cfreak, Sindre Sorhus Aug 26 '13 at 17:48

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question.If this question can be reworded to fit the rules in the help center, please edit the question.

2 Answers

Error syntax???

select 
CASE
    WHEN sex = 1
    THEN 'Boy'
    ELSE 'Girl'
end as sexName
FROM user
share|improve this answer
 
Should be end as sex, because OP is trying to "change data type". –  dcaswell Aug 26 '13 at 16:35
 
It's not trying to change data type, it's rather projecting the value of one column into another. –  p.campbell Aug 26 '13 at 16:37
 
He wants to use the same column name as currently exists for the column. He just want to change the contents. –  dcaswell Aug 26 '13 at 16:38
 
The main question is not name of column but as he can retrieve that information. I add sexName (it's ok?) ;) –  Joe Taras Aug 26 '13 at 16:40
add comment
SELECT
CASE
    WHEN sex = 1
    THEN 'Boy'
    ELSE 'Girl'
END as sex
FROM user
share|improve this answer
 
Tks! it working –  Dung Sep 4 '13 at 15:58
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.