How can a table in a database be set with two primary keys?

In relational databases, a table typically can only have one primary key, but the effect of having two primary keys can be achieved by using a composite key. A composite key is a primary key composed of multiple fields, ensuring that each record is unique.

For example, if there is a student table that requires both student ID and ID card number as primary keys, you can create a composite key using the following SQL statement:

CREATE TABLE Students (
    student_id INT,
    id_card_number VARCHAR(20),
    -- other columns
    PRIMARY KEY (student_id, id_card_number)
);

In this way, combining each student’s student ID and ID card number together forms a unique primary key, ensuring that each record in the table is unique.

广告
Closing in 10 seconds
bannerAds