Bird
Raised Fist0
MySQLquery~10 mins

UNIQUE constraints in MySQL - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - UNIQUE constraints
Start Table Creation
↓
Define Columns
↓
Add UNIQUE Constraint
↓
Insert Data
↓
Check for Duplicate Values
↓
Insert Row
↓
Continue or End
When creating a table, you define columns and add UNIQUE constraints to ensure no duplicate values in those columns. When inserting data, the database checks for duplicates and rejects rows that violate the UNIQUE rule.
Execution Sample
MySQL
CREATE TABLE users (
  id INT PRIMARY KEY,
  email VARCHAR(100) UNIQUE
);

INSERT INTO users VALUES (1, 'a@example.com');
INSERT INTO users VALUES (2, 'a@example.com');
This code creates a users table with a UNIQUE constraint on the email column, then tries to insert two rows with the same email.
Execution Table
StepActionData InsertedCheck UNIQUE ConstraintResult
1Create table with UNIQUE on emailN/AN/ATable created
2Insert row (1, 'a@example.com')(1, 'a@example.com')No duplicate foundRow inserted
3Insert row (2, 'a@example.com')(2, 'a@example.com')Duplicate email foundInsert rejected with error
💡 Insert rejected at step 3 because email 'a@example.com' already exists violating UNIQUE constraint
Variable Tracker
VariableStartAfter Step 2After Step 3
users table rowsempty[(1, 'a@example.com')][(1, 'a@example.com')] (no change, insert rejected)
Key Moments - 2 Insights
Why does the second insert fail even though the id is different?
Because the UNIQUE constraint is on the email column, not the id. The second insert tries to add a duplicate email, which violates the UNIQUE rule as shown in execution_table step 3.
Can a UNIQUE constraint allow NULL values?
Yes, UNIQUE constraints allow multiple NULLs because NULL means unknown, so duplicates are not considered. This is not shown in the example but is a common behavior in MySQL.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what happens at step 2?
AThe row is inserted because no duplicate email exists
BThe insert is rejected due to duplicate email
CThe table is dropped
DThe UNIQUE constraint is removed
💡 Hint
Check the 'Result' column in execution_table row 2
At which step does the UNIQUE constraint cause an error?
AStep 2
BStep 3
CStep 1
DNo error occurs
💡 Hint
Look at the 'Check UNIQUE Constraint' and 'Result' columns in execution_table
If the UNIQUE constraint was removed, what would happen at step 3?
ATable would be dropped
BInsert would still fail
CInsert would succeed, duplicate emails allowed
DInsert would cause syntax error
💡 Hint
UNIQUE constraints prevent duplicates; removing it allows duplicates as per concept_flow
Concept Snapshot
UNIQUE constraints ensure column values are unique in a table.
Defined during table creation or altered later.
Inserts violating UNIQUE cause errors.
Allows multiple NULLs in MySQL.
Used to prevent duplicate data entries.
Full Transcript
This visual execution shows how UNIQUE constraints work in MySQL. First, a table is created with a UNIQUE constraint on the email column. When inserting the first row with email 'a@example.com', it succeeds because the table is empty. When inserting a second row with the same email, the database checks the UNIQUE constraint, finds a duplicate, and rejects the insert with an error. The variable tracker shows the table rows after each step, confirming no change after the failed insert. Key moments clarify why the second insert fails despite different ids and that UNIQUE allows multiple NULLs. The quiz tests understanding of when inserts succeed or fail due to UNIQUE constraints. The snapshot summarizes the main points for quick review.

Practice

(1/5)
1. What is the main purpose of a UNIQUE constraint in MySQL?
easy
A. To prevent duplicate values in a column or set of columns
B. To allow NULL values in a column
C. To speed up query performance
D. To automatically generate unique IDs

Solution

  1. Step 1: Understand the role of UNIQUE constraint

    A UNIQUE constraint ensures that all values in a column or a group of columns are different from each other.
  2. Step 2: Compare with other options

    Options A, C, and D describe other features: allowing NULLs, indexing, and auto-increment, which are not the main purpose of UNIQUE.
  3. Final Answer:

    To prevent duplicate values in a column or set of columns -> Option A
  4. Quick Check:

    UNIQUE constraint = prevent duplicates [OK]
Hint: UNIQUE means no two rows share the same value [OK]
Common Mistakes:
  • Confusing UNIQUE with PRIMARY KEY
  • Thinking UNIQUE allows duplicates
  • Assuming UNIQUE speeds up queries
2. Which of the following is the correct syntax to add a UNIQUE constraint to an existing column email in a table users?
easy
A. ALTER TABLE users SET UNIQUE email;
B. ALTER TABLE users ADD UNIQUE (email);
C. ALTER TABLE users ADD UNIQUE email;
D. ALTER TABLE users ADD CONSTRAINT UNIQUE email;

Solution

  1. Step 1: Recall correct ALTER TABLE syntax for UNIQUE

    The correct syntax is to use ADD UNIQUE (column_name) inside ALTER TABLE.
  2. Step 2: Check each option

    ALTER TABLE users ADD UNIQUE (email); matches the correct syntax. Options A, B, and C are invalid or incomplete syntax.
  3. Final Answer:

    ALTER TABLE users ADD UNIQUE (email); -> Option B
  4. Quick Check:

    ALTER TABLE ADD UNIQUE (column) [OK]
Hint: Use ADD UNIQUE (column) to add constraint [OK]
Common Mistakes:
  • Omitting parentheses around column name
  • Using SET UNIQUE which is invalid
  • Missing ADD keyword
3. Given the table users(id INT, username VARCHAR(50), email VARCHAR(100)) with a UNIQUE constraint on email, what happens if you run this query twice?
INSERT INTO users (id, username, email) VALUES (1, 'alice', 'alice@example.com');
medium
A. Both inserts succeed, creating two identical rows
B. Both inserts fail due to UNIQUE constraint
C. Second insert updates the existing row
D. First insert succeeds, second insert fails with duplicate error

Solution

  1. Step 1: Understand UNIQUE constraint effect on inserts

    The UNIQUE constraint on email prevents duplicate emails. The first insert adds the row successfully.
  2. Step 2: Analyze second insert behavior

    The second insert tries to add the same email again, violating the UNIQUE constraint, causing an error.
  3. Final Answer:

    First insert succeeds, second insert fails with duplicate error -> Option D
  4. Quick Check:

    UNIQUE blocks duplicate inserts [OK]
Hint: Duplicate insert fails due to UNIQUE constraint [OK]
Common Mistakes:
  • Assuming duplicates are allowed
  • Thinking second insert updates existing row
  • Confusing UNIQUE with PRIMARY KEY behavior
4. You have this table creation statement:
CREATE TABLE products (id INT, code VARCHAR(20) UNIQUE);

You try to insert two rows:
INSERT INTO products VALUES (1, 'X123');
INSERT INTO products VALUES (2, 'X123');

But the second insert fails. What is the most likely cause?
medium
A. The UNIQUE constraint on code prevents duplicate values
B. The id column is missing a PRIMARY KEY
C. The table does not allow NULL values in code
D. The syntax of the INSERT statement is incorrect

Solution

  1. Step 1: Identify the UNIQUE constraint effect

    The code column has a UNIQUE constraint, so duplicate values like 'X123' are not allowed.
  2. Step 2: Analyze the insert failure reason

    The second insert tries to add 'X123' again, violating the UNIQUE constraint, causing failure.
  3. Final Answer:

    The UNIQUE constraint on code prevents duplicate values -> Option A
  4. Quick Check:

    UNIQUE constraint blocks duplicate column values [OK]
Hint: UNIQUE blocks duplicate values in that column [OK]
Common Mistakes:
  • Thinking PRIMARY KEY is required for uniqueness
  • Assuming NULL disallows duplicates
  • Blaming syntax error for insert failure
5. You want to ensure that the combination of first_name and last_name in a contacts table is unique, but each column alone can have duplicates. Which is the correct way to enforce this in MySQL?
hard
A. Add a PRIMARY KEY on first_name
B. Add UNIQUE constraints separately on first_name and last_name
C. Add a UNIQUE constraint on (first_name, last_name) together
D. Add a UNIQUE constraint only on last_name

Solution

  1. Step 1: Understand composite UNIQUE constraints

    A UNIQUE constraint on multiple columns ensures the combination is unique, but allows duplicates in each column individually.
  2. Step 2: Evaluate options for enforcing uniqueness

    Add a UNIQUE constraint on (first_name, last_name) together correctly adds a UNIQUE constraint on the pair (first_name, last_name). Options B, C, and D enforce uniqueness incorrectly or partially.
  3. Final Answer:

    Add a UNIQUE constraint on (first_name, last_name) together -> Option C
  4. Quick Check:

    Composite UNIQUE = unique pairs, not individual columns [OK]
Hint: Use UNIQUE on multiple columns for combined uniqueness [OK]
Common Mistakes:
  • Adding UNIQUE on each column separately
  • Confusing PRIMARY KEY with UNIQUE
  • Not using composite constraint for pairs
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard