Question

declare @t1 table (ID char(3) not null,Name char(5) not null)
insert into @t1(ID,  Name) values
('ID1','Test1'),
('ID2','Test2'),
('ID3','Test3')


declare @t2 table (ID char(3) not null)
insert into @t2(ID) values
('ID1'),
('ID2'),
('ID3'),
('ID4'),
('ID5')

SELECT id, name from @t1
WHERE id in (SELECT id from @t2)

This returns:

id  name
ID1 Test1
ID2 Test2
ID3 Test3

How could I get this code to return the the values for ID4 and ID5 as zero or null (ideally zero)? Like this:

id  name
ID1 Test1
ID2 Test2
ID3 Test3
ID4 NULL
ID5 NULL

With the solution provided I used ISNULL to return 0 instead of NULL.

Was it helpful?

Solution

You need to LEFT OUTER JOIN:

SELECT @t2.id, @t1.name from @t2 LEFT OUTER JOIN @t1 ON @t1.ID = @t2.ID

As opposed to an INNER JOIN an OUTER JOIN will take all rows from the source table instead of only those that also exist in the joined table.

OTHER TIPS

SELECT @t2.id, @t1.name 
from @t2
left join @t1 on @t1.id = @t2.id
SELECT aa.id,
       b1.name
from @t2 aa
LEFT JOIN @t1 b1 ON(aa.ID=b1.id)

Use COALESCE:

SELECT t1.id, COALESCE(t1.name, 0) 
FROM @t1 t1
LEFT OUTER JOIN @t2 t2
ON t2.id = t1.id

COALESCE will return the first non-null value in the argument list so if t1.name comes out as NULL then it will return 0 in its place.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top