SQL joining two tables

6.3k views Asked by At

I have 2 tables employees(id and name) and salary(id, salary), the 1st has 4 rows and 2nd has 2 rows.

table 1            Table 2
id   Name         id    salary
1     Sue          1    10000 
2    Sarah         3     9000
3    Nick 
4    james 

I want a join as follows

id   Name     Salary
1     Sue     10000
2    Sarah    No Salary
3    Nick     9000
4    james    No salary
4

There are 4 answers

2
Arda On BEST ANSWER

This should do the trick.

SELECT e.id, e.name , s.salary FROM employees e 
LEFT JOIN salary s
ON e.id=s.id
ORDER BY e.id ASC
0
Mikael Eriksson On

To get all rows from T1 when joining to table T2 that is lacking the rows 2 and 4 you need to use a left outer join. For row 2 and 4 salary will be null.

To replace the null value with something else you can use coalesce. Coalesce returns the first nonnull argument.

Since field salary is declared as an int field and you want No Salary as output where there is no salary you need to cast the int to a varchar before using it as an argument in coalesce.

declare @T1 table(id int, name varchar(10))
declare @T2 table(id int, salary int)

insert into @T1 values(1, 'Sue')
insert into @T1 values(2, 'Sarah')
insert into @T1 values(3, 'Nick')
insert into @T1 values(4, 'james') 

insert into @T2 values(1, 10000)
insert into @T2 values(3, 9000)

select
  T1.id,
  T1.name,
  coalesce(cast(T2.salary as varchar(10)), 'No Salary') as salary 
from @T1 as T1
  left outer join @T2 as T2
    on T1.id = T2.id  

Result

id          name       salary
----------- ---------- ----------
1           Sue        10000
2           Sarah      No Salary
3           Nick       9000
4           james      No Salary
0
BlackTigerX On
SELECT e.id, e.name , 
case
when s.salary is null then 'no salary'
else cast(s.salary as varchar)
end
FROM employees e LEFT JOIN salary s
ON e.id=s.id
order by e.id
1
zkhr On

Your goal is to list all employees, regardless of whether or not they have a listed salary, so you should be using a LEFT JOIN. An inner join would potentially list salaries for employees that no longer have a listing in the Employee table and an implicit join (I believe) would be missing rows.

Something like this should do what you need:

SELECT E.id, E.name, S.salary FROM Employees E LEFT JOIN Salary S ON E.id = S.id