Bird
Raised Fist0
MySQLquery~10 mins

Unique indexes in MySQL - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Unique indexes
Create Table
↓
Add Unique Index
↓
Insert Row
↓
Check Unique Constraint
↓
Insert OK
↓
Next Insert or End
When you create a unique index, the database checks each new row to make sure the indexed column values are unique. If a duplicate is found, the insert is rejected.
Execution Sample
MySQL
CREATE TABLE users (
  id INT PRIMARY KEY,
  email VARCHAR(100),
  UNIQUE (email)
);

INSERT INTO users VALUES (1, 'a@example.com');
INSERT INTO users VALUES (2, 'a@example.com');
This code creates a table with a unique index on email, inserts one row, then tries to insert a duplicate email which fails.
Execution Table
StepActionInput DataUnique Check ResultOutcome
1Create table users with unique index on emailN/AN/ATable created
2Insert rowid=1, email='a@example.com'No duplicate foundRow inserted
3Insert rowid=2, email='a@example.com'Duplicate email foundInsert rejected
💡 Insert rejected at step 3 because email 'a@example.com' already exists, violating unique index
Variable Tracker
VariableStartAfter Step 2After Step 3
users table rowsempty[{id:1, email:'a@example.com'}][{id:1, email:'a@example.com'}] (no change)
Key Moments - 2 Insights
Why does the second insert fail even though the id is different?
Because the unique index is on the email column, not the id. The email 'a@example.com' already exists, so the unique constraint rejects the insert (see execution_table step 3).
What happens if we insert a row with a different email?
The insert will succeed because the unique index only rejects duplicates on the indexed column. This is shown in execution_table step 2 where a new unique email is inserted.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the outcome of step 2?
AInsert rejected due to duplicate
BTable creation failed
CRow inserted successfully
DNo action taken
💡 Hint
Check the 'Outcome' column in execution_table row for step 2
At which step does the unique constraint cause an insert to be rejected?
AStep 2
BStep 3
CStep 1
DNo rejection occurs
💡 Hint
Look at the 'Unique Check Result' and 'Outcome' columns in execution_table
If the unique index was removed, what would happen at step 3?
AInsert would succeed
BInsert would still be rejected
CTable would drop
DDatabase error unrelated to unique index
💡 Hint
Refer to the concept_flow where unique index enforces uniqueness
Concept Snapshot
Unique indexes ensure column values are unique in a table.
When inserting, the database checks for duplicates.
If a duplicate exists, the insert is rejected.
Useful for columns like email to avoid duplicates.
Syntax: UNIQUE (column_name) in CREATE TABLE or ALTER TABLE.
Full Transcript
Unique indexes in MySQL are special rules that make sure no two rows have the same value in certain columns. When you create a unique index on a column, like email, the database checks every new row you add. If the email already exists, it stops you from adding that row. For example, if you insert a user with email 'a@example.com' and then try to insert another user with the same email, the second insert will fail. This helps keep data clean and prevents duplicates. The unique index only cares about the columns it covers, so other columns like id can have duplicates if not indexed uniquely.

Practice

(1/5)
1. What is the main purpose of a UNIQUE index in MySQL?
easy
A. To prevent duplicate values in one or more columns
B. To speed up data insertion
C. To allow duplicate values in a column
D. To delete duplicate rows automatically

Solution

  1. Step 1: Understand the role of UNIQUE index

    A UNIQUE index ensures that no two rows have the same value in the indexed column(s).
  2. Step 2: Compare options with this definition

    Only To prevent duplicate values in one or more columns correctly states that UNIQUE prevents duplicates. Others are incorrect or unrelated.
  3. Final Answer:

    To prevent duplicate values in one or more columns -> Option A
  4. Quick Check:

    UNIQUE index = prevent duplicates [OK]
Hint: UNIQUE means no duplicates allowed in indexed columns [OK]
Common Mistakes:
  • Thinking UNIQUE speeds up inserts
  • Believing UNIQUE allows duplicates
  • Confusing UNIQUE with automatic deletion
2. Which of the following is the correct syntax to create a UNIQUE index on the column email in a table named users?
easy
A. CREATE UNIQUE KEY idx_email FROM users(email);
B. CREATE INDEX UNIQUE idx_email ON users(email);
C. CREATE UNIQUE INDEX idx_email ON users(email);
D. CREATE UNIQUE ON users INDEX idx_email(email);

Solution

  1. Step 1: Recall correct syntax for UNIQUE index creation

    The correct syntax is: CREATE UNIQUE INDEX index_name ON table_name(column_name);
  2. Step 2: Match options with correct syntax

    CREATE UNIQUE INDEX idx_email ON users(email); matches exactly. Others have wrong keyword order or syntax errors.
  3. Final Answer:

    CREATE UNIQUE INDEX idx_email ON users(email); -> Option C
  4. Quick Check:

    CREATE UNIQUE INDEX ... ON ... (column) [OK]
Hint: Remember: CREATE UNIQUE INDEX name ON table(column) [OK]
Common Mistakes:
  • Swapping UNIQUE and INDEX keywords
  • Using FROM instead of ON
  • Incorrect keyword order
3. Given the table employees with a UNIQUE index on employee_id, what happens if you run this query?
INSERT INTO employees (employee_id, name) VALUES (101, 'Alice');
INSERT INTO employees (employee_id, name) VALUES (101, 'Bob');
medium
A. The second insert fails with a duplicate key error
B. Both rows are inserted successfully
C. The second insert overwrites the first row
D. The second insert is ignored silently

Solution

  1. Step 1: Understand UNIQUE index effect on inserts

    A UNIQUE index on employee_id prevents duplicate values in that column.
  2. Step 2: Analyze the inserts

    The first insert adds employee_id 101. The second insert tries to add the same employee_id 101, violating the UNIQUE constraint, causing an error.
  3. Final Answer:

    The second insert fails with a duplicate key error -> Option A
  4. Quick Check:

    UNIQUE index blocks duplicate inserts [OK]
Hint: Duplicate insert on UNIQUE column causes error [OK]
Common Mistakes:
  • Assuming duplicates are allowed
  • Thinking second insert overwrites first
  • Believing second insert is ignored silently
4. You tried to create a UNIQUE index on the column username but got an error. Which of these is the most likely cause?
medium
A. The table does not exist
B. The username column contains duplicate values
C. You forgot to specify the index name
D. UNIQUE indexes are not supported on text columns

Solution

  1. Step 1: Understand UNIQUE index creation requirements

    Creating a UNIQUE index requires all existing values in the column to be unique.
  2. Step 2: Identify common error causes

    If duplicates exist, MySQL throws an error when creating the UNIQUE index.
  3. Final Answer:

    The username column contains duplicate values -> Option B
  4. Quick Check:

    Duplicates block UNIQUE index creation [OK]
Hint: Check for duplicates before creating UNIQUE index [OK]
Common Mistakes:
  • Assuming index name is mandatory
  • Believing UNIQUE not allowed on text columns
  • Ignoring existing duplicates
5. You want to ensure that the combination of first_name and last_name in the contacts table is unique, but duplicates are still appearing. Which is the best way to fix this?
hard
A. Use a CHECK constraint to prevent duplicates
B. Create separate UNIQUE indexes on first_name and last_name individually
C. Add a PRIMARY KEY on first_name
D. Create a UNIQUE index on both first_name and last_name columns together

Solution

  1. Step 1: Understand uniqueness on multiple columns

    To ensure uniqueness on a combination, a composite UNIQUE index on both columns is needed.
  2. Step 2: Analyze other options

    Separate UNIQUE indexes allow duplicates across combinations. PRIMARY KEY on one column doesn't cover both. CHECK constraints can't enforce uniqueness.
  3. Final Answer:

    Create a UNIQUE index on both first_name and last_name columns together -> Option D
  4. Quick Check:

    Composite UNIQUE index = unique pairs [OK]
Hint: Use composite UNIQUE index for multi-column uniqueness [OK]
Common Mistakes:
  • Creating separate UNIQUE indexes instead of composite
  • Using PRIMARY KEY on one column only
  • Relying on CHECK constraints for uniqueness
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