Give each table an alias
When two tables both have a CustomerId column, SQL Server can’t tell which one you mean unless you name the table. Give each table a short alias, then match the columns in the ON clause:
SELECT o.OrderId, o.CustomerId, c.CustomerName
FROM dbo.Orders AS o
INNER JOIN dbo.Customers AS c
ON o.CustomerId = c.CustomerId;
If you leave out the alias and write SELECT CustomerId, SQL Server returns an “ambiguous column name” error. Qualifying every shared column with its alias avoids that.
Watch out for duplicate names in the results
SELECT * returns both CustomerId columns. A query result can show two columns with the same name. A view or derived table can’t, though. If you wrap the join in a view, SQL Server returns an error saying the column was specified more than once. Give one of the columns an alias:
SELECT o.OrderId, o.CustomerId AS OrderCustomerId, c.CustomerId
FROM dbo.Orders AS o
INNER JOIN dbo.Customers AS c
ON o.CustomerId = c.CustomerId;
Use ON, not USING or NATURAL JOIN
Some databases let you write JOIN Customers USING (CustomerId), which lists the shared column once in the results. MySQL and PostgreSQL support USING and NATURAL JOIN. SQL Server supports neither, so write the ON condition instead.
Match on several columns or different names
The ON clause can compare more than one pair of columns:
SELECT o.OrderId, c.CustomerName
FROM dbo.Orders AS o
INNER JOIN dbo.Customers AS c
ON o.CustomerId = c.CustomerId
AND o.StoreId = c.StoreId;
The columns don’t need matching names. ON o.CustId = c.CustomerId works the same way, because ON compares whatever columns you name.
Rows with NULL keys and the join type
A comparison with NULL isn’t true, so a row whose join column is NULL doesn’t match anything. In an inner join, that row drops out of the results.
A plain JOIN in SQL Server is an INNER JOIN, so rows without a match are left out. To keep unmatched rows, you need an outer join. The difference is covered in what’s the difference between inner and outer join.
Same-named columns are often a primary key in one table and a foreign key in the other. That relationship is explained in what is a PK and FK.