CodeBlanks Logo Icon CodeBlanks

UNIQUE constraint

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

query.sql
-- constrained table
CREATE TABLE products

Sample solution

query.sql
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

Question
CREATE TABLE products (
  id INT PRIMARY ____,
  name VARCHAR(100)
);
Answer
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

All lessons in Beginner