UNIQUE constraints in MySQL - Time & Space Complexity
When we use UNIQUE constraints in a database, the system must check if a value already exists before adding a new one.
We want to understand how the time to check grows as the data grows.
Analyze the time complexity of enforcing a UNIQUE constraint during an INSERT.
INSERT INTO users (email) VALUES ('new@example.com');
-- The database checks if 'new@example.com' already exists in the email column
-- If it does, the insert fails; if not, it adds the new row
This code tries to add a new email, and the database must ensure no duplicate emails exist.
The database must check existing rows to enforce uniqueness.
- Primary operation: Searching for the value in the column with the UNIQUE constraint.
- How many times: Once per insert, but the search may scan many rows depending on data size.
As the number of rows grows, the time to check for duplicates can grow too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: Without special help, the checks grow roughly in direct proportion to the number of rows.
Time Complexity: O(n)
This means the time to check for duplicates grows roughly in step with the number of rows in the table.
[X] Wrong: "Checking for duplicates is always instant no matter how big the table is."
[OK] Correct: Without an index, the database must look through many rows, so more data means more work.
Understanding how UNIQUE constraints affect performance helps you design better databases and write efficient queries.
What if the UNIQUE constraint had an index supporting it? How would the time complexity change?
Practice
UNIQUE constraint in MySQL?Solution
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.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.Final Answer:
To prevent duplicate values in a column or set of columns -> Option AQuick Check:
UNIQUE constraint = prevent duplicates [OK]
- Confusing UNIQUE with PRIMARY KEY
- Thinking UNIQUE allows duplicates
- Assuming UNIQUE speeds up queries
email in a table users?Solution
Step 1: Recall correct ALTER TABLE syntax for UNIQUE
The correct syntax is to useADD UNIQUE (column_name)inside ALTER TABLE.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.Final Answer:
ALTER TABLE users ADD UNIQUE (email); -> Option BQuick Check:
ALTER TABLE ADD UNIQUE (column) [OK]
- Omitting parentheses around column name
- Using SET UNIQUE which is invalid
- Missing ADD keyword
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');
Solution
Step 1: Understand UNIQUE constraint effect on inserts
The UNIQUE constraint onemailprevents duplicate emails. The first insert adds the row successfully.Step 2: Analyze second insert behavior
The second insert tries to add the same email again, violating the UNIQUE constraint, causing an error.Final Answer:
First insert succeeds, second insert fails with duplicate error -> Option DQuick Check:
UNIQUE blocks duplicate inserts [OK]
- Assuming duplicates are allowed
- Thinking second insert updates existing row
- Confusing UNIQUE with PRIMARY KEY behavior
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?
Solution
Step 1: Identify the UNIQUE constraint effect
Thecodecolumn has a UNIQUE constraint, so duplicate values like 'X123' are not allowed.Step 2: Analyze the insert failure reason
The second insert tries to add 'X123' again, violating the UNIQUE constraint, causing failure.Final Answer:
The UNIQUE constraint oncodeprevents duplicate values -> Option AQuick Check:
UNIQUE constraint blocks duplicate column values [OK]
- Thinking PRIMARY KEY is required for uniqueness
- Assuming NULL disallows duplicates
- Blaming syntax error for insert failure
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?Solution
Step 1: Understand composite UNIQUE constraints
A UNIQUE constraint on multiple columns ensures the combination is unique, but allows duplicates in each column individually.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.Final Answer:
Add a UNIQUE constraint on (first_name, last_name) together -> Option CQuick Check:
Composite UNIQUE = unique pairs, not individual columns [OK]
- Adding UNIQUE on each column separately
- Confusing PRIMARY KEY with UNIQUE
- Not using composite constraint for pairs
Ready to prove it?
Pass the test and this pattern moves unknown
