Multiple Inserts & Bulk Loading π¦ΒΆ
Prerequisites: INSERT INTO Basics
Mentor's Note: In the real world, you rarely insert one row at a time. Whether you are migrating data or importing a CSV, you need to handle batches. Efficiency is key here! π‘
π The Scenario: The Wholesale Order πΒΆ
Imagine you are a supplier delivering water bottles.
- Single Insert: Carrying one bottle at a time to the fridge. (Exhausting! π₯΅)
- Multiple Insert: Using a crate to carry 24 bottles at once. (Efficient! β‘)
- INSERT INTO SELECT: Transferring all bottles from a truck directly into the warehouse.
π» 1. Inserting Multiple Rows (One Query)ΒΆ
Most modern databases allow you to insert many rows in a single statement.
π» 2. Copying Data (INSERT INTO SELECT) πΈΒΆ
This is the most powerful way to move data between tables. It "SELECTS" from one table and "INSERTS" into another.
-- Scenario: Moving 'Active' students to a 'Graduates' archive
INSERT INTO graduates (id, name, grade)
SELECT id, name, grade
FROM students
WHERE status = 'Completed';
π» 3. Bulk Loading from External FilesΒΆ
If you have a .csv file with 1 million rows, don't use INSERT. Use the database's specific bulk loader.
- MySQL:
LOAD DATA INFILE 'file.csv' ... - PostgreSQL:
\copy table FROM 'file.csv' ... - Oracle:
SQL*LoaderorExternal Tables.
π‘ Performance TipΒΆ
"Inserting 1,000 rows in one query is significantly faster than running 1,000 separate
INSERTstatements. Each separate statement requires a 'round-trip' to the server, which adds overhead!"