Understanding SQL JOINs and Database Relationships
Learn how one-to-one, one-to-many, and many-to-many relationships shape SQL JOIN results, including bridge tables and duplicate rows.
SQL JOIN result shapes follow table cardinality. This guide explains one-to-one, one-to-many, and many-to-many relationships with a bridge-table example, then links to a companion guide for join types, aggregation, and query planning.
Understanding SQL JOINs and Database Relationships
A JOIN combines rows from related tables. How many rows appear depends on the relationship between those tables: one-to-one, one-to-many, or many-to-many. This guide focuses on cardinality and result shape, with a bridge-table example for many-to-many relationships.
For join types, outer-join filter placement, aggregation, and query planning, continue to Joins and Aggregations: SQL Patterns for Data Analysis.
Cardinality at a Glance
| Relationship | Typical schema | Result shape |
|---|---|---|
| One-to-one | A unique key on each side | Each row matches at most one row on the other side. |
| One-to-many | A parent key referenced by multiple child rows | The parent values repeat once per matching child. |
| Many-to-many | A bridge table with a foreign key to each entity | Each bridge row represents one association and produces a joined row. |
The schema constraints matter. A foreign key says that a referenced row must exist when the key is present; it does not make the referencing column unique. A UNIQUE constraint on that column is what limits the relationship to one matching row.
One-to-One
A user profile is often modeled separately from a user record. If each profile has a unique user_id that references users, a user can match at most one profile. Some users may have no profile, depending on the application rules.
SELECT u.user_id, u.username, p.bio
FROM users AS u
LEFT JOIN user_profiles AS p
ON p.user_id = u.user_id;
If user_profiles.user_id is unique, a left join returns one row per user. Users without a profile have NULL in the bio column. An inner join would return only users that have a profile.
To require every user to have a profile, the schema or application must enforce that rule as well. A unique foreign key prevents multiple profiles for one user; it does not require a profile row to exist for every user.
One-to-Many
Customers and orders are a common one-to-many relationship. Each order references one customer, while a customer can have several orders.
SELECT c.customer_id, c.customer_name, o.order_id
FROM customers AS c
LEFT JOIN orders AS o
ON o.customer_id = c.customer_id
ORDER BY c.customer_id, o.order_id;
Suppose Alice has orders 101 and 102, while Bob has none. The result shape is:
| customer_id | customer_name | order_id |
|---|---|---|
| 1 | Alice | 101 |
| 1 | Alice | 102 |
| 2 | Bob | NULL |
Alice appears twice because the join returns one row per matching order. Bob still appears because the query uses a left join, with NULL for the missing order. Repeated customer columns are part of the result shape; they do not mean the source customer row was duplicated.
This matters when adding another one-to-many table. Joining orders to order_items returns one row per order item, so customer and order columns repeat for each item. The output describes combinations of related records, not one row per customer or per order.
Many-to-Many and Bridge Tables
Students can enroll in several courses, and each course can have several students. A bridge table stores one row per association and can hold attributes of that relationship. This example uses common relational SQL syntax; adapt type names or foreign-key settings to the database in use.
CREATE TABLE students (
student_id INTEGER PRIMARY KEY,
student_name VARCHAR(50) NOT NULL
);
CREATE TABLE courses (
course_id INTEGER PRIMARY KEY,
course_title VARCHAR(50) NOT NULL
);
CREATE TABLE enrollments (
student_id INTEGER NOT NULL,
course_id INTEGER NOT NULL,
PRIMARY KEY (student_id, course_id),
FOREIGN KEY (student_id) REFERENCES students (student_id),
FOREIGN KEY (course_id) REFERENCES courses (course_id)
);
INSERT INTO students (student_id, student_name) VALUES
(1, 'Ava'),
(2, 'Ben');
INSERT INTO courses (course_id, course_title) VALUES
(10, 'Algebra'),
(11, 'Databases');
INSERT INTO enrollments (student_id, course_id) VALUES
(1, 10),
(1, 11),
(2, 10);
SELECT s.student_id, s.student_name, c.course_id, c.course_title
FROM students AS s
JOIN enrollments AS e
ON e.student_id = s.student_id
JOIN courses AS c
ON c.course_id = e.course_id
ORDER BY e.student_id, e.course_id;
The query returns one row per enrollment:
| student_id | student_name | course_id | course_title |
|---|---|---|---|
| 1 | Ava | 10 | Algebra |
| 1 | Ava | 11 | Databases |
| 2 | Ben | 10 | Algebra |
The composite primary key prevents duplicate student-course pairs. If the system tracks repeated attempts or enrollment history, include that distinguishing information in the key instead. An inner join through the bridge returns recorded associations; students with no enrollments or courses with no students do not appear. SQLite accepts this schema syntax, but foreign-key enforcement must be enabled separately.
Self-Referential Relationships
A manager relationship can be stored in an employees table: manager_id references another employee’s employee_id. This is a one-to-many relationship within one table, because one manager may have several direct reports.
SELECT
employee.employee_id,
employee.employee_name,
manager.employee_name AS manager_name
FROM employees AS employee
LEFT JOIN employees AS manager
ON employee.manager_id = manager.employee_id;
The aliases refer to two roles played by rows in the same table. A left join keeps employees who do not have a manager, such as the top-level manager.
Questions to Ask Before Joining
- Which key identifies a row on each side?
- Is that key unique, or can it match multiple rows?
- Should rows without a match remain in the result?
- Does a bridge table represent the relationship, and does it carry attributes of its own?
- Is the result meant to have one row per entity or one row per relationship?
Constraints describe what the database enforces. If the schema does not enforce uniqueness or referential integrity, inspect the data before relying on the assumed cardinality. A JOIN follows the rows and predicates it is given.
Further Reading
- Joins and Aggregations: SQL Patterns for Data Analysis — Join types, outer-join filter placement, aggregation, and query planning.
- PostgreSQL table expressions — JOIN syntax and semantics.
- PostgreSQL constraints — Primary keys, foreign keys, and uniqueness.
Category
Related Posts
Database Indexes: B-Tree, Hash, Covering, and Beyond
A practical guide to database indexes. Learn when to use B-tree, hash, composite, and partial indexes, understand index maintenance overhead, and avoid common performance traps.
Database Normalization: From 1NF to BCNF
Learn database normalization from 1NF through BCNF. Understand how normalization eliminates redundancy, prevents update anomalies, and when denormalization makes sense for performance.
Primary and Foreign Keys: A Practical Guide
Learn the difference between natural and surrogate keys, how foreign keys enforce referential integrity, cascade rules, and best practices for constraint naming.