Junior — Middle
What is the role of keys in a database structure and why are they used?
sobes.tech AI
Answer from AI
Keys in a database structure are special fields (or sets of fields) used for data identification and organization.
Main types of keys:
- Primary Key: uniquely identifies each record in a table. Cannot contain NULL and must be unique.
- Foreign Key: a field that references the primary key of another table, ensuring a relationship between tables.
- Unique Keys: guarantee the uniqueness of values in a column but can allow NULL.
Why keys are needed:
- Ensure data integrity (e.g., prevent duplicate records).
- Enable efficient searching and linking of data between tables.
- Help optimize queries and indexing.
Example: in the users table, the id field can be a primary key, and in the orders table, the user_id field can be a foreign key referencing users.id.