Setup: (1) Employee table (employeeID, firstName, lastName)
(1) Shoe table (shoeID, Employee_employeeID, shoeName, shoeColor, shoeBrand)
I want to select all rows in Employee table and even if there is no matching EmployeeID (Employee_EmployeeID) in the shoe table display that entire row anyway. Example desired output:
EmployeeID | firstName | lastName | shoeName | shoeColor | shoeBrand
1 John Smith AirMax2 Red Nike
2 Ronald Mcdonald null null null
3 James Knight null null null
4 Cindy Smith Pump Brown Cole Haan
I have tried a lot of different joins and I will get duplicate rows for each Employee.
The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the right table. This means that if the ON clause matches 0 (zero) records in the right table; the join will still return a row in the result, but with NULL in each column from the right table.
Since it's not possible to join on NULL values in SQL Server like you might expect, we need to be creative to achieve the results we want. One option is to make our AccountType column NOT NULL and set some other default value. Another option is to create a new column that will act as a surrogate key to join on instead.
How to Select All Records from One Table That Do Not Exist in Another Table in SQL? We can get the records in one table that doesn't exist in another table by using NOT IN or NOT EXISTS with the subqueries including the other table in the subqueries.
try this
SELECT e.employeeId,e.firstName,e.lastName,s.ShoeName,s.ShoeColor,s.ShoeBrand
FROM Employee e
LEFT JOIN Shoe s
ON e.employeeID = s.Employee_employeeID
DEMO SQLFIDDLE HERE
You are going to want to use a LEFT JOIN
:
select e.employeeId,
e.firstName,
e.lastName,
s.ShoeName,
s.ShoeColor,
s.ShoeBrand
from Employee e
left join shoe s
on e.employeeID = s.Employee_employeeID
See SQL Fiddle with Demo
A LEFT JOIN
will return the matching rows from the employee
table even if there is not a matching row in the shoe
table.
If you need help learning JOIN
syntax, here is a great visual explanation of joins.
Now, if you wanted all rows that match both tables, then you would use an INNER JOIN
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With