Junior — Middle
What are the ways to ensure data uniqueness in a database and what constraints are applied for this?
sobes.tech AI
Answer from AI
To ensure data uniqueness in a database, constraints and indexes are used, which guarantee that certain values will not be duplicated in a table.
Main methods:
- UNIQUE constraint — applied to one or more columns, prohibiting duplicate values. For example, a unique email in a users table.
- PRIMARY KEY — a unique constraint that also serves as the record identifier. Usually, the primary key is a single column or a set of columns that are unique and do not allow NULL.
- UNIQUE INDEX — an index that enforces the uniqueness of values, similar to a UNIQUE constraint, but created separately.
Example in SQL:
CREATE TABLE users (
id SERIAL PRIMARY KEY,
email VARCHAR(255) UNIQUE,
username VARCHAR(100),
CONSTRAINT unique_username UNIQUE (username)
);
Here, email and username cannot be duplicated.
Thus, uniqueness is ensured through PRIMARY KEY and UNIQUE constraints, which are applied to table columns.