SimpleGuy SimpleGuy - 3 months ago 16
MySQL Question

SELECT CASE in MySQL

I am running a simple query having

SELECT CASE


SELECT DEPT_ID, DEPT_NAME =
CASE DEPT_NAME
WHEN 'PBG' THEN 'Best Dept'
ELSE 'Usual Dept'
END
FROM DEPARTMENTS;


However, the output is not satisfactory. All
0
is coming in output

enter image description here

What is wrong in query ?

Otherwise the table has below data

SELECT * FROM DEPARTMENTS;


enter image description here

Answer

Move the column alias DEPT_NAME. It should be placed after the case expression, not before:

SELECT DEPT_ID, 
    CASE DEPT_NAME
        WHEN 'PBG' THEN 'Best Dept'
        ELSE 'Usual Dept'
    END as DEPT_NAME 
FROM DEPARTMENTS;
Comments