How do you add data with INSERT?
INSERT INTO table (columns) VALUES (…) adds rows: the named columns are filled, the rest get DEFAULT, and then the constraints are checked. The statement is atomic, so one bad row cancels the whole statement. Columns are listed explicitly and ids are not typed by hand, because the sequence knows nothing about them, and RETURNING in PostgreSQL returns the generated value. ON CONFLICT serves repeatable seeding.
SQL · Changing data and transactions
A test created a user through SQL and the next step needs its id. How do you get it in one statement?
A UI test needs a user with two accounts. Creating one through the sign-up form is slow, so QA inserts the data straight into the database. Two traps wait here: the id that must be passed to the next step, and data that later breaks other people's inserts. This lesson is about INSERT, RETURNING and why ids are not typed by hand.
How it works and why. In INSERT INTO table (columns) VALUES (…) the database fills the named columns, gives the rest their DEFAULT (for identity or serial it is the next number of the sequence, for the others NULL if there is no default), and then checks the constraints: NOT NULL, UNIQUE, FOREIGN KEY, CHECK. The statement is atomic: if the second of two rows violates a constraint, none is inserted. RETURNING returns the inserted rows with the generated values already in place (id, created_at), so no extra SELECT is needed.
Why columns are listed explicitly: without a list, values are matched by position. When a new column appears in the table, the statement either fails or silently puts values into the wrong columns of the same type.
Example: an id typed by hand. The users table holds ids 1 to 100, and id is serial (or GENERATED BY DEFAULT AS IDENTITY). QA inserts a test user with an invented id:
INSERT INTO users VALUES (101, 'qa_1@test.com', 'QA One', 'PL');
-- INSERT 0 1
-- later an ordinary sign-up in the application:
INSERT INTO users (email, name, country)
VALUES ('new@test.com', 'New', 'UA');
-- ERROR: duplicate key value violates unique constraint "users_pkey"
-- DETAIL: Key (id)=(101) already exists. (shortened)
The sequence knows nothing about the manual id: it stayed at 100, and the next sign-up gets 101. It is not QA's statement that fails but someone else's, later, and the cause is hard to find. The right way: omit the id and take the generated one through RETURNING.
INSERT INTO users (email, name, country)
VALUES ('qa_1@test.com', 'QA One', 'PL'),
('qa_2@test.com', 'QA Two', 'UA')
RETURNING id, email;
If the sequence stands at 100 and no row with id 101 exists yet, the result is:
| id | |
|---|---|
| 101 | qa_1@test.com |
| 102 | qa_2@test.com |
Two ways to insert a test user
Hand-written id, no column list
The sequence lags behind and someone else's insert fails with duplicate key. A column shift breaks the statement after a schema change.
Column list and RETURNING
The database issues the id and the test takes it from the result. The statement does not depend on the column order.
The second preparation step (accounts) does not need an id copy: in PostgreSQL RETURNING can be picked up in the same statement through a CTE.
WITH new_user AS (
INSERT INTO users (email, name, country)
VALUES ('qa_3@test.com', 'QA Three', 'PL')
RETURNING id
)
INSERT INTO accounts (user_id, currency, balance)
SELECT id, 'PLN', 0 FROM new_user;
For repeatable seeding there is ON CONFLICT (it needs a UNIQUE constraint on email): DO NOTHING skips a duplicate, DO UPDATE SET name = EXCLUDED.name updates the existing row. Note that for a skipped row RETURNING returns nothing, and the script must handle that. For thousands of rows, INSERT … SELECT … FROM generate_series(1, 1000) is handy.
Limits and alternatives. Syntax depends on the database: MySQL has no RETURNING (there is LAST_INSERT_ID()), SQL Server has OUTPUT inserted.id. The main limit of inserting around the application: it skips the business logic. A password without a hash, missing events and derived rows produce a state that never occurs in the system. When the real state matters, the user is created through the API or UI, and SQL is kept for states that cannot be reached otherwise.
Common mistakes.
- A manual id in a table with a sequence: the sequence lags and someone else's insert fails later. If it is already done, realign it with
setval. INSERTwithout a column list: after a schema change the values land in the wrong place.- Expecting the "good" rows of a multi-row insert to pass: one bad row cancels the whole statement.
ON CONFLICT DO NOTHINGwithout a check: the row may already exist with other values and the test works with the wrong data.- Inserting without a marker on a shared environment: later it is unclear which rows are yours.
Check yourself
A statement inserts two rows and the second email already exists in a table with UNIQUE. How many rows appear?
Answer
None. The statement is atomic: the duplicate key error cancels the first row too. For at least the first to pass you need separate statements or ON CONFLICT DO NOTHING.
After a manual INSERT with id 101, sign-up in the application fails with duplicate key. Why, and what to do?
Answer
The sequence stayed at 100 and issues 101, which is taken. Realign it: SELECT setval(pg_get_serial_sequence('users', 'id'), (SELECT max(id) FROM users));. In future do not set the id.
RETURNING returns the generated id. Middle/Senior: I do not write ids by hand: the sequence does not know about them, so my insert succeeds and someone else's sign-up fails later. The statement is atomic, so one bad row cancels all. For repeatable seeding I use ON CONFLICT, and for states where business logic matters I prefer creating through the API.