Skip to main content
Beginnerconceptual

Is a many-to-many relationship directly feasible between two relational tables? If not, how do you model it?

ReportedSource: GeeksforGeeks interview experience: Snowflake on-campus 2020

Quick answer

Not directly; add a junction table holding both foreign keys (composite PK) plus relationship attributes, turning it into two one-to-many relationships.

Not directly. A row holds one value per column, so students cannot hold a list of courses and courses cannot hold a list of students without breaking first normal form (comma-separated ids are a known anti-pattern: no foreign keys, no indexing, painful queries).

Use a junction (bridge / associative) table.

query.sql
CREATE TABLE enrolments (
  student_id INT REFERENCES students(student_id),
  course_id  INT REFERENCES courses(course_id),
  enrolled_on DATE,
  grade CHAR(2),
  PRIMARY KEY (student_id, course_id)
);

The many-to-many becomes two one-to-many relationships. The composite primary key prevents duplicate pairs, and the junction table is the natural home for attributes of the relationship (enrolment date, grade).

Querying.

query.sql
SELECT s.name, c.title
FROM students s
JOIN enrolments e ON e.student_id = s.student_id
JOIN courses c    ON c.course_id  = e.course_id;

Warehouse note. In dimensional models the same idea appears as a bridge table (e.g. accounts with multiple holders); be careful with weighting so measures are not double-counted.

See the concept: Atomic publication

Atomic publication

BEGIN TRANSACTION;

  1. 1Close and insert customer versions
  2. 2Upsert orders, sales, payments
  3. 3Insert batch ledger row
  4. 4Advance watermark

COMMIT: batch published

Committed watermark

Moves forward only after COMMIT.

Everything inside BEGIN…COMMIT lands together or not at all. A failure leaves the old facts and the old watermark untouched.

Discussion