I have an example table "cities" like this:
id | city
----------------
1 London
2 Liverpool
3 Birmingham
4 (Other)
Can I write a query that returns (Other) if I provide a non-existing city... such as:
SELECT * FROM cities WHERE city = "London" --> {1, London}
SELECT * FROM cities WHERE city = "Manchester" --> {4, (Other) }
I understand that the second SELECT-statement will return nothing. But how can I modify it to return the "(Other)" row? Conceptual code:
SELECT * FROM cities WHERE city = "Manchester" OTHERWISE WHERE city = "(Other)"
One method is:
select c.*
from cities c
where c.city in (?, '(Other)')
order by c.city = '(Other)'
limit 1;
This retrieves the two rows possible rows that might match (? is a placeholder for the name you want). If there are two rows, then then one that is not "other" is chosen.
Consider:
select *
from cities
where
city = 'Manchester'
or (city = '(Other)' and not exists (select 1 from cities where city = 'Manchester'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With