REPLACE INTO behavior in MySQL - Time & Space Complexity
We want to understand how the time it takes to run a REPLACE INTO query changes as the data grows.
Specifically, how does the database handle inserting or updating rows when using REPLACE INTO?
Analyze the time complexity of the following REPLACE INTO query.
REPLACE INTO users (id, name, email)
VALUES (5, 'Alice', 'alice@example.com');
This query inserts a new row or replaces an existing row with the same primary key in the users table.
Look for operations that repeat or scale with data size.
- Primary operation: Searching for an existing row with the same primary key.
- How many times: The database checks the index once per REPLACE INTO execution.
As the table grows, finding the row to replace depends on the index size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 3-4 steps to find the row |
| 100 | About 7 steps to find the row |
| 1000 | About 10 steps to find the row |
Pattern observation: The search steps grow slowly as the table grows, thanks to indexing.
Time Complexity: O(log n)
This means the time to find and replace a row grows slowly as the table gets bigger, because it uses an index to find the row efficiently.
[X] Wrong: "REPLACE INTO always scans the whole table to find a row to replace."
[OK] Correct: The database uses indexes to quickly find the row by primary key, so it does not scan the entire table.
Understanding how REPLACE INTO works helps you explain how databases handle updates and inserts efficiently, a useful skill for real projects and interviews.
"What if the table has no index on the primary key? How would the time complexity change?"
Practice
REPLACE INTO statement do in MySQL?Solution
Step 1: Understand the purpose of REPLACE INTO
TheREPLACE INTOstatement either inserts a new row or replaces an existing row if a unique key conflict occurs.Step 2: Compare with other statements
UnlikeINSERT, it can replace rows, and unlikeDELETE, it does not remove all rows before inserting.Final Answer:
Inserts a new row or replaces an existing row with the same unique key. -> Option AQuick Check:
REPLACE INTO = Insert or replace [OK]
- Thinking REPLACE INTO only inserts without replacing
- Confusing REPLACE INTO with DELETE
- Assuming REPLACE INTO updates without deleting first
REPLACE INTO in MySQL?Solution
Step 1: Recall REPLACE INTO syntax
The correct syntax usesREPLACE INTO table_name (columns) VALUES (values);format.Step 2: Identify incorrect options
Options A, C, and D use invalid syntax like missing INTO, wrong SET usage, or wrong VALUES format.Final Answer:
REPLACE INTO table_name (col1, col2) VALUES (val1, val2); -> Option AQuick Check:
Correct syntax = REPLACE INTO table_name (col1, col2) VALUES (val1, val2); [OK]
- Omitting INTO keyword
- Using SET instead of VALUES
- Incorrect parentheses placement
users(id INT PRIMARY KEY, name VARCHAR(20)) with rows:(1, 'Alice'), (2, 'Bob')What will be the result after executing:
REPLACE INTO users VALUES (2, 'Charlie');Then selecting all rows ordered by
id?Solution
Step 1: Understand REPLACE INTO effect on existing row
Sinceid=2exists, REPLACE deletes that row and inserts the new one with 'Charlie'.Step 2: Check final table rows
Row withid=1remains unchanged, row withid=2is replaced by (2, 'Charlie').Final Answer:
[(1, 'Alice'), (2, 'Charlie')] -> Option DQuick Check:
Row with id=2 replaced = [(1, 'Alice'), (2, 'Charlie')] [OK]
- Expecting duplicate keys after REPLACE
- Thinking REPLACE only updates without deleting
- Assuming original row remains unchanged
REPLACE INTO products (id, name) VALUES (1, 'Pen');But get an error:
ERROR 1146 (42S02): Table 'products' doesn't existWhat is the likely cause?
Solution
Step 1: Check syntax correctness
The query syntax is correct withREPLACE INTO products (id, name) VALUES (1, 'Pen');.Step 2: Identify cause of table error
Error 1146 indicates the tableproductsdoes not exist or is misspelled.Final Answer:
The tableproductsdoes not exist. -> Option CQuick Check:
Table doesn't exist error (1146) means the table is missing [OK]
- Assuming table error means wrong REPLACE INTO usage
- Ignoring table existence
- Confusing table error with syntax error
inventory(product_id INT PRIMARY KEY, quantity INT) with rows:(101, 5), (102, 10)You want to add 3 more units to product 101 or insert it if missing.
Which query correctly uses
REPLACE INTO to do this?Solution
Step 1: Understand REPLACE INTO behavior
REPLACE deletes existing row with product_id=101 and inserts new row with given quantity.Step 2: Check options for correctness
REPLACE INTO inventory VALUES (101, 8); replaces quantity with 8 (5+3). REPLACE INTO inventory VALUES (101, quantity + 3); is invalid syntax. REPLACE INTO inventory (product_id, quantity) VALUES (101, (SELECT quantity + 3, 0 FROM inventory WHERE product_id=101)); uses subquery in VALUES which is not allowed. REPLACE INTO inventory (product_id, quantity) VALUES (101, 3) ON DUPLICATE KEY UPDATE quantity = quantity + 3; mixes REPLACE and ON DUPLICATE KEY UPDATE which is invalid.Final Answer:
REPLACE INTO inventory VALUES (101, 8); -> Option BQuick Check:
REPLACE needs full new row, no expressions [OK]
- Using expressions like quantity + 3 directly in VALUES
- Mixing REPLACE INTO with ON DUPLICATE KEY UPDATE
- Using subqueries inside VALUES clause
Ready to prove it?
Pass the test and this pattern moves unknown
