Real databases keep data in many tables, so almost every useful query needs a JOIN. This guide explains every join type in SQL Server with the same small Employees, Departments and Projects tables, shows the exact result of each query, and finishes with the mistakes that cause wrong or huge results.
Part of the SQL Server for Beginners series. This article is the written version of lesson 2 of the Bigland Network video course, with the same sample data. The results shown were worked out by hand from that data, so run every example on a test database, not on production data.
Watch lesson 2 as a video or open it on YouTube. The written lesson below follows the same steps and the same sample data.
Contents
- 1. Why data is split into tables
- 2. INNER JOIN
- 3. LEFT JOIN
- 4. RIGHT and FULL OUTER JOIN
- 5. CROSS JOIN
- 6. Joining three tables
- 7. Self join
- 8. JOIN with GROUP BY
- 9. Mistakes and best practices
- 10. Practice
1. Why data is split into tables
One big table that repeats the department name on every employee wastes space and invites mistakes: rename a department and you must change many rows. Databases instead keep each kind of thing in its own table and connect them with keys. A primary key uniquely identifies a row (DeptId in Departments). A foreign key is a column that points to another table’s primary key (DeptId in Employees). A JOIN follows that link at query time.
This lesson uses three tables. Create them with this script (it is reused in the next lessons):
CREATE DATABASE BiglandTraining;
GO
USE BiglandTraining;
GO
CREATE TABLE Departments (
DeptId INT PRIMARY KEY,
DeptName VARCHAR(50) NOT NULL,
Location VARCHAR(50)
);
CREATE TABLE Employees (
Id INT IDENTITY(1,1) PRIMARY KEY,
FirstName VARCHAR(50) NOT NULL,
DeptId INT NULL REFERENCES Departments(DeptId),
Salary INT NOT NULL,
ManagerId INT NULL REFERENCES Employees(Id)
);
CREATE TABLE Projects (
ProjectId INT IDENTITY(1,1) PRIMARY KEY,
ProjectName VARCHAR(100) NOT NULL,
EmpId INT NOT NULL REFERENCES Employees(Id)
);
INSERT INTO Departments VALUES (1,'Sales','Casablanca'),(2,'IT','Rabat'),(3,'HR','Marrakech'),(4,'Finance','Tangier');
INSERT INTO Employees (FirstName, DeptId, Salary, ManagerId) VALUES
('Amina',1,4200,NULL),('Youssef',2,5200,NULL),('Salma',1,3600,1),
('Karim',3,3100,NULL),('Nadia',2,4800,2),('Omar',NULL,3900,2);
INSERT INTO Projects (ProjectName, EmpId) VALUES
('Website Redesign',2),('Network Upgrade',5),('Payroll Audit',1),('Migration to Azure',2);
| Id | FirstName | DeptId | Salary |
|---|---|---|---|
| 1 | Amina | 1 | 4200 |
| 2 | Youssef | 2 | 5200 |
| 3 | Salma | 1 | 3600 |
| 4 | Karim | 3 | 3100 |
| 5 | Nadia | 2 | 4800 |
| 6 | Omar | NULL | 3900 |
| DeptId | DeptName | Location |
|---|---|---|
| 1 | Sales | Casablanca |
| 2 | IT | Rabat |
| 3 | HR | Marrakech |
| 4 | Finance | Tangier |
Notice two details we will use later: Omar has no department (NULL) and the Finance department has no employees.
2. INNER JOIN
INNER JOIN returns only the rows that have a match on both sides. The ON clause says how the tables match. Short names after the table (aliases) keep the query readable.
SELECT e.FirstName, d.DeptName
FROM Employees e
INNER JOIN Departments d
ON e.DeptId = d.DeptId;
| FirstName | DeptName |
|---|---|
| Amina | Sales |
| Youssef | IT |
| Salma | Sales |
| Karim | HR |
| Nadia | IT |
Omar is missing because he has no department, and Finance is missing because nobody works there. If a column name exists in both tables (for example DeptId), SQL Server raises an ambiguous column name error: write e.DeptId or d.DeptId.
You can still filter and sort a join in the usual way:
SELECT e.FirstName, e.Salary, d.DeptName
FROM Employees e
INNER JOIN Departments d ON e.DeptId = d.DeptId
WHERE d.DeptName = 'IT'
ORDER BY e.Salary DESC;
| FirstName | Salary | DeptName |
|---|---|---|
| Youssef | 5200 | IT |
| Nadia | 4800 | IT |
3. LEFT JOIN and finding rows with no match
LEFT JOIN keeps every row of the left table, and fills the right side with NULL when there is no match:
SELECT e.FirstName, d.DeptName
FROM Employees e
LEFT JOIN Departments d
ON e.DeptId = d.DeptId;
| FirstName | DeptName |
|---|---|
| Amina | Sales |
| Youssef | IT |
| Salma | Sales |
| Karim | HR |
| Nadia | IT |
| Omar | NULL |
A classic trick: add WHERE ... IS NULL on the right table to find rows that have no match. Which departments have no employees?
SELECT d.DeptName
FROM Departments d
LEFT JOIN Employees e
ON e.DeptId = d.DeptId
WHERE e.Id IS NULL;
| DeptName |
|---|
| Finance |
4. RIGHT JOIN and FULL OUTER JOIN
RIGHT JOIN is the mirror image: it keeps every row of the right table. Most people simply swap the table order and use LEFT JOIN. With Departments on the right, Finance appears with an empty name:
SELECT e.FirstName, d.DeptName
FROM Employees e
RIGHT JOIN Departments d
ON e.DeptId = d.DeptId;
| FirstName | DeptName |
|---|---|
| Amina | Sales |
| Youssef | IT |
| Salma | Sales |
| Karim | HR |
| Nadia | IT |
| NULL | Finance |
FULL OUTER JOIN keeps unmatched rows from both sides, so you see both Omar (no department) and Finance (no employee):
SELECT e.FirstName, d.DeptName
FROM Employees e
FULL OUTER JOIN Departments d
ON e.DeptId = d.DeptId;
| FirstName | DeptName |
|---|---|
| Amina | Sales |
| Youssef | IT |
| Salma | Sales |
| Karim | HR |
| Nadia | IT |
| Omar | NULL |
| NULL | Finance |
| Join type | Rows returned |
|---|---|
| INNER JOIN | Only matching rows |
| LEFT JOIN | All left rows, plus matches |
| RIGHT JOIN | All right rows, plus matches |
| FULL OUTER JOIN | All rows from both sides |
| CROSS JOIN | Every combination |
5. CROSS JOIN
CROSS JOIN has no ON clause: every row is paired with every row. Six employees times four departments gives 24 rows. It is useful for generating combinations (for example every product with every size), and it is also what you get by accident when you forget the match condition.
SELECT e.FirstName, d.DeptName
FROM Employees e
CROSS JOIN Departments d;
The first rows are Amina with Sales, IT, HR and Finance, then Youssef with the same four departments, and so on.
6. Joining three tables
Add one more JOIN for each extra table. Here we show each project with the employee and the department:
SELECT p.ProjectName, e.FirstName, d.DeptName
FROM Projects p
INNER JOIN Employees e ON p.EmpId = e.Id
INNER JOIN Departments d ON e.DeptId = d.DeptId;
| ProjectName | FirstName | DeptName |
|---|---|---|
| Website Redesign | Youssef | IT |
| Network Upgrade | Nadia | IT |
| Payroll Audit | Amina | Sales |
| Migration to Azure | Youssef | IT |
7. Self join
A table can be joined to itself. Employees has a ManagerId that points to another row of the same table. Use two aliases, one for the employee and one for the manager:
SELECT e.FirstName AS Employee, m.FirstName AS Manager
FROM Employees e
INNER JOIN Employees m
ON e.ManagerId = m.Id;
| Employee | Manager |
|---|---|
| Salma | Amina |
| Nadia | Youssef |
| Omar | Youssef |
Use LEFT JOIN instead to keep the employees who have no manager (Amina, Youssef and Karim would show NULL).
8. JOIN with GROUP BY
Joins combine nicely with aggregates. To count employees per department, including departments with nobody, use a LEFT JOIN and count a column from the right table:
SELECT d.DeptName, COUNT(e.Id) AS EmployeeCount
FROM Departments d
LEFT JOIN Employees e ON e.DeptId = d.DeptId
GROUP BY d.DeptName;
| DeptName | EmployeeCount |
|---|---|
| Finance | 0 |
| HR | 1 |
| IT | 2 |
| Sales | 2 |
COUNT(e.Id) ignores NULLs, so Finance correctly shows 0. COUNT(*) would wrongly show 1. Lesson 3 explains GROUP BY in detail.
9. Common mistakes and best practices
- Forgetting the
ONclause or joining on the wrong columns: the result explodes into thousands of rows. - Using INNER JOIN when you need to keep unmatched rows, so rows silently disappear. Check the row count.
- Putting a filter on the right table in
WHEREafter a LEFT JOIN, which turns it back into an inner join. Put that filter in theONclause instead. - Not using aliases or qualifying columns, which causes ambiguous column errors.
- Best practice: join on indexed key columns (see SQL Server Indexes Explained: Clustered, Nonclustered and Covering), and always give tables short, meaningful aliases.
10. Practice
- Show every employee with the name of their department, keeping employees with no department.
- List the departments that have no employees.
- Show each project with the name of the employee who works on it.
Answers: the first is the LEFT JOIN in section 3 (6 rows, Omar has NULL). The second is the IS NULL query in section 3 and returns Finance. The third is SELECT p.ProjectName, e.FirstName FROM Projects p INNER JOIN Employees e ON p.EmpId = e.Id;, which returns four rows.
Frequently asked questions
What is the difference between INNER JOIN and LEFT JOIN?
INNER JOIN returns only rows that match on both sides. LEFT JOIN returns every row of the left table and fills the right side with NULL when nothing matches.
Is JOIN the same as INNER JOIN?
Yes. Writing JOIN alone means INNER JOIN in SQL Server. Writing INNER explicitly makes the intent clearer.
Why did my LEFT JOIN lose rows?
Usually a WHERE condition on the right table removed the NULL rows. Move that condition into the ON clause.
What to learn next
Next, summarise data with aggregates and write queries inside queries in Lesson 3: GROUP BY, HAVING and Subqueries. Previous lesson: Lesson 1: SELECT, WHERE and ORDER BY.
The whole series
- Lesson 1: SELECT, WHERE and ORDER BY
- Lesson 2: JOINs (this article)
- Lesson 3: GROUP BY, HAVING and Subqueries
- Lesson 4: INSERT, UPDATE, DELETE and Transactions
- Lesson 5: CREATE TABLE, Data Types and Constraints
- Lesson 6: Indexes, Views and Stored Procedures
- Lesson 7: CTEs and Window Functions
- Lesson 8: Built-in Functions
- Lesson 9: Functions, Temp Tables and Table Variables
- Lesson 10: Triggers and Audit Tables
- Lesson 11: Security: Logins, Users and Roles
- Lesson 12: Backup, Restore and Recovery Models
- Lesson 13: Query Performance Tuning
- Lesson 14: SQL Server Agent Jobs and Maintenance
- Lesson 15: Encryption and Auditing Basics
- Lesson 16: Working with JSON
- Lesson 17: Temporal Tables and Row History
- Lesson 18: Partitioning and Large Tables
- lesson 19: Full Text Search
- lesson 20: Query Store and Slow Queries
Sources and further reading
- Microsoft Learn, Transact-SQL reference (Database Engine), on learn.microsoft.com: the official syntax for every statement used here.
- Microsoft Learn, SQL Server documentation, for SQL Server Management Studio (SSMS) and the sample concepts.
More tutorials like this
Msg 208 Invalid Object Name in SQL Server: Causes and Fix
Fix SQL Server Msg 208 Invalid object name: check the spelling, the database and the schema, with real SSMS examples and scripts to find…
SQL Server Query Store Tutorial: Find Slow Queries, Compare Plans and Force a Plan
Turn on Query Store, find the most expensive queries with the sys.query_store views and the SSMS reports, compare the plans of one query and…
SQL Server Full Text Search Tutorial: CONTAINS, FORMSOF and CONTAINSTABLE
Search words inside text columns fast: create a full text catalog and index, use CONTAINS, word forms, phrases and rank the best matches with…
