Primary key
Первичный ключ
A table can designate one column or a combination of columns to identify each row. No two rows can have the same primary key, and none of its columns can contain NULL.
What a primary key identifies
Two orders can have the same customer, date, and total. If order_id is the primary key, the database guarantees that an order ID identifies at most one row. That guarantee matters when you query or update a specific order, or when another table needs to refer to it. It applies even if several applications write to the same database.
What the database enforces
A table can declare only one PRIMARY KEY constraint. The key can span several columns: this is called a composite primary key. The database checks that the full combination is unique and that every key column has a value other than NULL. An insert or update that would violate either rule cannot be saved.
A primary key is a constraint, not an index. In PostgreSQL, declaring one normally creates a unique B-tree index to enforce uniqueness. That index can also speed up lookups, but it doesn't guarantee the order of query results. Use ORDER BY when the result order matters.
Example: one enrollment per student and course
CREATE TABLE enrollments (
student_id bigint REFERENCES students (id),
course_id bigint REFERENCES courses (id),
PRIMARY KEY (student_id, course_id)
);
Assume that students and courses already exist and that each has an id primary key. Both (7, 101) and (7, 102) are valid: student 7 can take two courses. A second (7, 101) is not valid. The primary key prevents duplicate enrollments, while the foreign keys require the referenced student and course to exist. If students can enroll in the same course in different terms, the key must reflect that requirement, for example by including a term ID.
Choosing a key
A natural key comes from the domain. An order number can serve as one if it's unique across the table and stable. A surrogate key is introduced just to identify a row, such as a generated integer. Declaring PRIMARY KEY doesn't generate values; in PostgreSQL you can add an identity declaration to an integer column for that purpose.
The table can have other unique values besides the primary key. If you give enrollments a surrogate enrollment_id, the database will accept two rows for the same student and course as long as their IDs differ. To keep the original rule, add UNIQUE (student_id, course_id) and explicitly mark both columns NOT NULL.
How it comes up in interviews
Expect to design a join table or explain the difference between PRIMARY KEY and UNIQUE. Start by saying what one row represents and which values must not repeat. Then explain whether a composite key expresses that rule directly or whether you'd use a separate ID and enforce the rule with another constraint.