Junior — Middle
Can you explain what a one-to-one relationship means in databases?
sobes.tech AI
Answer from AI
A one-to-one relationship in databases means that each record in one table corresponds to exactly one record in another table, and vice versa.
For example, you have a Users table and a Profiles table. If each user has only one profile, and each profile belongs to only one user, then a one-to-one relationship is established between these tables.
This relationship is usually implemented using a foreign key with a unique constraint to ensure the uniqueness of the association.
Example in SQL:
CREATE TABLE Users (
UserId INT PRIMARY KEY,
UserName VARCHAR(100)
);
CREATE TABLE Profiles (
ProfileId INT PRIMARY KEY,
UserId INT UNIQUE,
Bio TEXT,
FOREIGN KEY (UserId) REFERENCES Users(UserId)
);
Here, UserId in the Profiles table with a UNIQUE constraint guarantees that each user has no more than one profile.