advanced
INSERT
Add new rows to a table with INSERT INTO — single rows, multiple rows, and from a query.
5 min read
Explanation
INSERT adds new rows to a table. You specify the target columns and the values
for each new row. If you omit a column, it gets its default (or NULL if allowed).
There are three common shapes:
- One row:
INSERT INTO t (cols) VALUES (...) - Many rows: multiple
VALUEStuples in one statement - From a query:
INSERT INTO t (cols) SELECT ...to copy filtered data
Always name your columns
Listing columns explicitly makes your INSERT resilient to table changes (new columns won't break it) and makes the intent obvious.
Syntax
INSERT INTO products (name, category, price, stock)
VALUES ('Desk Mat', 'Stationery', 11.99, 200);
-- Multiple rows:
INSERT INTO products (name, category, price, stock)
VALUES
('Webcam Cover', 'Electronics', 4.99, 500),
('Pen Refill', 'Stationery', 2.49, 800);
-- From a query:
INSERT INTO products_archive (name, price)
SELECT name, price FROM products WHERE stock = 0;Interactive Example
Because this sandbox is read-only you can't persist inserts, but you can preview
the exact row an INSERT would create using SELECT with literal values.
Loading database engine...
Loading database engine...
Common Mistakes
- Mismatched column/value counts. The number of columns must equal the number of values, or the statement fails.
- Forgetting NOT NULL columns. Omitting a column that disallows NULL and has no default triggers an error.
- Relying on column order. Inserting without naming columns depends on the table's physical order — brittle and error-prone.
Best Practices
- Name every column you're inserting to keep queries robust.
- Batch multiple rows into one
INSERTfor big loads. - Use
INSERT ... SELECTto copy data between tables in a single step. - Wrap bulk inserts in a transaction so you can roll back on error.
Practice Question
Write an INSERT that adds two new products rows (a 'Furniture' item priced
99.99 with stock 50, and a 'Stationery' item priced 3.99 with stock 300), naming
all four columns explicitly.
Summary
INSERT INTO adds rows, with columns named explicitly for safety. Insert one or
many rows, or copy from a SELECT. Always match column count to value count and
respect NOT NULL constraints.