Unique index behavior in SQL - Time & Space Complexity
When we use a unique index in a database, it helps quickly find if a value already exists.
We want to know how the time to check or insert changes as the data grows.
Analyze the time complexity of the following SQL commands involving a unique index.
CREATE UNIQUE INDEX idx_email ON users(email);
INSERT INTO users (email, name) VALUES ('a@example.com', 'Alice');
SELECT * FROM users WHERE email = 'a@example.com';
This code creates a unique index on the email column, inserts a new user, and searches by email.
Look at what repeats when we insert or search using the unique index.
- Primary operation: Searching the index tree to find the right spot or value.
- How many times: The search steps grow slowly as data grows, not checking every row.
As the number of users grows, the steps to find or insert an email grow slowly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 3 steps |
| 100 | About 7 steps |
| 1000 | About 10 steps |
Pattern observation: The steps grow slowly, adding only a few more as data grows much larger.
Time Complexity: O(log n)
This means the time to find or insert grows slowly, even if the data gets very big.
[X] Wrong: "Checking a unique index takes as long as scanning all rows."
[OK] Correct: The unique index uses a tree structure that jumps quickly to the right place, so it does not check every row.
Understanding unique index time helps you explain how databases keep searches fast even with lots of data.
What if we removed the unique index and only had a regular index? How would the time complexity change?
Practice
UNIQUE index in a database table?Solution
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).Step 2: Compare options with this definition
Only To prevent duplicate values in one or more columns correctly states that UNIQUE prevents duplicates. Others describe unrelated behaviors.Final Answer:
To prevent duplicate values in one or more columns -> Option DQuick Check:
UNIQUE index = prevent duplicates [OK]
- Thinking UNIQUE speeds up insertion
- Confusing UNIQUE with sorting
- Believing UNIQUE allows duplicates
email in a table named users?Solution
Step 1: Recall correct syntax for unique index creation
The standard syntax is: CREATE UNIQUE INDEX index_name ON table_name(column_name);Step 2: Match options to syntax
CREATE UNIQUE INDEX idx_email ON users(email); matches exactly. CREATE INDEX UNIQUE idx_email ON users(email); has wrong keyword order. CREATE UNIQUE KEY idx_email ON users(email); uses UNIQUE KEY which is for constraints, not index creation. CREATE UNIQUE TABLE idx_email ON users(email); is invalid syntax.Final Answer:
CREATE UNIQUE INDEX idx_email ON users(email); -> Option BQuick Check:
CREATE UNIQUE INDEX = CREATE UNIQUE INDEX idx_email ON users(email); [OK]
- Swapping UNIQUE and INDEX keywords
- Using UNIQUE KEY instead of UNIQUE INDEX
- Trying to create UNIQUE TABLE (invalid)
products with a unique index on sku, what happens when you run this SQL?INSERT INTO products (sku, name) VALUES ('A123', 'Item1');
INSERT INTO products (sku, name) VALUES ('A123', 'Item2');Solution
Step 1: Understand unique index effect on inserts
The unique index onskumeans no two rows can have the sameskuvalue.Step 2: Analyze the insert statements
The first insert adds 'A123' successfully. The second tries to insert 'A123' again, violating uniqueness, causing an error.Final Answer:
Second insert fails with a duplicate key error -> Option AQuick Check:
Duplicate insert = error [OK]
- Assuming duplicates are allowed
- Thinking first insert fails
- Believing both inserts fail
username column. The following query causes an error:INSERT INTO users (username) VALUES ('john');
INSERT INTO users (username) VALUES ('john');What is the best way to fix this error?
Solution
Step 1: Identify cause of error
The unique index prevents duplicate usernames. Inserting 'john' twice violates this.Step 2: Choose a fix that respects uniqueness
Changing the second insert to a different username avoids duplicates and keeps data integrity.Final Answer:
Change the second insert to a different username -> Option AQuick Check:
Fix duplicates by changing values [OK]
- Removing unique index (loses data integrity)
- Inserting NULL (may not be allowed or unique)
- Using SELECT instead of INSERT (doesn't fix duplicates)
employees with a unique index on (email, department_id). Which of these inserts will cause a unique index violation if the table already has a row with email='alice@example.com' and department_id=10?Solution
Step 1: Understand composite unique index
The unique index on (email, department_id) means the combination of both values must be unique.Step 2: Check each insert against existing row
Only INSERT INTO employees (email, department_id) VALUES ('alice@example.com', 10); duplicates both email and department_id, causing violation. Others differ in at least one value, so allowed.Final Answer:
INSERT with email='alice@example.com' and department_id=10 causes violation -> Option CQuick Check:
Composite UNIQUE = unique pairs [OK]
- Thinking unique applies to each column separately
- Assuming different department_id allows duplicate email
- Ignoring composite key uniqueness
Ready to prove it?
Pass the test and this pattern moves unknown
