Relationship Design and Database Constraints

Model user relationships with a junction table and prevent duplicate or invalid associations

🎯 Introduction

By the end of this article, you will be able to model user relationships with a junction table and prevent duplicate or invalid associations.


🧱 Decide where information belongs

Store the author ID in each article and the name in the user table. When an author changes their name, update only the user table; article queries retrieve the new name through the ID. Splitting tables this way reduces inconsistent copies of the same information.

One user can write many articles: a one-to-many relationship. A user can join multiple groups, and a group can have multiple users: a many-to-many relationship. A many-to-many relationship needs a table recording who joined which group, rather than a string of user IDs in a text column.


👥 Create the group table first

This article uses user 1 in blog_demo.user, showing only the columns needed for this relationship:

idusername
1Xiao Ming

Other users and columns do not affect this example. Next, create the groups:

CREATE TABLE study_group (
    id INT PRIMARY KEY,
    name VARCHAR(50) NOT NULL
);

Insert two groups:

INSERT INTO study_group VALUES (1, 'SQL Study Group'), (2, 'Node Study Group');

study_group now contains these two groups:

idname
1SQL Study Group
2Node Study Group

🔗 Each junction-table row represents a membership

CREATE TABLE group_member (
    group_id INT NOT NULL,
    user_id INT NOT NULL,
    joined_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (group_id, user_id)
);

The two columns form a composite primary key: a user can join multiple groups, but the same “group + user” pair cannot appear twice. joined_at belongs to the membership, so it is stored in the junction table.

Add a member:

INSERT INTO group_member (group_id, user_id) VALUES (1, 1);

This adds the following record to group_member, showing only its two ID columns:

group_iduser_id
11

This row means “Xiao Ming joined SQL Study Group”: group_id 1 identifies SQL Study Group in the group table, and user_id 1 identifies Xiao Ming in the user table.

Repeating the statement produces a duplicate key error instead of a duplicate relationship. The database rejects duplicate pairs even when two requests arrive concurrently; an application-side check alone is insufficient.


🛡 Foreign keys prevent references to nonexistent data

The group table contains only IDs 1 and 2. A membership saying “user 1 joined group 999” would be invalid because group 999 does not exist.

A foreign key is a rule that makes the database check this relationship: a group ID written to the membership table must exist in the group table. Naming a column group_id does not enable this check automatically; add a foreign key explicitly.

Require memberships to reference existing groups

ALTER TABLE group_member ADD CONSTRAINT fk_member_group
    FOREIGN KEY (group_id) REFERENCES study_group(id);

This adds a rule named fk_member_group to group_member, checking that its group_id appears in the id column of study_group.

Column being writtenReferenced columnAllowed IDs in this example
group_member.group_idstudy_group.id1, 2

FOREIGN KEY specifies the column to check, and REFERENCES specifies the table and column supplying valid IDs. fk_member_group is simply the rule's name, making it identifiable in errors or when modifying constraints.

Try joining a nonexistent group

INSERT INTO group_member (group_id, user_id) VALUES (999, 1);

MySQL reports a foreign key constraint error, typically with error code 1452. The record is not inserted; the membership table still contains only the original record:

group_iduser_id
11

Because study_group.id does not contain 999, the database refuses to store the membership in group 999.

Joining an existing group succeeds

INSERT INTO group_member (group_id, user_id) VALUES (2, 1);

Group 2 exists and this pair of IDs is not a duplicate, so the insertion succeeds. The membership table becomes:

group_iduser_id
11
21

Xiao Ming now belongs to two groups. The composite primary key checks for duplicate memberships; the foreign key checks whether the group exists. The rules address different problems.

Check the user ID separately too

So far, only the group has been checked. Another foreign key is needed to prevent a nonexistent user from becoming a member:

ALTER TABLE group_member ADD CONSTRAINT fk_member_user
    FOREIGN KEY (user_id) REFERENCES user(id);

This checks group_member.user_id, requiring a matching user.id. For example, this course has no user 999, so a membership with group 1 and user 999 is rejected. An existing group does not imply an existing user; check the columns separately.

When adding a foreign key, the database also checks existing records. Correct any previously stored references to nonexistent groups or users first. Both sides use INT here to keep the types consistent.


🗑 Decide what deletion should preserve

This example does not enable cascading deletion. Deleting group 1 while it still has membership records is rejected by the foreign key, preventing references to a nonexistent group.

To remove the group, delete its memberships first, then the group, placing both steps in a transaction as covered next. If deleting a parent should automatically remove all its relationships, choose ON DELETE CASCADE when designing the foreign key, after confirming that the related data should also disappear.

To hide a group temporarily, add a status column and filter it in queries. This is called soft deletion or deactivation. It preserves the data, but every relevant query must apply the filter, and existing unique constraints still apply.


🧭 Decide when duplicated values are useful

Read current information through relationships to avoid copying it. To preserve history, such as the nickname displayed when a user performed an action, store that value in the action record and make clear that later name changes will not update it.

Decide whether you need the current value or the value at the time before duplicating data. Do not copy every column merely to avoid a JOIN.


❓ Questions and Answers

Q1: Must every table be related to another table?

No. Add relationships when the application requires them. Independent records such as logs do not need to be linked to every table.

Q2: Does a foreign key automatically return user details?

No. Foreign keys enforce data validity. Reading related data still requires a JOIN or another query.

Q3: Do I need a foreign key if the application already checks that the user exists?

They serve different purposes. The application provides a helpful message; the foreign key also prevents invalid relationships caused by concurrent deletion or direct writes from other programs.


🧪 Exercise

Try adding user 999 to group 1 and confirm that the user foreign key rejects it. Then try adding user 1 to group 1 again and compare the errors. Before starting, confirm that the user table has no record with ID 999.

-- Write your SQL or record your verification results here