What is the difference between a primary key, a unique key and a composite key?
ReportedSource: GeeksforGeeks interview experience: Amazon Data Engineer
Primary key: one per table, unique + NOT NULL row identifier. Unique key: several allowed, unique, may allow NULLs. Composite key: a key made of multiple columns (can be primary or unique).
Primary key. The column(s) that identify each row. Values must be unique and NOT NULL, and a table has exactly one primary key. Most engines build a unique index on it, and foreign keys usually reference it.
Unique key (unique constraint). Also enforces uniqueness, but a table can have several, and they can allow NULL (in most databases multiple NULLs are allowed because NULL is not equal to NULL; SQL Server allows only one). Example: email is unique but user_id is the primary key.
Composite key. Any key made of two or more columns whose combination is unique. Example: enrolments(student_id, course_id) where neither column alone is unique. A composite key can be the primary key or a unique constraint.
Related terms. Candidate key (any minimal unique column set), surrogate key (a generated id with no business meaning), natural key (a real-world identifier such as PAN number).
CREATE TABLE enrolments (
student_id INT,
course_id INT,
enrolled_on DATE,
PRIMARY KEY (student_id, course_id)
);
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.