SQL Tutorial 0/85 lessons ~6 min read Lesson 10
INSERT Queries
INSERT adds new rows to a table.
Course progress0%
Focus
7 guided sections
Practice signal
Examples included
Career prep
Foundation builder
Introduction
INSERT adds new rows to a table. It is the most common write operation — every signup, order, like and message is an INSERT under the hood.
Beginner analogy: INSERT is writing a new row in a spreadsheet — except the database checks all your rules first.
Understanding the topic
Core concepts to understand:
INSERT INTO users(email, name) VALUES('a@b.com','Ana');- Bulk insert:
VALUES (...), (...), (...). RETURNING *in Postgres returns the inserted row (great for IDs).INSERT ... ON CONFLICThandles duplicates (Postgres) —ON DUPLICATE KEYin MySQL.- Always use parameterized queries from your app — never concatenate strings.
Syntax reference
Visual workflow / architecture:
bash
App ── INSERT INTO orders(...) VALUES(...) RETURNING id ──▶ DB│▼┌────────────────┐│ Constraint ││ checks (NN, FK)│├────────────────┤│ WAL write │├────────────────┤│ Row inserted │└────────────────┘◀────────── new id ──────────────────
Syntax Pattern
INSERT INTO <table> (<col1>, <col2>, ...) VALUES (<val1>, <val2>, ...) [, (<val1>, <val2>, ...)] -- optional bulk rows [RETURNING <columns>]; -- Postgres only
INSERT INTOTarget table that will receive the new row(s).(cols)Column list — order must match VALUES.VALUESOne tuple per row; repeat for bulk insert.RETURNINGReturns generated columns (e.g. id) without a second query.
Live Example
sql
INSERT INTO users (email, name, plan)VALUES ('ana@acme.io', 'Ana', 'pro')RETURNING id, created_at;
users (before)
| id | name | plan | |
|---|---|---|---|
| 1 | leo@acme.io | Leo | free |
| 2 | mia@acme.io | Mia | pro |
runs
users (after)
| id | name | plan | |
|---|---|---|---|
| 1 | leo@acme.io | Leo | free |
| 2 | mia@acme.io | Mia | pro |
| 3 | ana@acme.io | Ana | pro |
INSERT row
row added, constraints checked, WAL written
INSERT validates constraints, writes to the WAL, then appends the new row.
Real-world use
Every Stripe payment, GitHub commit comment and Uber ride event is one or more INSERTs wrapped in a transaction.
Best practices
- Always use parameterized queries — prevents SQL injection.
- Bulk-insert in batches of 100–1000 for speed.
- Use
RETURNINGto avoid a follow-up SELECT.
Common mistakes
- String-concat user input into INSERT — classic SQL injection.
- Inserting one-by-one in a loop — 100× slower than batch.
- Forgetting ON CONFLICT and crashing on duplicates.
Hands-on exercise
Interview preparation — practice these questions:
- Q1. Syntax to insert one row.
- Q2. How to insert many rows at once.
- Q3. What does RETURNING do?
- Q4. ON CONFLICT vs ON DUPLICATE KEY.
- Q5. Why parameterize all queries?
Ready to mark this lesson complete?Track your journey across the entire course.