Skip to content
Back to 50 Concepts
Topic 5 of 50foundationsBeginner

# 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.

Relational Invariant:Deterministic relational algebra contract evaluated by the Cost-Based Optimizer.

2. Explain Like I'm 5

Intuitive mental model for beginners

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 Trace
Interactive Engine Simulation

INSERT Statements Visual Simulator

Step 1 of 3
SQL>INSERT INTO users (username, email) VALUES ('lucky', 'lucky@test.com') RETURNING id, created_at;Active Input

Step 1: Input & Parsing Stage

Engine Action: Validate SQL syntax and resolve schema metadata for INSERT Statements
SQL Input

Initiating INSERT Statements

Schema Catalog

Checking Table Invariants

How the Database Executes This:

The database engine inspects active tables, verifies permissions, and prepares the physical operation.

💡 Loading a pallet: Put 50 boxes on one pallet and ship it across the warehouse once, rather than driving 50 individual round-trips.

4. Real-World Example

A registration service creates new user records and needs their newly generated primary key IDs immediately.

Inserted Rows
id (Auto)usernameemail
101luckylucky@example.com
102rahulrahul@example.com
Relational walkthrough: Using batch INSERT sends multiple rows in a single network round-trip.

5. SQL Syntax

ANSI SQL / PostgreSQL Dialect
Step 1: Single Row Insert with RETURNING
INSERT INTO users (username, email)
VALUES ('lucky', 'lucky@example.com')
RETURNING id, created_at;
Returns generated identity columns without a second SELECT query.
Step 2: Multi-row Batch Insert
INSERT INTO users (username, email) VALUES
  ('rahul', 'rahul@example.com'),
  ('amit', 'amit@example.com'),
  ('neha', 'neha@example.com');
Significantly faster than executing separate insert statements in a loop.
Step 3: INSERT INTO ... SELECT
INSERT INTO user_archives (id, email)
SELECT id, email FROM users WHERE is_active = FALSE;
Pulls data from one table directly into another entirely within engine memory.

6. Important Rules & Behaviors

RuleBehavioral Explanation
Column List MatchingValues in the VALUES list must align with the specified column order.
Default Value OmissionColumns with DEFAULT or IDENTITY constraints can be omitted from the insert column list.
Constraint ViolationsIf any single row in a multi-row insert violates a constraint, the entire statement is rolled back.
Batch insert network efficiencyInserting 1,000 rows in a single multi-row statement avoids 999 network round-trips and transaction commits.
Atomic UPSERT guaranteesON 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);
Caution: Extremely large batch inserts (e.g. 100,000 rows in one statement) can hit parameter limits or memory thresholds; batch in chunks of 1,000 to 5,000.

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

Scenario Question:

What happens if the 3rd row in a 5-row batch INSERT violates a UNIQUE constraint?

Select your answer: