stack stack - 3 months ago 8
MySQL Question

How to use CASE statement once for multiple columns when the condition is identical?

I have a query like this:

SELECT (CASE WHEN subject = '' THEN $subject ELSE subject END ) main_subject,
(CASE WHEN subject = '' THEN $id ELSE id END ) main_id,
(CASE WHEN subject = '' THEN $related ELSE related END ) main_related
FROM qanda
WHERE tag = :tag;


As you see, the condition is identical in all conditions .. So I want to know, can I improve that? I mean can I write
CASE
just one time for all cases?

Answer

Your code is fine. If you really wanted to, you could do:

SELECT $subject as main_subject, $id as main_id, $related as main_related
FROM qanda
WHERE tag = :tag AND subject = ''
UNION ALL
SELECT subject as main_subject, id as main_id, related as main_related
FROM qanda
WHERE tag = :tag AND (subject <> '' or subject IS NULL)

This gets rid of the CASE statements, but I don't think it is a real simplification. It does, however, reduce the number of times that the condition needs to be copied, which can be a simplification if you have lots of columns.