Can a primary key be composite?
sobes.tech AI
Answer from AI
Yes, a primary key can be composite. A composite primary key is a key consisting of multiple columns in a table that together uniquely identify a record.
Example in SQL:
CREATE TABLE Orders (
OrderID INT,
ProductID INT,
Quantity INT,
PRIMARY KEY (OrderID, ProductID)
);
Here, the combination of OrderID and ProductID is unique and serves as the primary key.
In Go, when working with ORM (e.g., GORM), a composite key can be described using tags or separate structures, but it is important to note that not all ORMs support composite keys equally conveniently.
Composite keys are useful when the uniqueness of a record is determined by a combination of several fields rather than just one. However, their use can complicate queries and maintenance, so sometimes it is preferable to use a surrogate key (e.g., an auto-incremented ID).