Relationships

Updated · 7 min read
mediumPostgreSQL 18sqlrelationshipsone-to-manymany-to-manycardinalityer-diagram

A relationship in SQL is a connection between two tables, stored as a foreign key, that says how many rows on one side can relate to how many on the other. It is used to describe facts such as "a student has many payments" or "a course has many students", and the database enforces it with keys and constraints. There are three kinds: one-to-one, one-to-many and many-to-many, and each side can be optional or required. In this lesson, we will learn each kind with Fee Tracker examples, how to make a relationship optional or required, and how to read crow's foot symbols in an ER diagram.

In One Minute

  • One-to-many: a foreign key in the "many" table. A student has many payments.
  • One-to-one: a foreign key that is also unique (often the primary key). A student has one profile.
  • Many-to-many: a junction table with two foreign keys. Students and courses, through enrollments.
  • Required or optional: a NOT NULL foreign key is required; a nullable one is optional.
  • Crow's foot: bar = one, circle = zero, crow's foot = many.

Types of Relationship

TypeExampleHow it's stored
One-to-manyStudent to paymentspayments.student_id references students
One-to-oneStudent to profilestudent_profiles.student_id is the primary key and references students
Many-to-manyStudents and coursesenrollments (student_id, course_id)

One Parent, Many Children

The most common relationship: one row on one side, any number on the other. The foreign key always goes in the "many" table. Each payment belongs to one student; a student can have many payments, or none:

SQL▶ Try it
SELECT s.first_name, count(p.payment_id) AS payments
FROM students AS s
LEFT JOIN payments AS p USING (student_id)
GROUP BY s.student_id, s.first_name
ORDER BY s.student_id;
Output
 first_name | payments
------------+----------
 Srihitha   |        5
 Advitha    |        0
 Navika     |        2
(3 rows)

Explanation: Srihitha has five payments, Navika two, Advitha none. "Many" includes zero, which is why the LEFT JOIN keeps Advitha.

One Row on Each Side

A one-to-one relationship is a foreign key that is also unique, so each row on one side matches at most one on the other. It's used to split rarely used or sensitive columns into their own table. A student profile with an optional biography:

SQL▶ Try it
CREATE TABLE student_profiles (
  student_id        INTEGER PRIMARY KEY REFERENCES students (student_id),
  bio               TEXT,
  favorite_language TEXT
);
 
INSERT INTO student_profiles VALUES (103, 'Loves puzzles', 'JavaScript');
INSERT INTO student_profiles VALUES (103, 'A second profile', 'Java');
Output
CREATE TABLE
 
INSERT 0 1
 
ERROR:  duplicate key value violates unique constraint "student_profiles_pkey"
DETAIL:  Key (student_id)=(103) already exists.

Explanation: student_id is both the primary key and a foreign key. The foreign key makes each profile belong to a real student; the primary key allows only one profile per student, so the second insert is refused.

A profile per student, many payments per student, and students to courses through enrollments

Many on Both Sides

Many-to-many needs a junction table, as Data Modeling showed. Counting from the course side:

SQL▶ Try it
SELECT c.title, count(e.student_id) AS students
FROM courses AS c
LEFT JOIN enrollments AS e USING (course_id)
GROUP BY c.course_id, c.title
ORDER BY c.course_id;
Output
       title       | students
-------------------+----------
 Java Basics       |        2
 Java OOP          |        1
 Java Collections  |        1
 SQL Basics        |        2
 JavaScript Basics |        1
 Git Basics        |        0
(6 rows)

Explanation: Java Basics and SQL Basics have two students each; Git Basics has none. A student's courses and a course's students are both read from the same enrollments rows. A many-to-many relationship is really two one-to-many relationships meeting in the junction table.

Required or Optional

A NOT NULL foreign key makes the relationship required; a nullable one makes it optional.

Fee Tracker columnNullable?Reading
payments.student_idNoEvery payment must have a student
students.mentor_idYesA student may have a mentor
courses.prerequisite_idYesA course may require another

The "many" side's minimum is controlled differently: nothing forces a student to have a payment, so "zero or many" is the default, and "at least one" would need application logic or a trigger.

Reading Crow's Foot Symbols

Each end of a relationship line carries two marks: the inner one is the maximum, the outer one the minimum.

Line endReading
Bar and barExactly one
Circle and barZero or one
Bar and crow's footOne or many
Circle and crow's footZero or many
Exactly one, zero or one, one or many, and zero or many, drawn with bars, circles and crow's feet

The line between students and payments reads both ways: at the students end, "exactly one" (every payment has one student); at the payments end, "zero or many" (a student has any number of payments).

Where the Foreign Key Goes

Common Mistakes

The foreign key on the wrong side. students.payment_id can hold only one payment. Put student_id in payments.

One-to-one without UNIQUE. Without it, the second profile is accepted and the relationship becomes one-to-many.

Many-to-many with a list column. Use a junction table.

Required links left nullable. A payment with no student is meaningless; make student_id NOT NULL.

Interview Corner

What are the three types of relationship?

One-to-one, one-to-many and many-to-many. One-to-many uses a foreign key on the many side; one-to-one adds a unique constraint to it; many-to-many uses a junction table.

How do you enforce a one-to-one relationship?

Make the foreign key unique, usually by making it the child table's primary key, so each parent row can match at most one child row.

What does "zero or many" mean in crow's foot notation?

A circle and a crow's foot at the line end: the related table may have no rows or any number of rows for each row on the other side.

Practice

Challenge: Which relationship does students.mentor_id represent? Show each mentor's name and how many students they mentor, including those who mentor nobody, sorted by student_id.

Show solution
SQL▶ Try it
SELECT m.first_name AS mentor, count(s.student_id) AS mentees
FROM students AS m
LEFT JOIN students AS s ON s.mentor_id = m.student_id
GROUP BY m.student_id, m.first_name
ORDER BY m.student_id;
Output
  mentor  | mentees
----------+---------
 Srihitha |       1
 Advitha  |       1
 Navika   |       0
(3 rows)

It's a one-to-many relationship from a table to itself: a mentor can have many mentees (here, at most one each), and each student has zero or one mentor, because mentor_id is nullable.

Quick check: Relationships

3 questions
1A student has many payments. Which table holds the foreign key?
2How is a one-to-one relationship enforced?
3mentor_id is nullable. What does that make the relationship?

Key Takeaways

RelationshipStore it as
One-to-manychild.parent_id REFERENCES parent
One-to-onechild.parent_id PRIMARY KEY REFERENCES parent
Many-to-manyjunction (a_id, b_id) with two foreign keys
Requiredadd NOT NULL to the foreign key

Was this tutorial helpful?

Lesson 71 of 115