Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query - select one if exists else other, never both

Tags:

sql

Let's say there is a table with two columns, First Name and Eye Color.

In this table you could potentially have:

Name - Green Eyes
Name - Brown Eyes

I'm trying to select all the rows for names with green eyes, but if there is a name that doesn't have green eyes, then I would like to select the name with Brown eyes. I never want to return two rows for a given name. Any thoughts on how to do this? Any help would be greatly appreciated!

like image 442
user1623682 Avatar asked May 21 '26 11:05

user1623682


2 Answers

SELECT COALESCE(g.name, b.name) name,
    COALESCE(g.eye_color, b.eye_color) eye_color

FROM (
  SELECT DISTINCT name, eye_color
  FROM eye_colors
  WHERE eye_color = 'green'
) g

FULL OUTER JOIN (
  SELECT DISTINCT name, eye_color
  FROM eye_colors
  WHERE eye_color = 'brown'
) b
ON b.name = g.name
like image 118
We Are All Monica Avatar answered May 23 '26 23:05

We Are All Monica


IF EXISTS(SELECT * FROM Table WHERE Color='Green')
    SELECT * FROM Table WHERE Color = 'Green'
ELSE
    SELECT * FROM Table WHERE Color='Brown'
like image 33
Irfan TahirKheli Avatar answered May 24 '26 00:05

Irfan TahirKheli



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!