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:
INSERTINTO users VALUES (101, 'qa_1@test.com', 'QA One', 'PL');
-- INSERT 0 1-- later an ordinary sign-up in the application:INSERTINTO 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.
What: the primary key users_pkey is violated. But this INSERT gives no id, so the sequence issued it, and the error looks like somebody else's.
Which key:DETAIL names id = 101. A row with 101 already exists: it was inserted by hand once, and the sequence reached the same number.
What to do
Find the row inserted with a manual id and move the sequence above the maximum id. In future do not give an id in test inserts.
Figure 2. The PostgreSQL message from the example (shortened): the numbers lead to the explanations.
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 (
INSERTINTO users (email, name, country)
VALUES ('qa_3@test.com', 'QA Three', 'PL')
RETURNING id
)
INSERTINTO accounts (user_id, currency, balance)
SELECT id, 'PLN', 0FROM 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.
INSERT without 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 NOTHING without 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.
Related lessons: “How do you run UPDATE and DELETE safely?”, “What is a transaction and how does QA use it?”, “How do you prepare and clean up test data with SQL?”.
In an interview.Junior: INSERT adds rows. I list the columns explicitly so the statement does not depend on the column order, and I can insert several rows at once. In PostgreSQL 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.
How do you run UPDATE and DELETE safely?
UPDATE and DELETE change every row selected by WHERE, and without WHERE the whole table, and the database does not ask for confirmation. The safe habit is a SELECT with the same WHERE first, then the change inside BEGIN, a check of the row count against the command tag, and only then COMMIT, or ROLLBACK on a mismatch. Clients usually run in autocommit, so without BEGIN the change cannot be undone.
SQL · Changing data and transactions
Someone ran UPDATE accounts SET status = 'blocked' and forgot WHERE. How many accounts are blocked?
On a shared environment QA wants to block two accounts of user 42 to see the error screen. A condition is missing and every account is blocked. There is no undo, because the client works in autocommit mode. This lesson is about a habit that makes such mistakes visible before the commit.
How it works and why.UPDATE and DELETE pick rows by WHERE and change every picked row. Without WHERE every row is picked. The database does not ask for confirmation: it is the same operation as for one row. The only signal after execution is the command tag with a count: UPDATE 3. After that autocommit applies: psql and most GUI clients commit every statement at once, so only what runs inside BEGIN can be rolled back. One more consequence: changed rows stay locked until the end of the transaction, and a colleague updating the same row will wait.
The data that shows the difference (the accounts table before the change: accounts 7 and 8 belong to user 42, account 9 to user 43, all with status active).
The same UPDATE without WHERE and with WHERE
Without WHERE: UPDATE 3
id
user_id
status
7
42
blocked
8
42
blocked
9
43
blocked extra
WHERE user_id = 42: UPDATE 2
id
user_id
status
7
42
blocked
8
42
blocked
9
43
active
Figure 1. The difference shows in the command tag: 3 instead of the expected 2.
The habit in four steps:
-- 1. what we will touch: expect 2 rows (7 and 8)SELECT id, user_id, status FROM accounts WHERE user_id = 42;
BEGIN; -- 2.UPDATE accounts SET status = 'blocked'WHERE user_id = 42RETURNING id, status; -- 3. shows what changed-- UPDATE 2 <- matches the expectationCOMMIT; -- 4. or ROLLBACK;
If the tag shows UPDATE 3, run ROLLBACK and nobody sees the change. The same goes for DELETE … RETURNING *: the returned rows stay as evidence and as a source for restoring. For bigger changes, a copy can be made beforehand: CREATE TEMP TABLE bak_accounts AS SELECT * FROM accounts WHERE user_id = 42; (a temporary table disappears with the session, so for longer storage use a regular table with the date in its name).
Deleting has one more trap: related rows. DELETE FROM users WHERE id = 42 either fails with a foreign key error (update or delete on table "users" violates foreign key constraint …) or, if the relation is declared with ON DELETE CASCADE, silently deletes the accounts too. Before deleting, check the child tables with the same SELECT.
Limits and alternatives. A transaction does not save you from a change you have already committed. MySQL has the sql_safe_updates guard, which rejects UPDATE and DELETE without a key in WHERE or a LIMIT; PostgreSQL has no such mode. Turning autocommit off helps: \set AUTOCOMMIT off in psql, manual-commit mode in GUI clients. Then every change waits for an explicit COMMIT, but a forgotten COMMIT becomes a problem of its own (see mistakes).
Common mistakes.
Running a change without BEGIN and learning about the error from the tag after the commit.
WHERE user_id = 42 OR status = 'active': OR widens the choice to every active row. When mixing AND and OR, add parentheses.
The condition status <> 'blocked' will not touch rows with status = NULL: a comparison with NULL is not true.
A forgotten open BEGIN: rows stay locked and others' updates hang. Such sessions show in pg_stat_activity with the state idle in transaction.
Checking the count only by eye: compare the number with the one expected from step 1.
Check yourself
The SELECT from step 1 showed 2 rows and the UPDATE inside the transaction returned UPDATE 3. What to do?
Answer
ROLLBACK and investigate. The conditions in SELECT and UPDATE may have diverged, or someone added a row in between. A count mismatch must not be committed.
In psql without BEGIN, an UPDATE ran with the tag UPDATE 3 instead of 2. Will ROLLBACK help?
Answer
No. Autocommit has already committed the change, and ROLLBACK only warns that there is no transaction. You have to restore from a copy or a backup, so the copy is needed before the change.
Related lessons: “How do you add data with INSERT?”, “What is a transaction and how does QA use it?”, “What happens to child records when a parent is deleted?”.
In an interview.Junior: UPDATE and DELETE without WHERE change the whole table. So I first write a SELECT with the same WHERE, then run the change in a transaction, check the row count and only then COMMIT. Middle/Senior: I know the client works in autocommit by default, so without BEGIN there is no rollback. I use RETURNING as evidence of the change, copy the rows before a large change, watch cascades and NULL in the condition, and never leave open transactions, because they hold locks.
How do DELETE, TRUNCATE and DROP differ?
DELETE removes rows by condition, TRUNCATE quickly empties the whole table, and DROP removes the table with its structure. TRUNCATE fires no row triggers, takes an ACCESS EXCLUSIVE lock in PostgreSQL and does not reset the id counter without RESTART IDENTITY. It can be rolled back in PostgreSQL but not in MySQL and Oracle. CASCADE empties dependent tables too.
SQL · Changing data and transactions
The environment must be cleared before a run. TRUNCATE fails and CASCADE supposedly fixes everything. What else will it wipe?
Before a regression run the orders table must be cleared. The first attempt, TRUNCATE orders, fails with an error and the hint suggests CASCADE. Three commands remove data in different ways: rows, all rows or the whole table, and the difference concerns speed, locks, id counters and related tables.
How it works and why.DELETE processes rows one by one under the WHERE condition, fires row triggers, returns the number of deleted rows and locks only those rows. In PostgreSQL the deleted row versions remain as "dead" until VACUUM cleans them, so a big delete is slow and bloats the table. TRUNCATE does not walk the rows but replaces the table storage with an empty one: it is almost instant regardless of size. There is no condition and no row triggers (ON TRUNCATE triggers exist), but the strongest lock, ACCESS EXCLUSIVE, is taken and blocks even reads. DROP TABLE removes the table itself: data, structure, indexes.
DELETE
TRUNCATE
DROP
What it removes
Rows by condition
All rows
The whole table
WHERE
Yes
No
No
Lock
Row-level
ACCESS EXCLUSIVE
ACCESS EXCLUSIVE
Row triggers
Fire
No
No
Rollback before COMMIT
Yes
PostgreSQL, SQL Server: yes. MySQL, Oracle: no
PostgreSQL: yes. MySQL, Oracle: no
Id counter
Not reset
PostgreSQL: only with RESTART IDENTITY; MySQL resets
Gone with the table
For PostgreSQL the next insert behaves as follows (the last id was 1000):
Cleared with
Next id
DELETE FROM orders
1001
TRUNCATE orders
1001
TRUNCATE orders RESTART IDENTITY
1
A test expecting "the first order has id 1" depends on how the table was cleared.
Example: TRUNCATE and related tables. The order_items table references orders through a foreign key.
TRUNCATE orders;
-- ERROR: cannot truncate a table referenced in a foreign key constraint-- DETAIL: Table "order_items" references "orders". (shortened)TRUNCATE orders CASCADE;
-- NOTICE: truncate cascades to table "order_items"
The error protects: an empty parent table would leave items without orders. CASCADE "fixes" it by clearing order_items too, and every table that references it further down the chain. On a shared environment that is other people's data. The right options depend on the environment:
-- own environment: both tables togetherTRUNCATE orders, order_items RESTART IDENTITY;
-- shared: only your own rows, children firstDELETEFROM order_items
WHERE order_id IN (SELECT id FROM orders WHERE user_id = 42);
DELETEFROM orders WHERE user_id = 42;
Clearing orders: two approaches
Wrong
TRUNCATE orders CASCADE
Clears order_items too, and every table further down the chain. On a shared environment other people's data vanishes, and the lock during the command affects everyone.
Right
DELETE children, then parents, by condition
Touches only your rows, returns a count, rolls back until COMMIT, and the locks are row-level.
Figure 1. CASCADE extends the command to tables you may not have thought about.
Reading the error: TRUNCATE of a parent table
TRUNCATE orders;
1ERROR: cannot truncate a table referenced in a foreign key constraint2DETAIL: Table "order_items" references "orders".
3HINT: Truncate table "order_items" at the same time, or use TRUNCATE ... CASCADE.
What:TRUNCATE refused because a foreign key references the table. This is protection, not a failure.
Who references it:DETAIL names the child table that would have to be cleared too.
Hint: the database offers two ways out: truncate order_items in the same command or use CASCADE. The second is the shortest but also the most dangerous: it clears every table that references further down the chain.
What to do
In your own environment clear both tables together: TRUNCATE orders, order_items. In a shared one delete only your own rows: children first, then parents.
Figure 2. The PostgreSQL message from the example (shortened): the numbers lead to the explanations.
Limits and alternatives. In MySQL and Oracle TRUNCATE and DROP are not rollback-friendly: they are DDL with an implicit commit. On small tables DELETE without WHERE is often enough and gives a rollback in any database. Test isolation can be built differently: a separate schema or database per run, per-test data with its own marker, a transaction rolled back after the test.
Common mistakes.
TRUNCATE … CASCADE "to make it pass": more is cleared than intended.
TRUNCATE on a table someone else's test is reading right now: the command waits for the lock or blocks others itself.
Expecting a TRUNCATE rollback in MySQL.
Forgetting that ids continue after DELETE while the test expects id 1.
DELETE of millions of rows in one statement: a long transaction and a bloated table. Delete in batches or use TRUNCATE where allowed.
Check yourself
Why does TRUNCATE orders fail when order_items references orders, and why is that no reason to add CASCADE at once?
Answer
An empty parent table would leave items without orders, so PostgreSQL refuses. CASCADE clears the child tables and anything that references them further. First find out which tables they are and whether they are yours.
The table was cleared, a row was inserted and its id is 1001 while the test expected 1. What to change?
Answer
The clearing was DELETE or TRUNCATE without RESTART IDENTITY: the sequence continued. Better still, do not depend on the id value: the test should take the id from RETURNING.
Related lessons: “How do you run UPDATE and DELETE safely?”, “What to check before DELETE, TRUNCATE or DROP?”, “What happens to child records when a parent is deleted?”.
In an interview.Junior: DELETE removes rows by condition and rolls back inside a transaction. TRUNCATE quickly clears the whole table with no condition, and DROP removes the table with its structure. Middle/Senior: TRUNCATE does not walk rows, does not fire row triggers, takes ACCESS EXCLUSIVE and does not reset the sequence without RESTART IDENTITY. In PostgreSQL it can be rolled back, in MySQL and Oracle it cannot. CASCADE extends the effect to dependent tables, so on a shared environment I use DELETE by condition and leave TRUNCATE for my own environment.
What is a transaction and how does QA use it?
A transaction runs several operations as one: either all changes are applied or none. BEGIN opens it, COMMIT persists the changes, ROLLBACK cancels them, and without BEGIN every statement is a transaction of its own (autocommit). QA uses a transaction as insurance for its own changes and as a subject for testing failures between steps. In PostgreSQL an error makes the transaction aborted until ROLLBACK, and id sequences are not rolled back.
SQL · Changing data and transactions
A transfer of 100: the debit went through and the credit failed. Where is the money now?
A transfer consists of two updates: minus on one account, plus on another. If the credit fails and the debit stays, the money has vanished. A transaction guarantees that either both changes happen or neither. QA uses it in two ways: as insurance for its own changes and as a subject of testing.
How it works and why.BEGIN opens a transaction, COMMIT persists all changes, ROLLBACK cancels all of them. Without BEGIN every statement is a transaction of its own (autocommit). Until the transaction ends, only it sees its changes: other sessions at Read Committed, the PostgreSQL default, read the previous values. The changed rows stay locked against other writes until the end. PostgreSQL has two more traits. After an error inside a transaction it becomes aborted: every next command is rejected until ROLLBACK. And sequences (ids) are not rolled back: an insert followed by ROLLBACK leaves a gap in the numbering.
Example: a transfer that must not go through. Account 10 holds 150, account 11 holds 20, and the table has CHECK (balance >= 0). A transfer of 200:
BEGIN;
UPDATE accounts SET balance = balance - 200WHERE id = 10;
-- ERROR: new row for relation "accounts" violates check-- constraint "accounts_balance_check" (shortened)UPDATE accounts SET balance = balance + 200WHERE id = 11;
-- ERROR: current transaction is aborted, commands ignored-- until end of transaction blockROLLBACK;
SELECT id, balance FROM accounts WHERE id IN (10, 11);
id
balance
10
150.00
11
20.00
The balances did not change: the first update was rejected, the second one to account 11 never ran, and ROLLBACK closed the aborted transaction. For a transfer of 100 both UPDATEs succeed, and after COMMIT the table shows 50.00 and 120.00.
Two half-operations: without a transaction and inside one
No transaction
Each UPDATE commits itself
The debit is committed, the credit failed: 100 vanished and there is nothing to roll back.
In a transaction
BEGIN … COMMIT
An error at any step, and ROLLBACK returns both accounts to the start.
Figure 1. A transaction turns several steps into one action.
Reading the errors: the first and the second
UPDATE accounts SET balance = balance - 200 WHERE id = 10;
1ERROR: new row for relation "accounts" violates check constraint "accounts_balance_check"
UPDATE accounts SET balance = balance + 200 WHERE id = 11;
2ERROR: current transaction is aborted, commands ignored until end of transaction block
Cause:CHECK rejected the debit because the balance would drop below zero. This is the only real failure.
Effect: after the first error the transaction is aborted, and every later command until ROLLBACK gets this answer, even a correct one. Looking for the cause here is pointless.
What to do
Read the first error, not the last one. Close the transaction with ROLLBACK (or go back to a SAVEPOINT) and only then retry.
Figure 2. The two PostgreSQL errors from the example (shortened): the real cause is the first one.
How QA uses transactions:
Safe manual change:BEGIN, change, check, COMMIT or ROLLBACK.
Dry run: run the change, look at the effects, roll back.
Failure testing: stop the application or database between two steps of an operation and check that the state is not "half-done".
Limits and alternatives. A test-level rollback (a transaction rolled back after each test) works only when the test and the code under test share one connection. In E2E the application has its own connections and will not see uncommitted data, so the data is cleaned explicitly there. In MySQL DDL statements (CREATE, ALTER, DROP, TRUNCATE) end the transaction implicitly, in PostgreSQL they do not. Partial rollbacks are given by SAVEPOINT and ROLLBACK TO.
Common mistakes.
A forgotten COMMIT or ROLLBACK: the session hangs "idle in transaction", holds locks and others' updates wait.
Continuing to type commands after an error without ROLLBACK: in PostgreSQL they are all rejected.
Being surprised by an id gap after a rollback: a sequence does not go back, and that is normal.
A long transaction on a shared environment: it blocks colleagues and prevents cleaning of old row versions.
Expecting another session to see the changes before COMMIT.
Check yourself
In a PostgreSQL transaction the first UPDATE ended with an error. Will a second UPDATE run if you send it?
Answer
No. The transaction is aborted: commands are rejected with current transaction is aborted until ROLLBACK (or a rollback to a SAVEPOINT).
The last insert had id 100, then BEGIN; INSERT …; ROLLBACK;, then one more insert. What is its id?
Answer
102. The rolled-back insert used 101 and the sequence does not go back.
Related lessons: “What is ACID?”, “What are isolation levels and which concurrency problems do they solve?”, “How do you run UPDATE and DELETE safely?”.
In an interview.Junior: A transaction runs several operations as one: all or none. A transfer debits one account and credits another, and both steps must go together. I use BEGIN, COMMIT and ROLLBACK to change data safely. Middle/Senior: Without BEGIN autocommit applies. In PostgreSQL an error aborts the transaction until ROLLBACK, and sequences are not rolled back. I test that a failure between steps leaves no half-done state, and I remember that a test-level rollback does not work when the application has its own connections.
What is ACID?
ACID is four guarantees of a transaction: atomicity, consistency, isolation and durability. Atomicity means all changes are applied or none, consistency that the database moves between states that obey the declared rules, isolation that concurrent transactions do not interfere with each other, durability that after COMMIT the changes survive a failure. Rules that are not declared are guaranteed by the application, and ACID does not span microservices.
SQL · Changing data and transactions
The bank confirmed the transfer and the server crashed right after. Will the transfer vanish?
ACID is often learned as four words. It is more useful when each letter has a concrete situation where it works and a concrete check. This lesson walks one transfer through four failure moments and shows what the database cannot guarantee.
How it works and why.
Atomicity: all changes of a transaction are applied or none. In PostgreSQL the changes of an unfinished transaction simply remain invisible as uncommitted row versions.
Consistency: a transaction takes the database from one state that obeys the declared rules to another. The database checks what is declared: PRIMARY KEY, UNIQUE, FOREIGN KEY, CHECK, NOT NULL. Rules that are written nowhere (for example "the sum over all accounts does not change in a transfer") are guaranteed only by the application.
Isolation: concurrent transactions do not interfere with each other within the chosen isolation level (a separate lesson).
Durability: after COMMIT the changes survive a failure. PostgreSQL flushes the write-ahead log (WAL) to disk before confirming the commit.
Example: where exactly a transfer can fail. A transfer of 100 between accounts consists of two UPDATEs and a COMMIT. What happens depends on the moment of the failure:
Moment of failure
What the user sees after the restart
Who guarantees
After the debit, before COMMIT
Both accounts unchanged
Atomicity
The credit violated CHECK or FOREIGN KEY
An error, both accounts unchanged
Atomicity + Consistency
After COMMIT, an OS crash before the reply to the client
The transfer is there
Durability
After COMMIT, the reply to the client was lost
The transfer is there, the client does not know. A retry may duplicate
The application: Idempotency-Key
The last row is the most interesting for QA: it is not a database failure but the edge between the database and the client, where ACID guarantees nothing anymore. The check: cut the connection after COMMIT, repeat the request and see whether two transfers appeared.
Consistency in action (CHECK rejects a negative balance):
UPDATE accounts SET balance = balance - 500WHERE id = 10;
-- ERROR: new row for relation "accounts" violates check-- constraint "accounts_balance_check" (shortened)
What the database guarantees and what the application does
Database
Declared rules and the way data is stored
Atomicity, keys, CHECK, durability after COMMIT, isolation by level.
Application
Rules that are not in the schema
A transfer keeps the total sum, a repeated request does not duplicate the action, the reply to the client after commit.
Figure 1. Both sides have their own guarantees and QA checks both.
Limits and alternatives. The C in ACID is not the same as consistency in the CAP theorem. ACID works within one database. Between microservices there is no single transaction, so sagas and eventual consistency are used there, and the intermediate states and compensations must be tested. Durability can be loosened on purpose: in PostgreSQL synchronous_commit = off confirms the commit faster, but recent transactions may be lost on a crash (without corrupting the database). Test environments are sometimes tuned for speed, so durability is not checked there.
Common mistakes.
Assuming consistency guarantees every business rule: the database only knows the declared constraints.
Mixing C with CAP.
Treating a 200 as proof that data is committed: the application may have replied before COMMIT or after an error it swallowed.
Testing durability on an environment where fsync or synchronous_commit is switched off for speed.
Expecting ACID across several services.
Check yourself
During a transfer the debit ran and the credit to a non-existent account violated a FOREIGN KEY. What happens to the debit, and which property ensures it?
Answer
The transaction rolls back and the debit is cancelled. That is atomicity: an error at any step cancels all of them. The error itself comes from consistency (FOREIGN KEY).
Why does the database not guarantee on its own that the total amount of money in the system stays the same in transfers?
Answer
Consistency checks only declared rules (keys, CHECK). "The sum is unchanged" is declared nowhere, so an application bug that debits 100 and credits 90 passes every database check. It needs a separate query to verify.
Related lessons: “What is a transaction and how does QA use it?”, “What are isolation levels and which concurrency problems do they solve?”, “What constraints are there and how do you test them?”.
In an interview.Junior: ACID is atomicity, consistency, isolation and durability. On the transfer example: money cannot be debited without a credit, the database will not allow a negative balance under CHECK, and after COMMIT the transfer will not disappear on a failure. Middle/Senior: I distinguish what the database guarantees from what the application does: consistency covers only declared rules. I check separately the moment between COMMIT and the reply to the client, where a repeated request can duplicate the action, which needs an Idempotency-Key. Between services there is no ACID, there are sagas and compensations.
What are isolation levels and which concurrency problems do they solve?
Isolation levels define what a transaction sees of other transactions' changes, and so which concurrency anomalies it is protected from. These are dirty read, non-repeatable read, phantom read and serialization anomaly: the higher the level, the stricter and costlier the protection. PostgreSQL defaults to Read Committed, and a lost update is cured with an atomic UPDATE with a condition, FOR UPDATE locking, or a higher level with a transaction retry.
SQL · Changing data and transactions
An account holds 100. Two requests withdraw 80 at the same time and both succeed. How did that happen?
A user pressed "Withdraw 80" twice or two devices sent a request at once. Each request is correct alone, but together they give a negative balance or a lost debit. These are concurrency errors, and isolation levels describe which of them the database protects against. This lesson shows the anomalies on two sessions and three ways to avoid them.
How it works and why. Isolation defines what a transaction sees of other people's changes. Full serialisation is safe but slow, so the SQL standard describes four levels from weak to strong, and the database lets you choose between speed and strictness. The anomalies: dirty read (reading other people's uncommitted changes), non-repeatable read (re-reading a row gives another value), phantom read (a repeated query with the same filter returns another set of rows) and serialization anomaly (the result of concurrent transactions is impossible under any serial order). The table for PostgreSQL:
Level
Dirty read
Non-repeatable
Phantom
Serialization
Read Uncommitted
no (as Read Committed)
possible
possible
possible
Read Committed
no
possible
possible
possible
Repeatable Read
no
no
no (in PostgreSQL)
possible
Serializable
no
no
no
no
PostgreSQL defaults to Read Committed, MySQL InnoDB to Repeatable Read. The standard allows phantoms at Repeatable Read, but the PostgreSQL implementation (the whole transaction sees one snapshot, taken at its first statement, not a new one per statement as in Read Committed) does not. The level is set like this: BEGIN ISOLATION LEVEL REPEATABLE READ;.
Example: a lost update. Account 10, balance 100. The application reads the balance, computes the new one in code and writes the number back. Read Committed:
Step
Session A
Session B
balance
1
BEGIN; SELECT balance → 100
100
2
BEGIN; SELECT balance → 100
100
3
UPDATE … SET balance = 20; COMMIT
20
4
UPDATE … SET balance = 20; COMMIT
20
Both withdrawals of 80 are confirmed and the balance is 20, although after the first one it was 20 and the second should not have happened. A debit is lost with no error. Three fixes:
-- 1. an atomic update with a condition: the second one waits-- for the row lock, then sees 20 and does not passUPDATE accounts
SET balance = balance - 80WHERE id = 10AND balance >= 80;
-- A: UPDATE 1; B: UPDATE 0 -> the application answers with a refusal-- 2. an explicit lock: B waits, then reads 20BEGIN;
SELECT balance FROM accounts WHERE id = 10 FOR UPDATE;
-- the application checks the value read: 20 < 80 -> ROLLBACKUPDATE accounts SET balance = balance - 80WHERE id = 10;
COMMIT;
-- 3. a higher level: the second one gets an error and must retryBEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT balance FROM accounts WHERE id = 10; -- 100-- (meanwhile A wrote 20 and committed)UPDATE accounts SET balance = 20WHERE id = 10;
-- ERROR: could not serialize access due to concurrent update
Two ways to handle the debit
Wrong
Read, compute in code, write the number
A window between read and write lets another change in: an update is lost.
Right
One atomic change with a condition
SET balance = balance - 80 WHERE balance >= 80: the check and the write in one statement.
Figure 1. The cheapest protection is not an isolation level but a well-formed statement.
The same read twice inside one transaction
Read Committed
Session B read
balance
1st SELECT
100
2nd, after A's COMMIT
20
Repeatable Read
Session B read
balance
1st SELECT
100
2nd, after A's COMMIT
100
Figure 2. Between two reads of session B, session A wrote balance 20 to account 10 and committed. At Read Committed the second read sees 20 (a non-repeatable read); at Repeatable Read B sees its own snapshot with 100.
How QA tests this: sends identical requests at once and checks the outcome.
// withdraw: a custom helper that calls the withdrawal APIconst [a, b] = awaitPromise.all([withdraw(10, 80), withdraw(10, 80)]);
// exactly one request must succeed; the refusal code depends on the APIexpect([a.ok, b.ok].filter(Boolean)).toHaveLength(1);
expect(awaitbalance(10)).toBe(20);
Limits and alternatives. One run is not enough: a race depends on timing, so the test is repeated and the number of parallel requests is raised. Higher levels are not free: Repeatable Read and Serializable in PostgreSQL return a serialization error (code 40001), and the application must retry the transaction, which is a separate branch to test. FOR UPDATE locking adds waiting and the risk of a deadlock. Another strategy, optimistic: a version column and the condition WHERE version = ….
Common mistakes.
Treating a lost update with an isolation level when an atomic UPDATE is enough.
Testing concurrency with one sequential test: the race does not reproduce.
Expecting dirty reads in PostgreSQL: they do not occur even at Read Uncommitted.
Not handling a serialization error with a retry.
Carrying conclusions between databases: MySQL has another default level and other locking behaviour.
Check yourself
Why does UPDATE … SET balance = balance - 80 WHERE id = 10 AND balance >= 80 not lose a debit even at Read Committed?
Answer
The statement locks the row. The second UPDATE waits for the first to finish, then re-checks the condition on the new value (20): balance >= 80 is false, so 0 rows are changed.
At Repeatable Read two concurrent debits give the second could not serialize access due to concurrent update. Is that an application bug?
Answer
No, it is expected: the database refuses instead of losing the update. It is a bug if the application does not retry the transaction and gives the user a 500 instead of a correct result.
Related lessons: “What is a transaction and how does QA use it?”, “What is ACID?”, “How do you safely change data on a shared test environment?”.
In an interview.Junior: With concurrent transactions there are dirty reads, non-repeatable reads, phantoms and lost updates. Isolation levels from Read Uncommitted to Serializable protect against them to different degrees, and PostgreSQL defaults to Read Committed. Middle/Senior: A lost update at Read Committed comes from the "read, compute, write" pattern. I cure it with an atomic UPDATE with a condition, FOR UPDATE locking, or a higher level with a retry on a serialization error. I test with parallel requests, several repeats, and check the final balance.
How do you safely change data on a shared test environment?
On a shared environment only your own data is changed, data that can be reliably told from other people's, and this is verified before the change. A marker or owner column, a SELECT with a row-count check and a transaction with a rollback serve for that. Patterns are not trusted: in LIKE an underscore means any character. The best isolation is a separate schema, database or container per run.
SQL · Changing data and transactions
You removed your test accounts and your colleagues' autotests failed. What went wrong?
On a shared environment other testers, autotests and developers work. The data there belongs to nobody and to everybody. A typical story: QA deletes "its own" accounts by an email pattern and the pattern also catches other people's. This lesson is about telling your data from other people's and leaving no breakage behind.
How it works and why. A shared environment has no isolation: everyone uses the same tables. Three risks follow: you change other people's data, other people's changes break your test, and a long transaction or TRUNCATE blocks everyone. The protection has layers: a marker for your own data, a count check before the change, a transaction with a rollback, saved scripts and an agreement with the team.
Example: a pattern that caught other people. The users table has six rows. QA created qa_ana_1 and qa_ana_2 and removes them with the pattern LIKE 'qa_%@test.com':
id
email
Whose
Matches the pattern?
1
qa_ana_1@test.com
mine
yes
2
qa_ana_2@test.com
mine
yes
3
qa2team@test.com
a colleague's
yes
4
qamobile@test.com
a colleague's
yes
5
qa_robot@test.com
autotests'
yes
6
anna@test.com
a real user
no
In a LIKE pattern the _ character means "any single character", so qa_% matches qa2team and qamobile. Two rows were expected and DELETE would touch 5. The protection works if you check the count before the change:
-- unreliable: _ is a wildcardSELECTcount(*) FROM users WHERE email LIKE'qa_%@test.com'; -- 5, expected 2-- the wildcard is escaped and the prefix is unique to the ownerSELECTcount(*) FROM users
WHERE email LIKE'qa!_ana!_%@test.com' ESCAPE '!'; -- 2-- more reliable: delete by the ids RETURNING gave at creationBEGIN;
SET LOCAL lock_timeout = '3s';
DELETEFROM users WHERE id IN (1, 2);
-- DELETE 2COMMIT;
SET LOCAL lock_timeout lasts until the end of the transaction: if the needed row is busy, the command does not hang but ends with an error, and you do not block anyone by waiting. Even more reliable is a column for the owner or run (created_by, a tenant) in the table, filtered on.
Removing your test data
Wrong
A pattern with a common prefix
LIKE 'qa_%' catches other people's accounts and nobody checked the count.
Right
Ids from creation, count check, transaction
Exactly what was created is deleted, and a count mismatch is visible before COMMIT.
Figure 1. Your own data is recognised by identifiers, not by similar text.
Rules for a shared environment:
First make sure where you are: SELECT current_database(), current_user;.
Keep setup and cleanup scripts so they can be repeated instead of typed by hand each time.
Do not touch data that colleagues and autotests depend on; if needed, warn in the team channel.
Split large changes into parts instead of holding them in one long transaction.
Production: no changes; reading only with permission. Real personal data is not copied into a test environment.
Limits and alternatives. The best isolation is your own schema, database or container per run (Testcontainers, a separate tenant): then patterns and markers are unnecessary. When a shared environment is unavoidable, each test creates its data with a unique suffix (a run id) and cleans up by it. Privileges also limit the risk: a QA role without TRUNCATE and DROP rights cannot do anything irreversible.
Common mistakes.
The _ or % wildcard in LIKE without escaping.
A change without a preceding SELECT and a count comparison.
One shared test account for everybody: tests spoil each other's state.
A cleanup script that does not return the environment to its initial state and leaves "garbage" for the next runs.
Changing shared reference data (countries, roles, settings) because "it is faster".
Check yourself
Why does email LIKE 'qa_%@test.com' match qamobile@test.com?
Answer
In LIKE _ stands for any one character and % for any sequence. Here _ matched "m" and % matched "obile". To search for a literal underscore, escape it: qa!_% with ESCAPE '!'.
Before DELETE you expected 2 rows and SELECT count(*) showed 5. What is the next step?
Answer
Do not run the change. Look at those 5 rows, narrow the condition or take exact ids, and repeat the check. A count mismatch is a signal to stop.
Related lessons: “How do you run UPDATE and DELETE safely?”, “How do you prepare and clean up test data with SQL?”, “How do you use SQL in automated tests?”.
In an interview.Junior: On a shared environment I change only my own data, marked with a marker, run a SELECT first, and do the change in a transaction with a row count check. On production I change nothing. Middle/Senior: I do not trust patterns: in LIKE the underscore is a wildcard, so I clean up by the ids obtained at creation or by an owner column. I add lock_timeout so I do not block colleagues, keep the scripts and, where possible, take a separate schema or container per run.
What to check before DELETE, TRUNCATE or DROP?
Before DELETE, TRUNCATE or DROP three questions are answered: where am I, what will I touch and can it be undone. That covers database, environment and user; rows, related tables, cascades and triggers; transaction, copy and privileges. If one has no answer, the command is not run. Before COMMIT all three roll back in PostgreSQL, only DELETE in MySQL.
SQL · Changing data and transactions
You have a database connection open on a shared environment. What to check before running DELETE, TRUNCATE or DROP?
The difference between the three commands is covered in a separate lesson. Here it is about something else: what to do before pressing "execute". Mistakes of this kind are rarely syntax errors. They are a correct command on the wrong connection, on the wrong data, or with no way back.
How it works and why. A safe destructive deletion rests on three questions. Where am I? Which database, which environment, which user. What will I touch? Which rows, which related tables, whether there are cascades and triggers. Can it be undone? Whether inside a transaction, whether there is a copy, which privileges. If one of the three has no answer, the command is not run.
-- where am ISELECT current_database(), current_user, inet_server_addr();
-- a dry run (PostgreSQL): the effects are visible, then a rollbackBEGIN;
DELETEFROM sessions WHERE expires_at < now();
-- DELETE 1240 <- is this the expected count?ROLLBACK;
What exactly rolls back before COMMIT depends on the command and the database: in PostgreSQL all three do, in MySQL only DELETE (the comparison is in the lesson “How do DELETE, TRUNCATE and DROP differ?”). After COMMIT there is no rollback in any database: only a copy or a restore from backup, which is usually done by someone else and takes hours.
Example: a DROP that failed. The old users_old table has to be removed.
DROPTABLE users_old;
-- ERROR: cannot drop table users_old because other objects depend on it-- DETAIL: view v_users depends on table users_old (shortened)-- HINT: Use DROP ... CASCADE to drop the dependent objects too.-- safer: rename and waitALTERTABLE users_old RENAME TO users_old_to_drop_20261121;
The error says that the view v_users depends on the table. CASCADE would remove it too, and perhaps a report that relies on it. Renaming takes the table out of service for code that uses it by name: if something breaks, the name is restored. A view in PostgreSQL, however, references the table by its internal id, so v_users keeps working after the rename and the final DROP fails again. So first find out who reads v_users, rewrite or drop it, and only then drop the table.
Before a destructive command
Wrong
Run the selection on a ready connection
Neither the database, nor the count, nor the relations are visible. There is no way back.
Right
Where am I, what will I touch, how to undo
A connection check, a SELECT with the same condition, a dry run in a transaction, a copy and a rename instead of DROP.
Figure 1. Three questions cost a minute and a mistake costs hours of restoring from a backup.
Limits and alternatives. A dry run in a transaction is safe in PostgreSQL, but TRUNCATE and DROP take ACCESS EXCLUSIVE and hold it until the end of the transaction, so be quick. In MySQL DDL cannot be checked this way. Privileges save better than discipline: the QA role gets SELECT, INSERT, UPDATE, DELETE on the test schema, without TRUNCATE and DROP; that is a question for the database administrator. One more layer, a backup or snapshot before a big run, allows going back when everything else failed.
Common mistakes.
Running the whole script instead of one selected statement, or the other way round.
Two tabs with identical connection names to different environments.
CASCADE "to make it pass" without finding out what depends.
Counting on a rollback in MySQL for TRUNCATE or DROP.
A TRUNCATE dry run left in a transaction for long, blocking the table for everybody.
Check yourself
Why is a dry run BEGIN; TRUNCATE t; … ROLLBACK; safe in PostgreSQL but not in MySQL?
Answer
In PostgreSQL TRUNCATE is transactional and rolls back. In MySQL it is DDL with an implicit COMMIT: the data is gone for good. Also in PostgreSQL the table is locked for everyone until the rollback.
DROP TABLE users_old fails because of a dependent view. Why not just add CASCADE?
Answer
CASCADE removes the dependent objects too (views, constraints), and you do not know which. First find out what depends on what, and where possible rename the table instead of dropping it.
Related lessons: “How do DELETE, TRUNCATE and DROP differ?”, “How do you safely change data on a shared test environment?”, “What is a transaction and how does QA use it?”.
In an interview.Junior: Before deleting I write a SELECT with the same condition and look at which rows I will touch. I make the change in a transaction and, if the count is wrong, ROLLBACK. On production I change nothing without agreement. Middle/Senior: I check where I am connected, what depends on the object (cascades, views, triggers) and whether there is a way back. In PostgreSQL TRUNCATE and DROP roll back before COMMIT, in MySQL they do not. Instead of DROP I rename, and I would ask for the TRUNCATE and DROP rights on a shared environment to stay with the administrator.
What is a SAVEPOINT and how does it help with test data?
SAVEPOINT sets a named mark inside a transaction, and ROLLBACK TO SAVEPOINT undoes only the commands after it. In PostgreSQL this revives an aborted transaction after an expected error, so a negative case does not destroy the rest of the prepared data. The mark stays after the rollback, and id sequences are not rolled back. Outside a transaction SAVEPOINT does not work.
SQL · Changing data and transactions
One negative case in a transaction broke every following command. How do you undo only that one?
A data-setup script works in one transaction. The third insert violated the email uniqueness, and PostgreSQL rejects every following command: the transaction is aborted. Rolling everything back loses the first two inserts. A SAVEPOINT lets you undo only the failed step and continue. This lesson is about how it works and where exactly it helps with test data.
How it works and why.SAVEPOINT name sets a named mark inside an open transaction (it cannot be created outside BEGIN). ROLLBACK TO SAVEPOINT name undoes everything run after the mark, and the transaction is usable again, even if it was aborted before. The mark itself stays, so you can roll back to it once more, while marks created later disappear. RELEASE SAVEPOINT name removes the mark and keeps the changes after it. The reason: a partial undo is needed so that one expected error does not force a rollback of the whole long scenario.
Example: a duplicate email and the transaction lives on.
CREATETABLE usr (id serial PRIMARYKEY, email text UNIQUE);
BEGIN;
INSERTINTO usr (email) VALUES ('a@test.io');
SAVEPOINT sp;
INSERTINTO usr (email) VALUES ('a@test.io');
-- ERROR: duplicate key value violates unique constraint "usr_email_key"SELECT1;
-- ERROR: current transaction is aborted, commands ignored-- until end of transaction blockROLLBACK TO SAVEPOINT sp;
INSERTINTO usr (email) VALUES ('b@test.io');
COMMIT;
SELECT id, email FROM usr ORDERBY id;
-- (1, a@test.io), (3, b@test.io)
The first row stayed, the duplicate was rolled back, and the other insert ran after ROLLBACK TO. The ids in the result are 1 and 3: the failed insert used 2, and a sequence is not rolled back.
Reading the errors: cause and effect
INSERT INTO usr (email) VALUES ('a@test.io');
1ERROR: duplicate key value violates unique constraint "usr_email_key"2DETAIL: Key (email)=(a@test.io) already exists.
SELECT 1;
3ERROR: current transaction is aborted, commands ignored until end of transaction block
Cause:UNIQUE rejected the second insert. This is the only real failure.
Value:DETAIL shows which key already exists. It makes clear the test inserted a duplicate and did not break the database.
Effect: even an innocent SELECT 1 after the error gets this answer until the transaction is rolled back or returned to a mark.
What to do
ROLLBACK TO SAVEPOINT sp undoes only the failed insert and brings the transaction back to work.
Figure 1. The real PostgreSQL messages from the example (shortened): the numbers lead to the explanations.
Where it helps with test data.
Negative cases at the database level: checking that CHECK, UNIQUE or FOREIGN KEY rejects a bad row. A SAVEPOINT is set before each attempt, and after the expected error you roll back to it and continue in the same transaction.
A setup script where one step may fail while the rest of the data is still needed: the step is wrapped in a SAVEPOINT.
A test inside an outer transaction that is rolled back at the end: the nested "transactions" of test helpers are usually savepoints, so an inner rollback does not destroy the outer context.
Limits and alternatives. A mark exists only inside a transaction and disappears when it ends. A rollback does not return sequences. For "insert if missing" INSERT ... ON CONFLICT DO NOTHING is often simpler, since it raises no error at all. Wrapping a test in a transaction (savepoints included) does not help when the test and the application use different connections: the application cannot see the test's uncommitted data, so the data is committed and cleaned up explicitly. SAVEPOINT, ROLLBACK TO SAVEPOINT and RELEASE SAVEPOINT also exist in MySQL (InnoDB).
Common mistakes.
Writing on after an error without ROLLBACK TO: in PostgreSQL every command is rejected until the transaction ends.
Setting the mark after the error: you can roll back only to a mark created before it.
Expecting ROLLBACK TO to return the id counter or to end the transaction: it only undoes the commands after the mark.
Forgetting COMMIT after rolling back to a mark: the transaction stays open and holds locks.
Check yourself
The second command in a transaction failed, and a SAVEPOINT sp was set before it. Which command restores work and what is kept?
Answer
ROLLBACK TO SAVEPOINT sp. Everything before the mark is kept, the commands after it are undone, and the transaction works again.
After ROLLBACK TO SAVEPOINT sp, does the mark sp still exist?
Answer
Yes. Only marks created after it disappear, so you can roll back to sp again.
Related lessons: "What is a transaction and how does QA use it?", "What is ACID?", "How do you safely change data on a shared test environment?".
In an interview.Junior: SAVEPOINT sets a mark in a transaction, and ROLLBACK TO undoes only the changes after it, not the whole transaction. Middle/Senior: In PostgreSQL it is the way to survive an expected error in an aborted transaction. I use it for negative cases in data setup, I remember that sequences are not rolled back, and where possible I use ON CONFLICT.