INSERT INTO multiple rows in SQL - Time & Space Complexity
When adding many rows to a database table at once, it's important to understand how the time needed grows as you add more rows.
We want to know how the work 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 adds three new employee records to the employees table in one command.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Inserting each row into the table.
- How many times: Once for each row listed in the VALUES clause.
Each additional row means the database must do one more insert operation.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 insert actions |
| 100 | About 100 insert actions |
| 1000 | About 1000 insert actions |
Pattern observation: The work grows directly with the number of rows added.
Time Complexity: O(n)
This means the time to insert rows grows in a straight line as you add more rows.
[X] Wrong: "Adding multiple rows at once is always faster and takes the same time as adding one row."
[OK] Correct: Each row still needs to be inserted, so the total time grows with the number of rows, even if the command is one.
Understanding how inserting many rows affects time helps you write efficient database commands and explain your choices clearly.
"What if we inserted rows one by one using separate INSERT commands instead? How would the time complexity change?"