How do you prepare and clean up test data with SQL?
Test data carries a marker (email prefix, tenant or tag), created repeatably and deterministically, and cleaned up only by that marker. Scripts are repeatable thanks to ON CONFLICT, and cleanup goes from children to parents in one transaction and in a teardown hook. In LIKE an underscore matches any character, so starts_with is used or the underscore is escaped. SQL bypasses application logic, so routine setup is better done through the API.
SQL · QA practice
An autotest left a hundred users in the database and the next run fails on duplicates. How to prepare and clean up data?
A test creates the user qa_auto_1@test.com and does not remove it. The second run fails on a unique key, and on a shared environment garbage is left that breaks other people's reports. The worse opposite: a cleanup script deletes too much because its condition catches other people's rows too. This lesson is about creating data through SQL quickly and repeatably, and cleaning up only your own.
How it works and why
Test data has three properties. It is marked: a prefix in the email, a separate tenant or a tag, so cleanup finds only it. It is repeatable: the script can be run again without errors. And it is deterministic: the expected values are known in advance, so a pagination test knows exactly which amounts lie on page 2. The order is dictated by foreign keys: the parent row is created first and deleted last.
The order of creation and deletion
Example: create, generate, clean up
Creating a user with an account in one statement, to get the identifier without a second round trip:
WITH u AS (
INSERT INTO users (email)
VALUES ('qa_auto_p1@test.com')
ON CONFLICT (email) DO UPDATE SET email = EXCLUDED.email
RETURNING id
)
INSERT INTO accounts (user_id, balance, status)
SELECT id, 1000.00, 'active' FROM u
RETURNING id;
ON CONFLICT makes the script repeatable and requires a unique constraint on email. A nuance: with DO NOTHING the conflicting row returns nothing in RETURNING, so a "no-op" update is used here to get the id. For pagination and load, data is generated, and the amounts are set by a formula, not randomly:
INSERT INTO transactions (account_id, type, amount, status, created_at)
SELECT 10, 'deposit', g::numeric(14, 2), 'completed',
TIMESTAMPTZ '2026-11-01 12:00+00' - g * INTERVAL '1 minute'
FROM generate_series(1, 1000) AS g;
-- amounts 1.00 … 1000.00, known: 500500.00 in total
Cleanup: from children to parents, in one transaction, first checking the count:
SELECT COUNT(*) FROM users WHERE starts_with(email, 'qa_auto_');
BEGIN;
DELETE FROM transactions WHERE account_id IN (
SELECT a.id FROM accounts a
JOIN users u ON u.id = a.user_id
WHERE starts_with(u.email, 'qa_auto_'));
DELETE FROM accounts WHERE user_id IN (
SELECT id FROM users WHERE starts_with(email, 'qa_auto_'));
DELETE FROM users WHERE starts_with(email, 'qa_auto_');
COMMIT;
starts_with (PostgreSQL 11+) is used here deliberately, not LIKE 'qa_auto_%'. In LIKE the character _ means "any single character", so the pattern would also catch qaXautoYbob@mail.com. If LIKE is really needed, the underscore is escaped with a backslash: LIKE 'qa\_auto\_%'. The transaction guarantees that a failure in the middle does not leave half the data.
Limits and alternatives
Data inserted by SQL bypasses the application's logic: application triggers, events, audit. A row may end up in a state the application would never create. So for ordinary setup it is better to call the API, leaving SQL for states that cannot be reached otherwise: a date in the past, a blocked account, a large number of records. Other options: ON DELETE CASCADE, if it is in the schema and intended; rolling back a transaction when the test and the application share a connection; a template database or snapshot for a full reset. TRUNCATE is not used on a shared environment at all.
Common mistakes
DELETEwith no marker inWHEREor with too wide a pattern: other people's data disappears.LIKEwith an underscore in the prefix without escaping.- Random amounts in a fixture: a pagination test cannot know the expected result.
- A script that does not survive a rerun: duplicates and failures on a unique key.
- Cleanup only when the test succeeds: after a failure the data stays. Cleanup goes in a teardown hook.
Check yourself
A cleanup script with LIKE 'qa_auto_%' deleted the user qaXautoYbob@mail.com. Why?
Answer
In LIKE the underscore stands for any single character. Use starts_with(email, 'qa_auto_') or an escaped pattern 'qa\_auto\_%', or better a separate marker such as a column or a tenant.
A script inserts a user with ON CONFLICT (email) DO NOTHING RETURNING id. On the second run no id is returned. What to change?
Answer
A conflicting row with DO NOTHING does not reach RETURNING. Use DO UPDATE SET email = EXCLUDED.email and the id is always returned, or read the id by email separately.