JOIN: connect multiple tables
Connect tables through primary and foreign keys.
Intermediate
SQL syntax
Finance and accounting scenario
Related exercises
Objective
Connect data distributed across several tables to build coherent information.
Exercise context
An invoice alone is not always enough. Joins retrieve the related customer, payments or products sold.
Key concepts
- JOIN connects two tables using a shared key.
- A primary key uniquely identifies a row.
- A foreign key references the primary key of another table.
- Aliases such as c, f or r make queries easier to read.
- An incorrect join can artificially multiply rows.
Syntax pattern
SELECT a.colonne, b.colonne
FROM table_a a
JOIN table_b b ON a.cle = b.cle;
Applied example
SELECT c.nom_client, f.id_facture, f.montant_ttc
FROM clients c
JOIN factures f ON c.id_client = f.id_client;
Common mistakes
- Forgetting the ON condition.
- Joining columns that do not correspond.
- Not using aliases in long queries.
- Confusing INNER JOIN and LEFT JOIN.