A blog about SQL Server, SSIS, C# and whatever else I happen to be dealing with in my professional life.

Find ramblings

Tuesday, September 22, 2009

Basics of joins

On a DDD, Date Driven Development, project, our boss has identified
that we need to make use of a junior developer for the database work.
By "make use," she means train to use SSIS but I'm pretty positive
they've never written a query before. This post and upcoming posts
will hopefully cover the information I'm trying to educate the Junior
on. When I started working with ANSI joins, I made a diagram to help
keep me straight.

The following TSQL will create concrete examples for them to work
against vs hypothetical sets


CREATE TABLE dbo.ODDS
(
col1 int NOT NULL PRIMARY KEY
)
GO

CREATE TABLE dbo.EVENS
(
col1 int NOT NULL PRIMARY KEY
)
GO
INSERT INTO
dbo.ODDS
-- Yes, I know zero isn't odd but it's illustrative
SELECT
0 AS col1
UNION ALL
SELECT
1
UNION ALL
SELECT
3
UNION ALL
SELECT
5
UNION ALL
SELECT
7
UNION ALL
SELECT
9
GO
INSERT INTO
dbo.EVENS
SELECT
0 AS col1
UNION ALL
SELECT
2
UNION ALL
SELECT
4
UNION ALL
SELECT
6
UNION ALL
SELECT
8
UNION ALL
SELECT
10
GO

SET NOCOUNT ON

Green:
SELECT
*
FROM
dbo.ODDS A
INNER JOIN
dbo.EVENS B
ON B.col1 = A.col1

Yellow:
SELECT
A.*
FROM
dbo.ODDS A
LEFT OUTER JOIN
dbo.EVENS B
ON B.col1 = A.col1
WHERE
B.col1 IS NULL

Blue:
SELECT
B.*
FROM
dbo.ODDS A
RIGHT OUTER JOIN
dbo.EVENS B
ON B.col1 = A.col1
WHERE
A.col1 IS NULL


Colorblind:
SELECT
*
FROM
dbo.ODDS A
FULL OUTER JOIN
dbo.EVENS B
ON A.col1 = B.col1

GO
DROP TABLE dbo.ODDS
GO
DROP TABLE dbo.EVENS
GO

TODO: Set code with colors

No comments: