Our first Left Outer Join
Last updated
Last updated
SELECT *
FROM
[Pets] LEFT JOIN [Owners]
ON
[Pets].OwnerID = [Owners].OwnerID
SELECT [Pets].[Name], [Owners].[Name]
FROM
[Pets] LEFT JOIN [Owners]
ON
[Pets].OwnerID = [Owners].OwnerID
SELECT
A.[Name], B.[Name]
FROM
[Pets] AS A LEFT JOIN [Owners] AS B
ON
A.OwnerID = B.OwnerID
WHERE
LEFT(A.[Name], 1) = LEFT(B.[Name], 1)
Aliases for columns can be in two ways, let's check it out the first one:
-- ALIASES FOR COLUMNS
SELECT
A.[Name] AS PetName, B.[Name] AS OwnerName
FROM
[Pets] AS A LEFT JOIN [Owners] AS B
ON
A.OwnerID = B.OwnerID
WHERE
LEFT(A.[Name], 1) = LEFT(B.[Name], 1)
Or also you can write just as follows:
-- ALIASES FOR COLUMNS
-- No AS keyword for aliases
SELECT
A.[Name] PetName, B.[Name] OwnerName
FROM
[Pets] AS A LEFT JOIN [Owners] AS B
ON
A.OwnerID = B.OwnerID
WHERE
LEFT(A.[Name], 1) = LEFT(B.[Name], 1)
-- FULL CODE
-- ALIASES FOR TABLES
SELECT
A.[Name], B.[Name]
FROM
[Pets] AS A LEFT JOIN [Owners] AS B
ON
A.OwnerID = B.OwnerID
WHERE
LEFT(A.[Name], 1) = LEFT(B.[Name], 1)
-- ALIASES FOR COLUMNS
SELECT
A.[Name] AS PetName, B.[Name] AS OwnerName
FROM
[Pets] AS A LEFT JOIN [Owners] AS B
ON
A.OwnerID = B.OwnerID
WHERE
LEFT(A.[Name], 1) = LEFT(B.[Name], 1)
-- RIGHT JOINS
SELECT
A.[Name] AS PetName, B.[Name] AS OwnerName
FROM
[Owners] AS B RIGHT JOIN [Pets] AS A
ON
A.OwnerID = B.OwnerID
-- INNER JOINS
SELECT *
FROM [dbo].[Pets] AS A
INNER JOIN [dbo].[ProceduresHistory] AS B
ON A.Petid = B.PetID
-- COMPLEX JOINS
SELECT *
FROM
[dbo].[Pets] AS A
INNER JOIN [dbo].[ProceduresHistory] AS B
ON
A.Petid = B.PetID
LEFT JOIN [dbo].[ProceduresDetails] AS C
ON
B.ProcedureType = C.ProcedureType
AND
B.ProcedureSubCode = C.ProcedureSubCode
Here we have combined 3 tables:
Pets, ProceduresHistory and ProceduresDetails