Skip to content
Advertisement

SQL Query return extra column depending of condition

I want to make a query which will add a column depending of what condition is meet(I have tried with sequelize without obtaining the result that I wanted) therefore I want to try with plain SQL because It does not have as many limitations.

EXAMPLE: SELECT * FROM db.messages WHERE user_id = userID OR $contacts.user_id$ = userID

If the first condition is meet I want to add a column like:

SELECT *,'type' as 'Inbox' FROM db.messages

Second condition:

SELECT *,'type' as 'Send' FROM db.messages

I have not manage to implement it with a CASE...THEN

I would appreciette any comment.

SQL CASE STatement:

SELECT *,
CASE
    WHEN user_id = userID THEN 'Inbox'
    WHEN $contacts.user_id$ = userID THEN 'Send'
    ELSE NULL
END AS type
FROM db.messages;

Advertisement

Answer

The syntax for the case statement seems to be invalid, check the documentation. Instead of this:

select
    case
        when a = x then 'a' as result
        when b = x then 'b' as result
        else null
    end as y
from table_name

Try this:

select
    case
        when a = x then 'a'
        when b = x then 'b'
    end as 'result'
from table_name

or even simpler:

select
    case x
        when a then 'a'
        when b then 'b'
    end as 'result'
from table_name 
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement