SQL INNER JOIN — Return Only Matching Rows
Learn how SQL INNER JOIN works by returning only rows with matching values in both tables. Includes Venn diagram, syntax, and practical examples.
Detailed Explanation
What Is an INNER JOIN?
An INNER JOIN is the most common type of SQL join. It returns only the rows where the join condition is satisfied in both tables. If a row in the left table has no matching row in the right table, it is excluded from the result entirely — and vice versa.
Syntax
SELECT a.*, b.*
FROM employees AS a
INNER JOIN departments AS b
ON a.department_id = b.id;
How It Works Step by Step
- The database engine takes each row from
employees(the left table). - For each row, it searches
departments(the right table) for rows whereb.idmatchesa.department_id. - When a match is found, the columns from both tables are combined into a single result row.
- If no match is found, that employee row is skipped — it does not appear in the output.
Venn Diagram Interpretation
In the classic Venn diagram, INNER JOIN corresponds to the intersection — the overlapping region where both circles meet. Only data that exists in both tables (based on the join key) is included.
Performance Characteristics
INNER JOIN is typically the most performant join type because the database can skip non-matching rows early. Adding an index on the join columns (department_id and id) allows the engine to use index lookups instead of full table scans.
Common Pitfall
If either join column contains NULL values, those rows will never match because NULL = NULL evaluates to NULL (not TRUE) in SQL. Use IS NOT DISTINCT FROM or COALESCE if you need NULL-safe equality.
Use Case
Use INNER JOIN when you need data that is guaranteed to exist in both tables — for example, fetching employee details along with their department names, where every employee must belong to a valid department.
Try It — SQL JOIN Visualizer
Related Topics
SQL LEFT JOIN — Keep All Rows from the Left Table
JOIN Types
SQL RIGHT JOIN — Keep All Rows from the Right Table
JOIN Types
SQL FULL OUTER JOIN — Return All Rows from Both Tables
JOIN Types
SQL JOIN on Multiple Columns — Composite Join Conditions
Practical Examples
SQL JOIN NULL Handling — Avoiding Unexpected Results
Common Mistakes