Sub topic 9
Inserting Rows
This chapter covers how INSERT works in PostgreSQL, how identity columns fill in keys for you, and the errors you will meet when a row breaks a rule. It assumes you have a running server, a psql session connected to firstdb, and the books table from the previous chapter. You should know what a column, a row, and a data type are.
What INSERT does
INSERT adds new rows to a table. You name the table, list the columns you want to fill, and supply a value for each one. PostgreSQL checks each row against the table's rules before it stores the row. The rules are the column types, the NOT NULL constraints, and the primary key. If any rule fails, the statement fails and no row from that statement is stored.
The basic form is:
INSERT INTO table_name (column1, column2)
VALUES (value1, value2);The column list and the value list match by position. The first value goes into the first column named, the second into the second, and so on.
Your first insert
Run this in psql while connected to firstdb:
INSERT INTO books (title, author, published_year)
VALUES
('Dune', 'Frank Herbert', 1965),
('Neuromancer', 'William Gibson', 1984),
('Emma', 'Jane Austen', 1815);psql replies with:
INSERT 0 3The 3 is the number of rows inserted. The 0 is a leftover field for an object ID that modern PostgreSQL no longer uses, so it is always 0.
A single statement with several value lists is called a multi-row insert. It is faster than three separate statements because the server parses and plans the work once. It is also atomic: either all three rows are stored or none are.
How the id column gets its value
You did not supply id, yet each row has one. The table was defined with this column:
id integer GENERATED ALWAYS AS IDENTITY PRIMARY KEYAn identity column is a column whose value PostgreSQL generates from an internal counter called a sequence. Each new row takes the next number from that counter. A primary key is a column, or set of columns, that must be unique and non-null in every row. Together they give each book a stable label that never repeats.
Check the result:
SELECT id, title FROM books ORDER BY id;You should see ids 1, 2, and 3.
GENERATED ALWAYS and manual ids
GENERATED ALWAYS means PostgreSQL refuses to accept a value you type for that column. Try it:
INSERT INTO books (id, title, author)
VALUES (100, 'Hyperion', 'Dan Simmons');The server answers with an error similar to this:
ERROR: cannot insert a non-DEFAULT value into column "id"
DETAIL: Column "id" is an identity column defined as GENERATED ALWAYS.
HINT: Use OVERRIDING SYSTEM VALUE to override.If you declared the column GENERATED BY DEFAULT AS IDENTITY instead, a manual id would be accepted. That is convenient when you load data from another system, but it can cause trouble later, as the next section shows.
Gaps and the sequence
The counter does not roll back. If an insert fails after taking a number, that number is lost. Run the failed insert above with a valid NOT NULL violation, then insert a good row, and you will see a gap in the ids. Gaps are normal. Do not rely on ids being consecutive, and do not use them to count rows. Use SELECT count(*) FROM books; for that.
If you use BY DEFAULT and insert explicit ids that the counter has not reached yet, the counter does not know about them. Later, it may generate the same number, and the primary key rejects the insert with a duplicate key error.
Column lists, defaults, and NULL
Columns you leave out of the column list receive their default value. If a column has no default, it receives NULL, which means "no value". In books, published_year has no default and allows NULL, so you can omit it:
INSERT INTO books (title, author)
VALUES ('Untitled Draft', 'Anonymous');Check it:
SELECT title, published_year FROM books WHERE title = 'Untitled Draft';psql shows an empty cell for published_year. You can also write NULL explicitly, or use the keyword DEFAULT to ask for the column's default:
INSERT INTO books (title, author, published_year)
VALUES ('Second Draft', 'Anonymous', DEFAULT);Always list the columns
PostgreSQL allows INSERT INTO books VALUES (...) with no column list. The values then map to every column in table order. Avoid this form. If someone adds a column later or the order changes, your statement either fails or silently puts values in the wrong columns. A named column list keeps the statement correct as the table evolves.
Quoting and escaping values
Text values use single quotes. Double quotes are for identifiers such as table and column names, so "title" refers to a column and 'title' is a string.
To put an apostrophe inside a string, double it:
INSERT INTO books (title, author, published_year)
VALUES ('Ender''s Game', 'Orson Scott Card', 1985);Numbers need no quotes. Putting quotes around a number usually still works, because PostgreSQL converts the string to the column type, but the habit hides mistakes.
Rules that reject a row
Each of these produces an error, and the statement stores nothing. Try them and read the messages.
| Mistake | Example | Error message begins |
|---|---|---|
| Missing a required column | `INSERT INTO books (title) VALUES ('X');` | `null value in column "author" ... violates not-null constraint` |
| Wrong data type | `... VALUES ('X', 'Y', 'soon');` | `invalid input syntax for type integer` |
| Count mismatch | `INSERT INTO books (title, author) VALUES ('X');` | `INSERT has more target columns than expressions` |
| Unknown column | `INSERT INTO books (name) VALUES ('X');` | `column "name" of relation "books" does not exist` |
| Duplicate key | A repeated primary key value | `duplicate key value violates unique constraint` |
Reading these messages is a skill worth building. The first line names the rule, and the lines after it (DETAIL) show the offending row or value.
Multi-row inserts are all or nothing
If one row in a multi-row insert is bad, the whole statement fails:
INSERT INTO books (title, author, published_year)
VALUES
('Good Book', 'Good Author', 2001),
(NULL, 'Bad Row', 2002);The second row violates NOT NULL on title, so Good Book is not stored either. Confirm with SELECT title FROM books WHERE title = 'Good Book';, which returns no rows.
Getting the new rows back with RETURNING
Often you need the generated id right after an insert. Add a RETURNING clause to get it in the same round trip:
INSERT INTO books (title, author, published_year)
VALUES ('Foundation', 'Isaac Asimov', 1951)
RETURNING id, title;The output looks like this:
id | title
----+------------
7 | Foundation
(1 row)
INSERT 0 1Your id may differ because of gaps. RETURNING works with multi-row inserts too and returns one line per inserted row. It is safer than inserting and then running a separate query to guess which row is yours, since another session may insert at the same time.
Transactions and undoing an insert
By default psql runs in autocommit mode. Each statement is its own transaction, and it is saved as soon as it succeeds. To try inserts you might want to discard, wrap them in a transaction:
BEGIN;
INSERT INTO books (title, author) VALUES ('Scratch', 'Tester');
SELECT count(*) FROM books;
ROLLBACK;
SELECT count(*) FROM books;The first count includes the scratch row. After ROLLBACK the second count does not. The identity counter still advances, which is another source of id gaps.
If a statement fails inside an explicit transaction, PostgreSQL marks the transaction as aborted. Every later command returns current transaction is aborted, commands ignored until end of transaction block until you run ROLLBACK. This catches many learners the first time.
How an insert flows
The diagram shows the checks a row passes before it is stored.
Common pitfalls
- Using ids as counts or ordering. Ids can have gaps and are not a record of insertion time. Use
count(*)and an explicit timestamp column if you need those. - Omitting the column list. The statement breaks or misplaces data when the table changes.
- Forgetting that a failed statement stores nothing. After an error in a multi-row insert, fix the bad row and re-run the whole statement.
- Running the same insert twice. The
bookstable has no uniqueness rule ontitle, so a second run creates duplicate books with new ids. Check withSELECT title, count(*) FROM books GROUP BY title HAVING count(*) > 1;.
Check your understanding
Exercise
You run this statement and the second row has a NULL title, which violates NOT NULL. How many of the two rows are stored, and why? INSERT INTO books (title, author) VALUES ('A', 'X'), (NULL, 'Y');
Show answer
Zero rows are stored. A single INSERT statement is atomic, so when one row breaks a constraint the server rejects the whole statement and keeps none of its rows.
Exercise
Write an INSERT that adds the book 'Solaris' by 'Stanislaw Lem' with no published year, and returns the generated id.
Show answer
INSERT INTO books (title, author) VALUES ('Solaris', 'Stanislaw Lem') RETURNING id; The omitted published_year becomes NULL, and RETURNING id sends back the identity value in the same statement.
Exercise
Why does INSERT INTO books (id, title, author) VALUES (50, 'X', 'Y'); fail on this table, and what are two ways to make an explicit id acceptable?
Show answer
The id column is GENERATED ALWAYS AS IDENTITY, which rejects manually supplied values. You can add OVERRIDING SYSTEM VALUE to the INSERT, or redefine the column as GENERATED BY DEFAULT AS IDENTITY. With BY DEFAULT, make sure the sequence is moved past any manual ids to avoid later duplicate key errors.