| Lesson 3 | Entity Identifiers |
| Objective | Explain the purpose of entity identifiers and how they support relationships and integrity. |
UNIQUE/CHECK constraints prevent orphan records and broken links.NOT NULL and UNIQUE/PRIMARY KEY.CustomerID) and enforce the natural business rule with a UNIQUE constraint.UNIQUE.When two entities have a many-to-many (M:N) relationship (e.g., Students ↔ Courses), introduce an associative (bridge/junction) entity to break it into two 1:M relationships. The associative table’s identifier can be modeled in two common ways:
Pattern A - Composite Primary Key (compact and natural):
CREATE TABLE Enrollment (
StudentID INT NOT NULL,
CourseID INT NOT NULL,
EnrolledOn DATE NOT NULL,
PRIMARY KEY (StudentID, CourseID),
FOREIGN KEY (StudentID) REFERENCES Students(StudentID),
FOREIGN KEY (CourseID) REFERENCES Courses(CourseID)
);
Pattern B - Surrogate PK plus Business Uniqueness (flexible for additional relationships/attributes):
CREATE TABLE Enrollment (
EnrollmentID BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
StudentID INT NOT NULL,
CourseID INT NOT NULL,
EnrolledOn DATE NOT NULL,
UNIQUE (StudentID, CourseID),
FOREIGN KEY (StudentID) REFERENCES Students(StudentID),
FOREIGN KEY (CourseID) REFERENCES Courses(CourseID)
);
Note: An associative entity does have an identifier-either the composite of its FKs (Pattern A) or a surrogate PK with a UNIQUE constraint on the FK pair (Pattern B). Choose based on stability, simplicity, and query needs.
Each customer must be uniquely identifiable-by a surrogate CustomerID or a stable natural key. All other columns describe the customer but do not uniquely identify them.
UNIQUE to preserve business rules even when using surrogate PKs.