# Topic 5: INSERT Statements
Single row inserts, multi-row batching, INSERT INTO ... SELECT, and the RETURNING clause for atomic pipelines.
1. Definition
The INSERT statement is a DML command used to add one or more new tuples (rows) into a database table.
2. Explain Like I'm 5
INSERT is like mailing a letter into a mailbox. You fill out the address and details, drop it in, and the post office assigns it a receipt and spot.
3. Animation & Visual Simulation
Interactive Engine TraceINSERT Statements Visual Simulator
INSERT INTO users (username, email)
VALUES ('lucky', 'lucky@test.com')
RETURNING id, created_at;Active InputStep 1: Input & Parsing Stage
Initiating INSERT Statements
Checking Table Invariants
The database engine inspects active tables, verifies permissions, and prepares the physical operation.
4. Real-World Example
A registration service creates new user records and needs their newly generated primary key IDs immediately.
| id (Auto) | username | |
|---|---|---|
| 101 | lucky | lucky@example.com |
| 102 | rahul | rahul@example.com |
5. SQL Syntax
ANSI SQL / PostgreSQL DialectINSERT INTO users (username, email)
VALUES ('lucky', 'lucky@example.com')
RETURNING id, created_at;INSERT INTO users (username, email) VALUES
('rahul', 'rahul@example.com'),
('amit', 'amit@example.com'),
('neha', 'neha@example.com');INSERT INTO user_archives (id, email) SELECT id, email FROM users WHERE is_active = FALSE;
6. Important Rules & Behaviors
| Rule | Behavioral Explanation |
|---|---|
| Column List Matching | Values in the VALUES list must align with the specified column order. |
| Default Value Omission | Columns with DEFAULT or IDENTITY constraints can be omitted from the insert column list. |
| Constraint Violations | If any single row in a multi-row insert violates a constraint, the entire statement is rolled back. |
| Batch insert network efficiency | Inserting 1,000 rows in a single multi-row statement avoids 999 network round-trips and transaction commits. |
| Atomic UPSERT guarantees | ON CONFLICT DO UPDATE takes an exclusive row lock, preventing race conditions inherent in SELECT-then-INSERT logic. |
7. Deep Dive: Batch Inserts and Write-Ahead Log (WAL) Efficiency
Executing 1,000 separate INSERT statements causes 1,000 network round-trips and 1,000 transaction sync operations. A single batched INSERT statement writes all tuples in one go, drastically reducing disk flush overhead.
-- Slow (1000 round-trips): -- INSERT INTO t VALUES (1); INSERT INTO t VALUES (2); ... -- Fast (1 round-trip): INSERT INTO t (val) VALUES (1), (2), (3), (4), (5);
8. Advantages & Disadvantages
Advantages
- •Batching minimizes network round-trips and WAL lock contention.
- •RETURNING clause provides instant access to auto-generated columns.
- •INSERT INTO SELECT allows bulk data transformation without application middleware.
Disadvantages & Trade-offs
- •A single failing row in a batch statement cancels all other rows unless handled with ON CONFLICT.
9. Common Interview Questions
Q1.Why is batch inserting (INSERT ... VALUES (...), (...)) so much faster than single-row inserts?
A single-row INSERT requires a client-server network round trip, query parsing, planning, WAL transaction commit (forcing an fsync to disk), and index updates. Batching 1,000 tuples into one statement parses once, acquires locks once, amortizes a single WAL fsync across 1,000 rows, and batch-updates B-Tree indexes, achieving 50x to 100x higher throughput.
Q2.What is UPSERT (INSERT ON CONFLICT) and how does it prevent race conditions?
Before ON CONFLICT, applications had to query SELECT ... WHERE id = 1, then issue INSERT if missing or UPDATE if present. Under concurrent traffic, two threads could simultaneously see no row, both issue INSERT, and one would fail with a Unique Key Violation. INSERT ... ON CONFLICT DO UPDATE executes atomically inside the storage engine using row locks.
INSERT INTO page_views (page_url, views)
VALUES ('/blog/sql', 1)
ON CONFLICT (page_url)
DO UPDATE SET views = page_views.views + 1
RETURNING views;Q3.Why should you use INSERT ... RETURNING instead of querying SELECT MAX(id)?
Querying SELECT MAX(id) after an insert is susceptible to severe race conditions: another transaction could insert a row between your insert and your query, returning the wrong ID. Furthermore, MAX(id) requires a separate query. INSERT ... RETURNING returns the generated ID directly from the newly inserted tuple header with zero race conditions and zero extra round-trips.
Q4.What is bulk loading (COPY / LOAD DATA INFILE) and why does it outperform INSERT statements?
The PostgreSQL COPY command (or MySQL LOAD DATA INFILE) bypasses the SQL parser, query planner, and per-row statement overhead. The database engine reads raw CSV/binary streams directly into 8 KB buffer pages, postponing secondary index updates and constraint evaluations until the stream completes, loading millions of rows in seconds.
Q5.What happens when an INSERT statement fails partway through a batch?
In standard relational engines, a SQL statement is atomic. If the 500th row in a 1,000-row batch violates a CHECK or UNIQUE constraint, the entire statement is aborted, and all 499 previously processed rows in that statement are rolled back. None of the rows remain in the table.
10. Interview-Ready Answer
“The INSERT statement writes new rows to a table. High-performance applications use multi-row batched inserts to minimize network latency and leverage the RETURNING clause to atomically capture database-generated keys.”
11. Quick Test
What happens if the 3rd row in a 5-row batch INSERT violates a UNIQUE constraint?