Middle+
What are FK and UNIQUE constraints in a database?
sobes.tech AI
Answer from AI
FK (Foreign Key) — a database constraint that ensures referential integrity between tables. It guarantees that the value in a column (or set of columns) matches a primary key value in another table. This prevents the appearance of "dangling" references.
UNIQUE constraint — a constraint that guarantees all values in a column (or group of columns) are unique, i.e., no duplicates. This is useful for ensuring data uniqueness, such as a unique user email.
Example in SQL:
CREATE TABLE users (
id SERIAL PRIMARY KEY,
email VARCHAR(255) UNIQUE
);
CREATE TABLE orders (
id SERIAL PRIMARY KEY,
user_id INT,
FOREIGN KEY (user_id) REFERENCES users(id)
);
Here, email is unique, and user_id in the orders table references an existing user in users.