Sobes.tech
Junior — Middle

Explain what a unique key in a database is and how it is used to ensure data integrity.

sobes.tech AI

Answer from AI

A UNIQUE key in a database is a constraint that guarantees all values in a column or a set of columns are unique, meaning they do not repeat across different rows.

This ensures data integrity by preventing duplicate records based on certain criteria. For example, a unique key can be set on a user's email field to prevent two accounts from having the same email.

In SQL, it looks like this:

CREATE TABLE users (
    id INT PRIMARY KEY,
    email VARCHAR(255) UNIQUE
);

Thus, attempting to insert a record with an existing email will result in an error, helping to maintain data correctness and quality.