INSERT INTO multiple rows in MySQL - Time & Space Complexity
When adding many rows to a database table at once, it's important to know how the time to insert grows as we add more rows.
We want to understand how the cost changes when inserting multiple rows in one command.
Analyze the time complexity of the following code snippet.
INSERT INTO employees (name, age, department) VALUES
('Alice', 30, 'HR'),
('Bob', 25, 'Sales'),
('Charlie', 28, 'IT');
This code inserts three new employee records into the employees table in a single statement.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Inserting each row into the table.
- How many times: Once per row being inserted (here 3 times).
Each additional row adds roughly one more insert operation.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 insert operations |
| 100 | About 100 insert operations |
| 1000 | About 1000 insert operations |
Pattern observation: The work grows directly with the number of rows inserted.
Time Complexity: O(n)
This means the time to insert grows in a straight line as you add more rows.
[X] Wrong: "Inserting multiple rows at once takes the same time as inserting just one row."
[OK] Correct: Each row still needs to be added, so more rows mean more work and more time.
Understanding how insert time grows helps you explain database performance clearly and shows you know how data size affects operations.
"What if we inserted rows one by one in separate statements instead? How would the time complexity change?"