| Lesson 4 | Entity Identifier Rules |
| Objective | List two rules for creating entity identifiers. |
PRIMARY KEY and NOT NULL.Prefer surrogate keys (e.g., CustomerID integer or UUID) when natural candidates are volatile, bulky, regional, or sensitive. If a truly stable natural key exists (e.g., an authoritative code with governance), you may use it, but still document/enforce its uniqueness.
-- Surrogate key as PK; preserve business rule with UNIQUE
CREATE TABLE Customers (
CustomerID BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
FullName VARCHAR(200) NOT NULL,
Email VARCHAR(255) NOT NULL,
-- Natural rule: no two customers share the same email
CONSTRAINT uk_customers_email UNIQUE (Email)
);
Many-to-many (M:N) relationships require an associative (bridge/junction) entity. It does have an identifier-either a composite of its foreign keys or its own surrogate key plus a uniqueness rule:
Composite PK (compact, 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)
);
Surrogate PK (flexible for extra 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,
CONSTRAINT uk_enrollment UNIQUE (StudentID, CourseID),
FOREIGN KEY (StudentID) REFERENCES Students(StudentID),
FOREIGN KEY (CourseID) REFERENCES Courses(CourseID)
);
Choose based on stability, indexing needs, and how often you reference the row directly.
Column names should be meaningful and consistent (CustomerID, OrderID). The values stored in identifiers should be meaningless and unrestricted. This resolves the common confusion between readable schema names and opaque key values.