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?