SQL Practice Logo

SQLPractice Online

INSERT Patterns: Concept

Module: Data Modification & Transactions

INSERT adds new rows to tables. Key patterns: (1) Single INSERT: Adds 1 row, simple but slow for many rows. (2) Bulk INSERT: Adds multiple rows in 1 statement, 10-100x faster. (3) INSERT...SELECT: Copies data from query results, used for ETL/migrations. (4) RETURNING/OUTPUT: Returns inserted data without extra SELECT. (5) Bulk loading: COPY/LOAD DATA/BULK INSERT for fastest imports. Real-world: Shopify uses bulk inserts for flash sales (50K orders/min). Stripe uses RETURNING to get IDs (no extra SELECT). Amazon uses COPY for data warehouse (billions of rows). Trade-off: Single inserts are simple but slow. Bulk inserts are fast but require more memory.

**1. Single INSERT - Basic Pattern:**

Single INSERT adds one row at a time.

**Basic Syntax:**

```sql

-- Insert with all columns

INSERT INTO users (user_id, name, email, created_at)

VALUES (1, 'John Doe', 'john@example.com', NOW());

-- Insert without column list (must match all columns in order)

INSERT INTO users

VALUES (2, 'Jane Smith', 'jane@example.com', NOW());

-- Insert with DEFAULT values

INSERT INTO users (name, email, created_at)

VALUES ('Bob Wilson', 'bob@example.com', DEFAULT);

-- created_at uses column default

-- Insert with explicit DEFAULT keyword

INSERT INTO users (user_id, name, email, created_at)

VALUES (DEFAULT, 'Alice Brown', 'alice@example.com', NOW());

-- user_id uses auto-increment/sequence

```

**When to use Single INSERT:**

- Adding one record (user registration, single order)

- Interactive applications (form submissions)

- Low-volume operations (< 100 rows)

**Performance:**

- Each INSERT is separate transaction (slow)

- 1000 single inserts = 1000 transactions = slow

- Network round-trip for each INSERT

**Real-world: User registration**

- Single INSERT for new user

- Use RETURNING to get user_id

- Simple and clear for single records

**2. Bulk INSERT - Multiple Rows in One Statement:**

Bulk INSERT adds multiple rows in single statement (10-100x faster).

**Bulk INSERT Syntax:**

```sql

-- Insert multiple rows with multiple VALUES tuples

INSERT INTO products (name, price, category)

VALUES

('Laptop', 999.99, 'Electronics'),