Inserting Rows With INSERT: Values, Defaults and INSERT ... SELECT
How to add rows to a table with INSERT: listing columns, inserting several rows at once, defaults and the DEFAULT keyword, identity columns, constraint errors and all-or-nothing statements, type conversion, INSERT ... SELECT, CREATE TABLE AS, and bulk loading in each database.
kvi5hnuCode Sprout team member12 min readOn this page
So far, the course has only read data. Part 7 changes it, starting with INSERT, which adds new rows to a table. It's the simplest of the data-changing statements, but it has more details than it first appears: which columns get which values, what happens to the columns you leave out, what the database checks before accepting a row, and what happens when one row out of a hundred is invalid.
The examples run on the shop database from Part 3. Every example starts from a fresh copy, so the changes one example makes don't affect the next.
The basic INSERT
An INSERT names a table, a list of columns, and the values for those columns:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
\pset null '(null)'
-- One row, naming the columns
INSERT INTO products (product_id, name, category, brand, price, stock, weight_g)
VALUES (8, 'Trek poles', 'hiking', 'Alpina', 59.00, 18, 520);
-- Several rows in one statement; columns not listed get their default (here NULL)
INSERT INTO products (product_id, name, category, price, stock)
VALUES (9, 'Camp mug', 'kitchen', 9.50, 60),
(10, 'Spork', 'kitchen', 3.25, 120);
SELECT product_id, name, category, brand, price, stock, weight_g
FROM products
WHERE product_id >= 8
ORDER BY product_id;
product_id | name | category | brand | price | stock | weight_g
------------+------------+----------+--------+-------+-------+----------
8 | Trek poles | hiking | Alpina | 59.00 | 18 | 520
9 | Camp mug | kitchen | (null) | 9.50 | 60 | (null)
10 | Spork | kitchen | (null) | 3.25 | 120 | (null)
(3 rows)
- The column list after the table name says which columns the values are for. The values are matched to the columns by position: the first value goes into the first listed column, and so on. The number of values must equal the number of columns.
- One
VALUESclause can hold several rows, separated by commas. A multi-row insert is a single statement: it's faster than separate inserts, because the database processes the statement once and, outside an explicit transaction, commits once. - Columns that aren't in the list get their default value. The camp mug and spork don't list
brandandweight_g, which have no default, so they're NULL.
Strings and dates are written as literals, as in a WHERE clause: 'Camp mug', DATE '2026-05-01'.
Always list the columns
The column list is optional. Without it, you must supply a value for every column, in the order the table defines them:
INSERT INTO products VALUES (8, 'Trek poles', 'hiking', 'Alpina', 59.00, 18, 520);
This works, but it's fragile. If someone adds a column to the table, or the columns are in a different order in another environment, the statement fails or, worse, puts values in the wrong columns without any error when the types happen to be compatible. Swapping stock and weight_g, both integers, would be accepted silently.
Listing the columns makes the statement independent of the table's column order, documents what each value means, and lets you leave out columns that should get their defaults. Treat it as a rule for any INSERT in application code or scripts.
Defaults, DEFAULT and identity columns
A column's default is set when the table is created (article 52), with a DEFAULT clause. Without one, the default is NULL. The default is used when a column is left out of the column list, or when you write the keyword DEFAULT in place of a value:
\pset null '(null)'
CREATE TABLE stock_moves (
move_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
product_id INTEGER NOT NULL,
qty INTEGER NOT NULL DEFAULT 1,
reason VARCHAR(20) NOT NULL DEFAULT 'restock',
note TEXT
);
INSERT INTO stock_moves (product_id) VALUES (3); -- all defaults
INSERT INTO stock_moves (product_id, qty, reason) VALUES (5, -2, 'sale');
INSERT INTO stock_moves (product_id, qty, reason, note)
VALUES (7, DEFAULT, DEFAULT, 'count correction'); -- DEFAULT keyword
SELECT * FROM stock_moves ORDER BY move_id;
-- An identity column declared GENERATED ALWAYS rejects explicit values
INSERT INTO stock_moves (move_id, product_id) VALUES (99, 1);
move_id | product_id | qty | reason | note
---------+------------+-----+---------+------------------
1 | 3 | 1 | restock | (null)
2 | 5 | -2 | sale | (null)
3 | 7 | 1 | restock | count correction
(3 rows)
psql:/workspace/solution.sql:19: ERROR: cannot insert a non-DEFAULT value into column "move_id"
DETAIL: Column "move_id" is an identity column defined as GENERATED ALWAYS.
HINT: Use OVERRIDING SYSTEM VALUE to override.

move_idis an identity column: the database generates the next number from a sequence (article 54 covers identity columns and sequences). It's declaredGENERATED ALWAYS, so supplying a value is an error. PostgreSQL's hint mentionsOVERRIDING SYSTEM VALUE, which is meant for special cases such as copying data between databases.GENERATED BY DEFAULTwould allow explicit values.- The first insert gives only
product_id, soqtygets 1 andreasongets'restock'from their defaults, andnotegets NULL. - The third insert uses the keyword
DEFAULTforqtyandreason. It's useful when a statement lists a column but wants its default for some rows.
To insert a row made entirely of defaults, PostgreSQL, SQL Server and SQLite have INSERT INTO t DEFAULT VALUES. MySQL uses INSERT INTO t () VALUES ().
A default doesn't override an explicit NULL. INSERT INTO stock_moves (product_id, note) VALUES (3, NULL) stores NULL in note, and VALUES (3, NULL) for qty would be rejected by its NOT NULL constraint, even though qty has a default.
What the database checks
Before a row is stored, the database checks it against the table's constraints. If any check fails, the statement is rejected:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
CREATE TABLE ratings (
product_id INTEGER NOT NULL REFERENCES products (product_id),
customer_id INTEGER NOT NULL,
stars INTEGER NOT NULL CHECK (stars BETWEEN 1 AND 5),
PRIMARY KEY (product_id, customer_id)
);
INSERT INTO ratings VALUES (1, 1, 5);
INSERT INTO ratings VALUES (1, 1, 4); -- same key again
INSERT INTO ratings VALUES (42, 1, 4); -- no product 42
INSERT INTO ratings VALUES (2, 1, 9); -- breaks the CHECK
INSERT INTO ratings VALUES (2, 1, NULL); -- breaks NOT NULL
-- A multi-row insert is all or nothing: the second row fails, so neither is added
INSERT INTO ratings VALUES (3, 2, 4), (3, 2, 5);
SELECT * FROM ratings;
psql:/workspace/solution.sql:70: ERROR: duplicate key value violates unique constraint "ratings_pkey"
DETAIL: Key (product_id, customer_id)=(1, 1) already exists.
psql:/workspace/solution.sql:71: ERROR: insert or update on table "ratings" violates foreign key constraint "ratings_product_id_fkey"
DETAIL: Key (product_id)=(42) is not present in table "products".
psql:/workspace/solution.sql:72: ERROR: new row for relation "ratings" violates check constraint "ratings_stars_check"
DETAIL: Failing row contains (2, 1, 9).
psql:/workspace/solution.sql:73: ERROR: null value in column "stars" of relation "ratings" violates not-null constraint
DETAIL: Failing row contains (2, 1, null).
psql:/workspace/solution.sql:76: ERROR: duplicate key value violates unique constraint "ratings_pkey"
DETAIL: Key (product_id, customer_id)=(3, 2) already exists.
product_id | customer_id | stars
------------+-------------+-------
1 | 1 | 5
(1 row)
The four errors show the four common constraints:
| Constraint | Rejects |
|---|---|
PRIMARY KEY / UNIQUE | a row whose key already exists |
FOREIGN KEY | a reference to a row that doesn't exist in the parent table |
CHECK | a row for which the condition is false (but not unknown) |
NOT NULL | a NULL in the column |
The last insert shows something just as important: a statement is atomic. Its two rows have the same key, so the second one fails, and then the first one isn't inserted either. A statement either completes fully or has no effect. The final SELECT shows only the rating inserted at the start.
This matters when loading data. One bad row in a 10,000-row insert rejects all 10,000 rows. You can then fix the data and rerun, insert the rows one by one and skip the failures, or use an "insert or ignore" form, which article 34 covers with upserts.
Article 60 explains transactions, which extend the same all-or-nothing behaviour to several statements.
Types and conversions
Each value must be convertible to its column's type:
CREATE TABLE tags (
tag_id INTEGER PRIMARY KEY,
label VARCHAR(8) NOT NULL,
weight DECIMAL(5, 2)
);
-- Without a column list, values must match the table's column order exactly
INSERT INTO tags VALUES (1, 'outdoor', 1.5);
-- The values are in the wrong order: 'camping' can't become an integer
INSERT INTO tags VALUES ('camping', 2, 2.0);
-- Quoted numbers are converted; extra decimals are rounded
INSERT INTO tags (tag_id, label, weight) VALUES ('2', 'camping', 2.005);
-- Too long for VARCHAR(8): an error, not silent truncation
INSERT INTO tags (tag_id, label) VALUES (3, 'waterproof');
SELECT * FROM tags ORDER BY tag_id;
psql:/workspace/solution.sql:11: ERROR: invalid input syntax for type integer: "camping"
LINE 1: INSERT INTO tags VALUES ('camping', 2, 2.0);
^
psql:/workspace/solution.sql:17: ERROR: value too long for type character varying(8)
tag_id | label | weight
--------+---------+--------
1 | outdoor | 1.50
2 | camping | 2.01
(2 rows)
- The second insert lists no columns and gives the values in the wrong order.
'camping'can't become the integertag_id, so it fails. With compatible types, the same mistake would succeed and store wrong data. '2'is a string, but PostgreSQL converts it to the integer 2 for thetag_idcolumn. A quoted literal is converted to the column's type if its text is a valid value of that type.2.005is rounded to2.01to fitDECIMAL(5, 2). Most databases round extra decimals. A value with too many digits before the decimal point is an error.'waterproof'is 10 characters, andlabelisVARCHAR(8), so PostgreSQL rejects it rather than cutting it short.
Other databases are less strict:
- MySQL in its default strict mode also rejects values that are too long or invalid. With strict mode turned off (
sql_mode = '', still found in old applications), it stores'waterpro'and turns'camping'into 0 for an integer column, with only a warning. Never turn strict mode off. - SQLite doesn't enforce lengths: a
VARCHAR(8)column stores'waterproof'in full. It also stores'camping'in an ordinaryINTEGERcolumn as text (anINTEGER PRIMARY KEYcolumn is the exception: it rejects non-integers), because SQLite's types are affinities rather than rules. Declare tablesSTRICT(SQLite 3.37+) to make it reject values of the wrong type. - SQL Server raises "String or binary data would be truncated", and since SQL Server 2019 names the column and value.
INSERT ... SELECT
Instead of VALUES, an INSERT can take its rows from a query. Every row the query returns is inserted:
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
CREATE TABLE order_archive (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER,
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL,
order_value DECIMAL(10, 2)
);
-- Copy the result of a query, computing a column on the way
INSERT INTO order_archive (order_id, customer_id, placed_on, status, order_value)
SELECT o.order_id, o.customer_id, o.placed_on, o.status,
SUM(oi.qty * oi.unit_price)
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
WHERE o.status IN ('delivered', 'cancelled')
GROUP BY o.order_id, o.customer_id, o.placed_on, o.status;
SELECT * FROM order_archive ORDER BY order_id;
-- Create and fill a table in one step: CREATE TABLE ... AS
CREATE TABLE pune_customers AS
SELECT customer_id, name
FROM customers
WHERE city = 'Pune';
SELECT * FROM pune_customers ORDER BY customer_id;
order_id | customer_id | placed_on | status | order_value
----------+-------------+------------+-----------+-------------
103 | 1 | 2026-03-09 | delivered | 154.45
105 | 4 | 2026-03-20 | cancelled | 54.00
(2 rows)
customer_id | name
-------------+----------
1 | Asha Rao
3 | Chen Wei
(2 rows)
INSERT ... SELECT copies, transforms and summarises data in one statement, without sending rows to the application and back. Here it archives the delivered and cancelled orders with their computed value. The query can be anything a SELECT can be: joins, grouping, CTEs and window functions. Its columns are matched to the column list by position, not by name, so the column list and the select list must be in the same order.
Typical uses:
- copying rows to an archive or history table before deleting them (article 33)
- filling a summary or reporting table
- loading data from a staging table after cleaning it
- duplicating rows with changes, such as copying last year's price list as this year's
CREATE TABLE ... AS SELECT (often called CTAS) creates a new table from a query's result and fills it in one step. The new table gets the query's column names and types, but no constraints: no primary key, foreign keys, indexes or (in PostgreSQL) defaults and NOT NULL constraints. MySQL and Oracle keep NOT NULL. It's handy for quick copies and scratch tables, but define permanent tables with CREATE TABLE and fill them with INSERT ... SELECT.
SQL Server uses SELECT ... INTO new_table FROM ... instead of CREATE TABLE AS. PostgreSQL also accepts SELECT ... INTO, but CREATE TABLE AS is the standard and recommended form.
Bulk loading
INSERT statements are fine for thousands of rows. For millions, such as loading a CSV export or a data warehouse feed, every database has a faster bulk-loading command that skips most of the per-statement work:
| Database | Bulk load |
|---|---|
| PostgreSQL | COPY table FROM 'file' on the server, or \copy in psql for a client-side file |
| MySQL | LOAD DATA [LOCAL] INFILE 'file' INTO TABLE table |
| SQL Server | BULK INSERT, or the bcp utility |
| Oracle | SQL*Loader, or external tables |
| SQLite | .import file table in the sqlite3 shell |
When you must use INSERT, a few habits make large loads much faster:
- Put many rows in each statement, for example 1,000 rows per
VALUESlist. SQL Server allows at most 1,000 rows in a singleVALUESlist. - Wrap many statements in one transaction, rather than committing every row.
- In application code, use prepared statements with parameters (article 59), which are faster and protect against SQL injection. Never build
INSERTstatements by joining strings.
INSERT in other databases
The basic statement is the same everywhere. The main differences:
- Multi-row
VALUESis supported by PostgreSQL, MySQL, SQL Server 2008+, SQLite 3.7.11+ and Oracle 23ai. Older Oracle versions useINSERT ALL INTO t VALUES (...) INTO t VALUES (...) SELECT * FROM dual, orINSERT ... SELECT ... UNION ALL .... - Getting generated keys back: PostgreSQL, SQLite 3.35+ and MariaDB have
RETURNING, SQL Server hasOUTPUT, and MySQL hasLAST_INSERT_ID(). Article 34 covers them. - Ignoring duplicates: MySQL has
INSERT IGNORE, SQLiteINSERT OR IGNORE, and PostgreSQLON CONFLICT DO NOTHING(article 34).
Inserting into several tables at once
Oracle can send each row of one query to several tables, or to one of several, with a single statement:
-- Oracle: route each row to a table chosen by a condition
INSERT FIRST
WHEN amount >= 1000 THEN INTO large_orders (order_id, amount) VALUES (order_id, amount)
WHEN amount >= 100 THEN INTO medium_orders (order_id, amount) VALUES (order_id, amount)
ELSE INTO small_orders (order_id, amount) VALUES (order_id, amount)
SELECT order_id, amount FROM staged_orders;
INSERT FIRST uses the first matching WHEN for each row, and INSERT ALL inserts into every table whose condition matches. Other databases need one INSERT ... SELECT ... WHERE per table, inside a transaction. PostgreSQL can also do it in one statement with data-modifying CTEs (article 24), each inserting the rows its condition selects.
What's current
- Oracle 23ai added multi-row
VALUESlists, the last major database to support them. - SQLite 3.37 added
STRICTtables, which enforce column types. - SQL Server 2019 improved the truncation error message to name the table, column and value that didn't fit.
- PostgreSQL 17 added the
ON_ERROR ignoreoption toCOPY, which skips rows with conversion errors instead of failing the whole load.
Common questions
Do I have to list the columns? No, but you should. Without a column list, you must give every column in table order, and the statement breaks or stores wrong data when the table changes.
What value does a column get if I leave it out? Its default, which is NULL unless the table defines another default or the column is an identity or generated column.
What happens if one row of a multi-row insert fails? The whole statement fails, and none of its rows are inserted.
Is INSERT ... SELECT faster than inserting row by row?
Yes, much faster. The data stays inside the database and the statement runs once.
Does CREATE TABLE AS copy indexes and constraints?
No. It copies only column names, types and data. Add keys, constraints and indexes separately.
Can I insert into a view? Into a simple view over one table, yes, in most databases. Article 56 covers updatable views.
How do I get the ID of the row I just inserted?
With RETURNING in PostgreSQL and SQLite, OUTPUT in SQL Server, or LAST_INSERT_ID() in MySQL. See article 34.
Summary
INSERT INTO table (columns) VALUES (values)adds rows. Values match the listed columns by position.- One
VALUESclause can hold several rows, and the statement is all or nothing. - Columns left out get their default, which is NULL unless defined otherwise. The keyword
DEFAULTasks for it explicitly. Identity columns generate their own values. - Every row is checked against
NOT NULL,CHECK,UNIQUE/PRIMARY KEYandFOREIGN KEYconstraints. - Values are converted to the column types. PostgreSQL, SQL Server and MySQL's strict mode reject values that don't fit. SQLite doesn't, unless the table is
STRICT. INSERT ... SELECTinserts a query's result.CREATE TABLE ... AS SELECTcreates and fills a table, without constraints.- For very large loads, use the database's bulk loader, such as
COPYorLOAD DATA.
Practice questions
Write a statement that adds two customers, Gita Shah from Pune referred by Asha (1), and Hugo Lind from York with no referrer, with IDs 7 and 8.
Answer
INSERT INTO customers (customer_id, name, city, referred_by)
VALUES (7, 'Gita Shah', 'Pune', 1),
(8, 'Hugo Lind', 'York', NULL);
You could also leave referred_by out of the list for Hugo, but both rows share one column list, so NULL is written explicitly.
A table has status VARCHAR(10) NOT NULL DEFAULT 'new'. What happens with INSERT INTO t (id, status) VALUES (1, NULL)?
Answer
It fails with a NOT NULL violation. The default is used only when the column is left out or written as DEFAULT, not when you supply NULL explicitly.
Write an INSERT ... SELECT that copies every product in the packs category into a table packs_copy(product_id, name, price), raising the price by 10%.
Answer
INSERT INTO packs_copy (product_id, name, price)
SELECT product_id, name, ROUND(price * 1.10, 2)
FROM products
WHERE category = 'packs';
The two backpacks are inserted with prices 98.95 and 59.40.
A 500-row INSERT fails because row 312 has a duplicate primary key. How many rows were inserted?
Answer
None. A statement is atomic, so the failure undoes the rows already inserted by the same statement. Fix or remove row 312 and rerun, or use an insert-or-ignore form such as ON CONFLICT DO NOTHING if duplicates should be skipped.
Why might INSERT INTO products VALUES (11, 'Bivvy bag', 'shelter', 'Alpina', 79.00, 450, 6) store wrong data without any error?
Answer
Without a column list, the values go to the columns in table order: price, stock, weight_g. If the intent was stock 6 and weight 450 g but the values were swapped, both are integers, so the database accepts the row. Listing the columns makes such mistakes visible.
Previous: Gaps and Islands: Finding Consecutive Ranges and Missing Values
Next: Updating Rows With UPDATE: Expressions, Subqueries and Joins

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.