Sobes.tech
Junior — Middle

Is it possible to define a composite primary key using multiple attributes in a database table?

sobes.tech AI

Answer from AI

Yes, in relational databases, a composite (or concatenated) primary key can be defined, which consists of multiple attributes (columns). Such a key guarantees the uniqueness of the combination of these column values.

Example of creating a table with a composite primary key in SQL:

CREATE TABLE orders (
    order_id INT,
    product_id INT,
    quantity INT,
    PRIMARY KEY (order_id, product_id)
);

Here, the primary key consists of two columns: order_id and product_id. This means that each pair of values must be unique, but order_id or product_id alone can be repeated.

Composite keys are often used to model "many-to-many" relationships or to ensure uniqueness across multiple fields simultaneously.