INSERT
one row, many rows, INSERT ... SELECT, DEFAULT, and your first CREATE TABLE.
- address
- everything.writes.insert
- part
- part 5, changing data
- chapter
- chapter 1 of 10
- reading time
- 9 min
INSERT adds rows: name the columns, give the values, one row or many per statement. a column you leave out gets its DEFAULT, and a column with no default gets NULL. INSERT ... SELECT fills a table from a query.
ids come from a sequence, and a sequence never gives a number back: a failed or rolled-back insert leaves a gap.
the picture
you know how a spreadsheet lets you type into any empty cell, anywhere? a table doesn't. it has a fixed set of columns with types and rules, and the only way in is a whole row at a time.
think of a form at a counter. every box on the form is a column. some boxes are pre-filled (the defaults), some you must fill (NOT NULL), and the clerk stamps the number in the corner herself (the identity column). hand in a form with a required box empty and the whole form comes back, nothing filed.
- 1CREATE TABLE teas (
- 2 id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
- 3 name text NOT NULL,
- 4 origin text,
- 5 grams int NOT NULL DEFAULT 100
- 6)
| idint4 | nametext | origintext | gramsint4 |
|---|
a brand new table: four columns, no rows.
everything on this page runs on a real postgres in your browser, on a fresh copy of the database every time you press run. nothing you do here sticks, so go ahead and break things.
your first table
before you can insert, there has to be somewhere to insert into. this is the table from the figure:
CREATE TABLE teas (
id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name text NOT NULL,
origin text,
grams int NOT NULL DEFAULT 100
);four columns, read left to right: a name, a type, then the rules. id numbers itself and is the primary key. name has to be there. origin may be NULL. grams falls back to 100. (the rules themselves are a chapter of their own: NOT NULL, CHECK and UNIQUE.)
now one row. list the columns you're filling, then the values in the same order:
INSERT INTO teas (name, origin, grams) VALUES ('assam', 'india', 250);
SELECT * FROM teas ORDER BY id;| idint4 | nametext | origintext | gramsint4 |
|---|---|---|---|
| 1 | assam | india | 250 |
INSERT 0 1 is the command tag: 1 row inserted. the 0 is a leftover. it used to be the inserted row's oid, and tables haven't had oids since postgres 12, so it's always 0 now.
many rows, and defaults
one VALUES list can hold as many rows as you like, separated by commas. it's one statement, one round trip, and all or nothing:
INSERT INTO teas (name, origin) VALUES
('sencha', 'japan'),
('darjeeling', 'india'),
('rooibos', 'south africa');
SELECT * FROM teas ORDER BY id;| idint4 | nametext | origintext | gramsint4 |
|---|---|---|---|
| 1 | assam | india | 250 |
| 2 | sencha | japan | 100 |
| 3 | darjeeling | india | 100 |
| 4 | rooibos | south africa | 100 |
nobody said grams, so all three got 100. a column you leave out of the list gets its default, and a column without a default declared gets NULL. you can also ask for the default by name, with the keyword DEFAULT in the VALUES:
INSERT INTO teas (name, origin, grams) VALUES ('house blend', DEFAULT, DEFAULT);
SELECT * FROM teas WHERE name = 'house blend';| idint4 | nametext | origintext | gramsint4 |
|---|---|---|---|
| 5 | house blend | null | 100 |
origin has no default, so DEFAULT means NULL there. and NOT NULL is the box you must fill:
INSERT INTO teas (origin) VALUES ('china');the error even shows the row it refused: (6, null, china, 100). look at that 6. the id was already taken from the sequence before the NOT NULL check failed.
the numbers have gaps
-- the last id handed out was 5 (house blend). then the
-- insert without a name failed, and then:
BEGIN;
INSERT INTO teas (name, origin, grams) VALUES ('pu-erh', 'china', 357);
ROLLBACK;
INSERT INTO teas (name, origin, grams) VALUES ('oolong', 'taiwan', 50);
-- what id does oolong get?- 1INSERT INTO teas (name, origin, grams) VALUES ('pu-erh', 'china', 357)
| idint4 | nametext | origintext | gramsint4 |
|---|---|---|---|
| 1 | assam | india | 250 |
| 2 | sencha | japan | 100 |
| 3 | darjeeling | india | 100 |
| 4 | rooibos | south africa | 100 |
| 5 | house blend | null | 100 |
| 7 | pu-erh | china | 357 |
pu-erh goes in, and takes the next id from the sequence.
here it is for real. the insert that failed already ran, two blocks up (this page runs a session's blocks in order), so this picks up right after it:
BEGIN;
INSERT INTO teas (name, origin, grams) VALUES ('pu-erh', 'china', 357);
ROLLBACK;
INSERT INTO teas (name, origin, grams) VALUES ('oolong', 'taiwan', 50);
SELECT id, name FROM teas ORDER BY id;| idint4 | nametext |
|---|---|
| 1 | assam |
| 2 | sencha |
| 3 | darjeeling |
| 4 | rooibos |
| 5 | house blend |
| 8 | oolong |
ids are for telling rows apart, not for counting them. if you need "the 7th order this year" without holes, that's a number you compute (row_number()), not one you store. and if a gap in an id upsets a report, the report is wrong, not the id.
where ids come from
GENERATED ALWAYS AS IDENTITY is the standard spelling (SQL:2003), and postgres has had it since 10. older code uses serial, a postgres shorthand that creates a sequence and sets the column's default to nextval(...). the difference shows up the first time someone types an id by hand:
- 1CREATE TABLE kinds (id int GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name text);
- 2INSERT INTO kinds (id, name) VALUES (1, 'typed by hand');
- 3INSERT INTO kinds (name) VALUES ('from the sequence');
GENERATED ALWAYS: the identity column refuses a value you typed. the mistake is caught on the spot.
GENERATED ALWAYS catches the mistake when it's made. BY DEFAULT and serial catch it later, on somebody else's insert, as a duplicate key. (when you really do need to load ids by hand, say in a migration, OVERRIDING SYSTEM VALUE gets past ALWAYS, and then you move the sequence on with setval.)
this isn't hypothetical. shop's tables use BY DEFAULT, and customers go up to 2000. type in the next id yourself, and the next normal signup collides with you:
INSERT INTO customers (id, name, country, created_at)
VALUES (2001, 'Typed By Hand', 'GB', '2026-05-01 10:00+00');
INSERT INTO customers (name, country, created_at)
VALUES ('Next Signup', 'GB', '2026-05-01 10:05+00');identity columns and uuids has the rest: why serial is legacy, and keys that don't need a sequence at all.
INSERT ... SELECT
VALUES is one way to say "these rows". a query is the other. anything a SELECT returns can go straight into a table, as long as the columns line up. here's a table of shop's ten best customers, filled from a join in one statement:
CREATE TABLE vip (
customer_id int PRIMARY KEY REFERENCES customers,
spent numeric(12,2) NOT NULL
);
INSERT INTO vip (customer_id, spent)
SELECT o.customer_id, sum(oi.qty * oi.unit_price)
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.id
WHERE o.status <> 'cancelled'
GROUP BY o.customer_id
ORDER BY sum(oi.qty * oi.unit_price) DESC, o.customer_id
LIMIT 10;INSERT 0 10. the rows never left the database: no client fetched them and sent them back. that's why INSERT ... SELECT is the fast way to copy, reshape or archive data, and why a bulk load usually ends with one.
SELECT v.customer_id, c.name, v.spent
FROM vip AS v JOIN customers AS c ON c.id = v.customer_id
ORDER BY v.spent DESC, v.customer_id;| customer_idint4 | nametext | spentnumeric |
|---|---|---|
| 1 | Maya Chen | 26940.07 |
| 13 | Mei Kowalski | 17615.03 |
| 2 | Grace Okafor | 14950.61 |
| 8 | Sean O'Neil | 13456.09 |
| 4 | Zoë Martin | 13380.10 |
| 5 | Zoe Martin | 13158.45 |
| 3 | Sam Lee | 11298.06 |
| 1999 | Valentina Silva | 10852.84 |
| 119 | Leila Romano | 10576.20 |
| 16 | Elena Kelly | 10510.73 |
if the table doesn't exist yet, CREATE TABLE vip AS SELECT ... makes it and fills it in one go, with the columns the query returns (and no primary key, no constraints, no defaults: you add those after).
one level deeperwhat one INSERT does underneath
an INSERT finds a page with room for the row (the free space map knows), writes the row there with your transaction's id stamped in its header as xmin, adds an entry to every index on the table, and logs all of it to the WAL before COMMIT returns. the row exists on the page from the moment it's written; whether anyone else can see it depends on whether your transaction committed. one INSERT, all the way down follows a single row through every one of those steps.
keylines
- INSERT adds whole rows: name the columns, then give the values.
- a column you leave out gets its DEFAULT, or NULL if it has none.
- one statement is all or nothing, even with a thousand rows in VALUES.
- INSERT ... SELECT fills a table from a query without the rows ever leaving the database.
- prefer GENERATED ALWAYS AS IDENTITY over serial, and expect gaps in the ids.