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
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.
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.
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
BEGIN TRANSACTION;
- 1Close and insert customer versions
- 2Upsert orders, sales, payments
- 3Insert batch ledger row
- 4Advance watermark
COMMIT: batch published
Committed watermark
Moves forward only after COMMIT.