UNIQUE constraint in SQL - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When we add a UNIQUE constraint to a database column, the system automatically creates a unique index (typically a B-tree) to enforce uniqueness efficiently.
We want to understand how the time to check uniqueness grows as the table gets bigger.
Analyze the time complexity of enforcing a UNIQUE constraint during data insertion.
INSERT INTO users (email) VALUES ('newuser@example.com');
-- The database checks the unique index on 'email' for duplicates
-- If not found, it inserts the new row into both table and index
This code inserts a new email; the database uses the index to ensure uniqueness efficiently.
The database traverses the unique index (B-tree) to check for existing values.
- Primary operation: Tree traversal/comparisons in the B-tree index.
- How many times: Proportional to the height of the tree, logarithmic in the number of rows.
As the table grows, the index height increases logarithmically, keeping checks efficient.
| Input Size (n) | Approx. Operations (log n) |
|---|---|
| 10 | ~3-4 comparisons |
| 100 | ~6-7 comparisons |
| 1000 | ~9-10 comparisons |
Pattern observation: The number of operations grows logarithmically with the number of rows.
Time Complexity: O(log n)
This means the time to check and enforce uniqueness grows logarithmically as the table gets bigger, thanks to the index.
[X] Wrong: "The UNIQUE check scans all rows linearly, so O(n)."
[OK] Correct: UNIQUE constraints automatically use an index (e.g., B-tree), enabling O(log n) lookups and inserts.
Understanding how constraints and indexes affect performance helps you design scalable databases and optimize queries.
"What if there was no index on the column? How would the time complexity change?"
Practice
UNIQUE constraint in SQL?Solution
Step 1: Understand the UNIQUE constraint and compare to options
The UNIQUE constraint ensures that all values in a column or a set of columns are different from each other. The other options describe different SQL features, but only "To prevent duplicate values in a column or group of columns" correctly describes the UNIQUE constraint.Final Answer:
To prevent duplicate values in a column or group of columns -> Option DQuick Check:
UNIQUE constraint = prevent duplicates [OK]
- Confusing UNIQUE with PRIMARY KEY
- Thinking UNIQUE speeds up queries
- Assuming UNIQUE allows duplicates
email in a table users?Solution
Step 1: Recall ALTER TABLE syntax for UNIQUE and check options
The correct syntax to add a UNIQUE constraint is: ALTER TABLE table_name ADD UNIQUE (column_name); "ALTER TABLE users ADD UNIQUE (email);" matches exactly. The other options misuse keywords or omit parentheses.Final Answer:
ALTER TABLE users ADD UNIQUE (email); -> Option CQuick Check:
ALTER TABLE ADD UNIQUE (column) syntax = ALTER TABLE users ADD UNIQUE (email); [OK]
- Omitting parentheses around column name
- Using ADD CONSTRAINT UNIQUE without naming constraint
- Misplacing keywords in ALTER TABLE
products with a UNIQUE constraint on product_code, what happens when you run this SQL?INSERT INTO products (product_code, name) VALUES ('X123', 'Item A');
INSERT INTO products (product_code, name) VALUES ('X123', 'Item B');Solution
Step 1: Analyze UNIQUE constraint effect on the insert statements
The UNIQUE constraint on product_code means no two rows can have the same product_code value. The first insert adds 'X123' successfully. The second insert tries to add the same product_code 'X123', which violates the UNIQUE constraint, causing an error.Final Answer:
The second insert fails with a UNIQUE constraint violation error -> Option AQuick Check:
Duplicate insert on UNIQUE column = error [OK]
- Assuming duplicates overwrite existing rows
- Thinking duplicates are ignored silently
- Believing both inserts succeed
username but got an error. What is the most likely cause?Solution
Step 1: Understand UNIQUE addition failure and evaluate causes
Adding a UNIQUE constraint fails if existing data violates uniqueness (duplicates exist). "The columnusernamecontains duplicate values already" identifies the cause. A non-existent table is unrelated (assuming it exists); UNIQUE can be added later; indexing is irrelevant or automatic.Final Answer:
The columnusernamecontains duplicate values already -> Option BQuick Check:
Duplicates prevent adding UNIQUE constraint [OK]
- Assuming UNIQUE can't be added after creation
- Ignoring existing duplicate data
- Confusing indexing with UNIQUE constraint
first_name and last_name in the employees table is unique, but duplicates are allowed in each column individually. Which SQL statement correctly enforces this?Solution
Step 1: Understand multi-column UNIQUE and analyze options
A UNIQUE constraint on multiple columns ensures the combination is unique (individual duplicates allowed). "ALTER TABLE employees ADD UNIQUE (first_name, last_name);" correctly adds UNIQUE on the pair. Adding UNIQUE separately disallows individual duplicates; other syntax is wrong or ignores one column.Final Answer:
ALTER TABLE employees ADD UNIQUE (first_name, last_name); -> Option AQuick Check:
Multi-column UNIQUE = unique pairs [OK]
- Adding UNIQUE on each column separately
- Using incorrect syntax without parentheses
- Ignoring the need for combined uniqueness
