Ozzy
Ozzy

Reputation: 10643

SQL return row if no result found

I have two tables:

person
id
name

car
name
person_id

Currently the query goes like:

SELECT
person.name
car.name
FROM
person, car
WHERE
person.id = car.person_id

Now this works fine if there is a car associated with a person. However if there isn't, then the person won't get returned. If a person has no car, I want to return a row with the text 'No Car' in column car.name.

Upvotes: 1

Views: 854

Answers (3)

Jackie Robinson
Jackie Robinson

Reputation: 94

SELECT person.name, CASE WHEN car.name IS NULL THEN 'no car' ELSE car.name END 
FROM person
LEFT JOIN car ON person.id = car.person_id

Upvotes: 0

Luis Tellez
Luis Tellez

Reputation: 2973

select person.name, ISNULL(car.name, 'no car')
from person
left join car on person.id = car.person_id

Upvotes: -1

Andrew
Andrew

Reputation: 27294

select person.name, coalesce(car.name, 'no car')
from person
left outer join car on person.id = car.person_id

Upvotes: 3

Related Questions