Junior — Middle
Can you give examples of unique keys and explain their features?
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 no duplicates.
Features of unique keys:
- Unlike a primary key, a unique key can contain NULL values (depending on the DBMS).
- Multiple unique keys can be created in a single table.
- Unique keys ensure data integrity by preventing duplication.
Example in SQL:
CREATE TABLE users (
id INT PRIMARY KEY,
email VARCHAR(255) UNIQUE,
username VARCHAR(50),
UNIQUE (username)
);
Here, email and username have unique constraints, which prevent inserting two records with the same email or username.