Junior — Middle
When and why is it recommended to specify a primary key in a database?
sobes.tech AI
Answer from AI
It is recommended to always specify a primary key in a database whenever it is necessary to uniquely identify each record in a table. This ensures data integrity and allows for efficient search, update, and delete operations.
Main reasons for specifying a primary key:
- Uniqueness: guarantees that there will be no duplicates in the table based on the key field.
- Indexing: the primary key is automatically indexed, which speeds up queries.
- Relationships: used to establish relationships between tables (foreign keys).
For example, in a users table, the id field is often made the primary key:
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR(100),
email VARCHAR(100) UNIQUE
);