Sobes.tech
Junior

What is the purpose of a unique key in databases?

sobes.tech AI

Answer from AI

A Unique key is used to ensure the uniqueness of values in one or more columns of a table.

Main purposes:

  1. Data integrity guarantee: Prevents duplication of records based on a specified criterion. For example, ensuring each user has a unique email address.
  2. Aid in searching: Speeds up query execution, as the DBMS can create an index for the unique key.
  3. Use as a potential primary key: Can be used as a basis for constructing a primary key if additional constraints are imposed (e.g., NOT NULL).

Example:

CREATE TABLE Users (
    user_id INT PRIMARY KEY,
    username VARCHAR(50) UNIQUE, -- guarantees login uniqueness
    email VARCHAR(100) UNIQUE -- guarantees email uniqueness
);
What is the purpose of a unique key in databases… - sobes.tech