JOIN
In SQL, a JOIN combines rows from two tables based on a rule you specify. The join type determines what happens to rows that have no match.
Also known as: джойн, LEFT JOIN, INNER JOIN
What a JOIN does
Suppose you have one table of employees and another of departments. Each employee record stores a department ID, not a copy of the department’s name. A JOIN lets you show employee names alongside department names in a single query without changing either table. You can also join a table to itself: for example, join employees to another copy of the employee table to look up each employee’s manager.
Which rows make it into the result?
The ON clause tells SQL which pairs qualify as matches. It often compares a foreign key with a primary key, but a declared foreign key is not required. For each pair where the condition is true, the join produces a row.
INNER JOIN, also writtenJOIN, returns only matching pairs.LEFT JOINreturns the matching pairs and keeps every unmatched row from the left input, filling in the right-side columns withNULL.RIGHT JOINkeeps unmatched rows from the right input.FULL OUTER JOINkeeps unmatched rows from both inputs.CROSS JOINpairs every row on the left with every row on the right. Three rows crossed with four produce twelve pairs before filtering.
Example: Include departments with no active employees
SELECT d.name, COUNT(e.id) AS active_employees
FROM departments AS d
LEFT JOIN employees AS e
ON e.department_id = d.id
AND e.status = 'active'
GROUP BY d.id, d.name;
This query returns one row per department, even if a department has no employees or all of its employees are inactive. Before grouping, a department with three active employees has three joined rows. One with no active employees has a single joined row with NULL in the employee columns. COUNT(e.id) counts only non-NULL IDs. Since e.id is the employee primary key, that gives zero when there is no match. COUNT(*) would count the unmatched row and give one instead.
Common mistakes and interview questions
Moving e.status = 'active' into a WHERE clause changes the result. In ON, it controls which employee rows match. In WHERE, it filters rows after the join, so departments with no active employees disappear: the filter keeps neither unmatched rows nor rows matched to inactive employees.
Interviewers often ask you to predict the output when a join key appears more than once. If two rows on one side and three on the other share a key, an equality join produces six matching pairs for that key. Before adding DISTINCT, check what one output row should represent and whether the join condition uses all the columns needed to identify a match.
If the question is about performance, distinguish the SQL join type from the execution strategy. LEFT JOIN says which rows must be kept; the query plan shows how the database does the work, for example with a hash join or a nested-loop join.