SQL Server JOINs for Beginners
Real applications usually store related information in separate tables. A JOIN lets you combine rows from those tables using a related column.
Example Tables
Employees
---------
EmployeeID | EmployeeName | DepartmentID
1 | Anita | 10
2 | Rahul | 20
Departments
-----------
DepartmentID | DepartmentName
10 | IT
20 | Finance
INNER JOIN
SELECT e.EmployeeName,
d.DepartmentName
FROM Employees AS e
INNER JOIN Departments AS d
ON e.DepartmentID = d.DepartmentID;
INNER JOIN returns rows where the join condition matches in both tables.
LEFT JOIN
SELECT e.EmployeeName,
d.DepartmentName
FROM Employees AS e
LEFT JOIN Departments AS d
ON e.DepartmentID = d.DepartmentID;
LEFT JOIN keeps every row from the left table. If there is no matching department, the department columns are returned as NULL.
JOIN with a Filter
SELECT e.EmployeeName,
d.DepartmentName
FROM Employees AS e
INNER JOIN Departments AS d
ON e.DepartmentID = d.DepartmentID
WHERE d.DepartmentName = 'IT';
Why Aliases Help
Aliases such as e and d make queries shorter and clearer, especially when several tables are involved.
Common Beginner Mistakes
- Joining on unrelated columns.
- Forgetting the
ONcondition. - Using
INNER JOINwhen unmatched left-side rows must be retained. - Getting duplicate rows because the join relationship is one-to-many.
What to Learn Next
After JOINs, learn aggregate functions, GROUP BY, and HAVING to build summaries and reports.
Continue with the SQL Server Tutorials hub.
đŦ Comments
Sign in with Google to publish immediately, or comment anonymously and wait for approval.
Loading comments...