UNIQUE constraint
- SQL course
- Beginner
- Lesson 95/115
- 4 min
Force unique values with UNIQUE.
What is a constraint?
A constraint is a restriction applied to table data. It prevents bad input and keeps integrity.
CREATE TABLE products (
id INT PRIMARY KEY,
name VARCHAR(100) NOT NULL
);PRIMARY KEY and NOT NULL are constraints.
The table products is created.
What is a constraint? — details
Constraints keep data consistent. They block bad inserts and updates. PRIMARY KEY, UNIQUE, NOT NULL, CHECK and FOREIGN KEY are common.
Practice What is a constraint?
Create products with id INT PRIMARY KEY and name VARCHAR(100) NOT NULL.
Starter code
-- constrained table
CREATE TABLE productsSample solution
CREATE TABLE products (
id INT PRIMARY KEY,
name VARCHAR(100) NOT NULL
)Expected output
Tablo oluşturuldu
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does a constraint do?
- Runs a query
- Protects data integrity Correct answer
- Deletes data
- Creates an index
Explanation: A constraint keeps data integrity.
2 Add constraint
CREATE TABLE products (
id INT PRIMARY ____,
name VARCHAR(100)
);
CREATE TABLE products (
id INT PRIMARY KEY,
name VARCHAR(100)
);
Explanation: PRIMARY KEY is two words; it makes the column unique and not null.
3 UNIQUE constraint: match the terms
| Term | Meaning |
|---|---|
PRIMARY KEY |
primary |
NOT NULL |
not null |
UNIQUE |
unique |
CHECK |
check |