Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL query that returns a default row if no other row is matched

Tags:

sql

mysql

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)"
like image 446
Gowire Avatar asked Dec 06 '25 10:12

Gowire


2 Answers

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.

like image 162
Gordon Linoff Avatar answered Dec 08 '25 22:12

Gordon Linoff


Consider:

select * 
from cities 
where 
    city = 'Manchester'
    or (city = '(Other)' and not exists (select 1 from cities where city = 'Manchester'))
like image 45
GMB Avatar answered Dec 08 '25 23:12

GMB



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!