How do I join two tables using more than one matching column?
Quick answer
Add both matching conditions to the JOIN’s ON clause and connect them with AND. For example, ON e.course = o.course AND e.term = o.term matches an enrollment only to the offering with the same course and term. Matching on course alone can pair a record with offerings from other terms. The examples below use invented data and SQLite syntax.
The question, the details, the next step.
A practical checklist
Write down which columns together identify the intended match.
Include one comparison for each matching column in the
ONclause, joined withAND.Test a case where the first column matches but another differs.
Review sample result rows for cross-term or otherwise unintended pairings.
Confirm whether your real data requires additional matching columns.
A few more useful answers
Does `AND` mean either condition can match?
No. In this join pattern, both comparisons must be true for the pair to match. SQLite also documents USING with multiple shared columns as requiring all listed comparisons to be true. [S1]
Is `USING (course, term)` interchangeable with the example’s `ON` clause?
For SQLite, the documented USING form can compare multiple shared column names, and all listed comparisons must be true. The source does not establish syntax or behavior for every other database system. [S1]
Does joining on both columns guarantee one result per enrollment?
Not by itself. The example demonstrates matching conditions, but the source does not establish uniqueness in your tables; check whether the matching pair occurs more than once.
Sources
References used for this guide.
- [S1] SQLite SELECT: join conditions and matching rows sqlite.org · Checked
