Let’s Get Certified
Module 02 / 04 · Read and combine rows

Keep the right rows in a join

Relate tickets to owners and preserve owners who have no open work.

Which teams have open tickets?

Use the team and ticket tables from Filter and sort a result. Decide what one output row means before writing the query. Here each row is an open ticket paired with its team, plus a placeholder row for any team without open work.

SELECT g.name, t.id
FROM team AS g
LEFT JOIN ticket AS t
  ON t.team_id = g.id AND t.state = 'open'
ORDER BY g.id, t.id;

Expect (North, 11), (North, 12), (South, NULL), and (West, NULL). South owns a closed ticket. West owns no ticket. Neither has a matching open ticket, so the left join preserves both teams with null ticket columns.

Change one condition

Move the state filter into a WHERE clause. North still contributes two rows. The placeholders cannot satisfy the filter and both other teams disappear. An inner join is appropriate if the report asks only for teams with matches.

Check for accidental multiplication

Join on the unique team ID and its foreign key. Adding another one-to-many relation, such as ticket comments, can repeat ticket rows. Count the rows per ticket after the join before using the result to total hours.

SQLite join processing

Knowledge check

Keep the right rows in a join quiz

Answer 3 questions. Check each answer for an explanation.