How do you verify in the database the result of an action in the UI?
A UI action is verified in the database as a before-and-after difference: all new and changed rows, not just the latest one. A marker such as the maximum id or a balance is recorded before the action, then the user's rows newer than it are read, so a duplicate shows up and other people's records do not interfere. An asynchronous write is awaited by polling with a timeout, not a pause.
SQL · QA practice
The UI said "Top-up successful", but the account in the database holds 1250 instead of 750. What to check?
A test tops up an account by 500 PLN. The screen shows "Success" and the amount 500, and the API response check is green too. Yet after one click the database has two deposit rows and the balance grew by 1000. The user does not see it yet (the screen took the amount from the response), but accounting will. This lesson is about what exactly to check in the database after a UI action and how to make that check precise even on a shared environment where others write too.
How it works and why
The UI shows what the application decided to show, and the database holds what actually happened. A check must not assume the table is empty or that "the last row" belongs to this test: other tests and people work on the environment at the same time. A reliable technique has four steps. First remember a mark: the current maximum id of the table and the account balance. Then perform the action. Then wait for the result: the record may appear with a delay if processing goes through a queue or the response arrives before the commit. Finally compare: all rows with an id above the mark for this account, and the balance difference. This shows everything the action created and nothing that existed before it.
A database check around one action
Figure 1. The mark makes the check independent of what was in the database before the test.
Example: from "Success" to a duplicate
Before the action the test reads the mark for account 10:
-- before the action: the balance and the largest idSELECT balance,
(SELECTCOALESCE(MAX(id), 0) FROM transactions) AS mark
FROM accounts
WHERE id = 10;
-- result: balance 250.00, mark 100
After the click on the 500 PLN button, a query takes everything new for this account:
SELECT id, type, amount, status
FROM transactions
WHERE account_id = 10AND id > 100ORDERBY id;
What the query found and the balance
transactions (id > 100)
id
type
amount
status
101
deposit
500.00
completed
102
deposit
500.00
completed
accounts, id = 10
moment
balance
before
250.00
expected
750.00
after
1250.00
Figure 2. Two identical deposits instead of one: the balance is 500 above the expectation.
One row and a balance of 750 were expected. Two identical rows with the same time point to a double submit: either the button is not disabled after the click, or the server repeated the request without an idempotency key. The source of the defect is looked for in the code, and the bug report already has everything needed: the mark, the query and the result. The check the test keeps is short and does not depend on order:
SELECTCOUNT(*) AS n, COALESCE(SUM(amount), 0) AS total
FROM transactions
WHERE account_id = 10AND id > 100AND type = 'deposit';
-- expected: n = 1, total = 500.00
What else is checked after such an action besides the row:
Status matches the stage: completed or pending by the requirement, not stuck between them.
Side effects: exactly one fee, if there is one; an audit entry with who performed the action.
Nothing extra: other accounts did not change, no duplicates.
Service fields:created_at in the right time zone (more in the lesson on dates).
Limits and alternatives
A mark by id works while identifiers grow: for UUIDs take the creation time or a separate unique marker in the action (for example, a unique note on the payment). If another test writes to the same account in parallel, a filter by account does not help: each test needs its own account. Replication lag also gives an "empty" result, so read from the primary node. If the record really appears asynchronously, wait by polling with a timeout, not with a fixed pause: a pause is either too long or too short. The same can often be checked without the database by reading the account through the API. That is cheaper and does not tie the test to the schema, so the database is needed only where the client sees nothing: side effects, service states, the consequences of a failure.
Common mistakes
Checking only the last row (ORDER BY created_at DESC LIMIT 1): a duplicate goes unnoticed.
Comparing the balance with an absolute number instead of a difference from the starting value: the test breaks as soon as the account holds other data.
A fixed pause before the query: a slow environment gives a false bug, a fast one waits for nothing.
A query with no filter by account or mark: other people's rows get into the result.
Treating the stored amount as proof that the UI shows it correctly: these are different checks.
Check yourself
After a top-up a test takes SELECT amount FROM transactions ORDER BY created_at DESC LIMIT 1 and checks 500. Why does it pass on a double top-up and what replaces it?
Answer
The query sees only one, the newest row, and both duplicates have the amount 500. Everything new must be counted: a mark before the action, then COUNT(*) and SUM(amount) for the account with an id above the mark, plus the balance difference.
A query right after the click sometimes returns 0 rows and one a second later. Is it a bug?
Answer
Not necessarily: processing may be asynchronous or the response may be returned before the commit. The test should poll the database with a timeout that matches the requirement. It is a bug if the record is missing even after the expected time, or if the UI already showed "Success" where the requirement promises "Processing".
Related lessons: “How do you find anomalies and data integrity violations?”, “How do you use SQL in automated tests?”, “API validation through the DB”, “What should you pay attention to when working with dates and time zones?”.
In an interview.Junior: After a UI action I check in the database that the record was created with the right amount, type and status, that the balance changed and that there is no duplicate or change in other people's records. Middle/Senior: I make a mark before the action (the maximum id and the balance) and compare the difference afterwards, so the check does not depend on other people's data. I wait for an asynchronous write by polling with a timeout, not with a pause, look at side effects (fee, audit) and know that part of the same can be checked more cheaply through the API, leaving the database for what the client cannot see.
How do you find anomalies and data integrity violations?
A rule "this must not happen" is written as a query returning exactly the violations: an empty result means normal, and the rows go into the bug report. This finds orphans, duplicates, impossible values and stuck states. A result is a suspicion, not a verdict, so it is checked against the requirement. If the violations could be prohibited by FOREIGN KEY, CHECK or UNIQUE, the missing constraint is a bug too.
SQL · QA practice
The UI looks fine, yet the database has a transaction on a blocked account. How to hunt for findings like this systematically?
Tests check the scenarios a user goes through. But some defects live in data nobody opens: a transaction on an account blocked a week ago, a payment with no account, a balance below zero. They cannot be found by clicking the UI, but a few queries find them. This lesson is about turning domain rules into check queries and what they do not prove.
How it works and why
Each rule of the form "this must not happen" is written as a query that returns exactly the violations. An empty result means normal, and a non-empty one is already a ready description of a defect: the row identifiers go into the bug report. That is why such a query is worth saving and running again after migrations, releases and logic changes. The shape of the query depends on the class of violation.
Class
Query shape
Example
Orphans
NOT EXISTS
a transaction with no account
Duplicates
GROUP BY … HAVING COUNT(*) > 1
two users with one email
Impossible values
WHERE with a check for IS NULL
amount ≤ 0, an unknown status
Impossible combinations
JOIN and comparing columns of two tables
an operation after blocking
Stuck states
status and record age
pending for over an hour
Example: five rows and three findings
A small data set with violations hidden in it:
Data in which violations must be found
accounts
id
status
blocked_at
1
active
NULL
2
blocked
2026-11-10
transactions
id
account_id
amount
created
t1
1
100.00
11-02
t2
2
50.00
11-09
t3
2
70.00
11-12
t4
9
30.00
11-05
t5
1
-20.00
11-06
Figure 1. Account 2 was blocked on 10 November, and t3 was created on the 12th. Account 9 does not exist, the amount of t5 is negative.
-- orphans: a transaction with no accountSELECT t.id, t.account_id
FROM transactions t
WHERENOTEXISTS (SELECT1FROM accounts a WHERE a.id = t.account_id);
-- t4-- impossible combination: an operation after blockingSELECT t.id, a.id AS account_id, t.created_at, a.blocked_at
FROM transactions t
JOIN accounts a ON a.id = t.account_id
WHERE a.status = 'blocked'AND t.created_at > a.blocked_at;
-- t3-- impossible values (NULL is a violation too)SELECT id, amount, status
FROM transactions
WHERE amount ISNULLOR amount <= 0OR status ISNULLOR status NOTIN ('pending', 'completed', 'failed');
-- t5 (amount -20.00)
Three queries found three different rows: t4, t3 and t5. Note the third: status NOT IN (…) for a row with status = NULL gives UNKNOWN, so without a separate status IS NULL condition such a row would silently drop out of the result. For orphans NOT EXISTS is used instead of NOT IN (SELECT …): one NULL in the subquery zeroes the whole result. The other classes are written the same way.
-- duplicates: email ignoring caseSELECT lower(email) AS email, COUNT(*) AS n
FROM users
GROUPBY lower(email)
HAVINGCOUNT(*) > 1;
-- stuck in pending for over an hourSELECT id, account_id, created_at
FROM transactions
WHERE status = 'pending'AND created_at < NOW() - INTERVAL '1 hour';
Limits and alternatives
A query result is a suspicion, not a verdict. A transaction after blocking may be a legitimate refund, and pending for over an hour may be normal for a bank transfer. So first find the rule in the requirements or from an analyst and only then declare a bug. Many classes are closed by database constraints altogether: FOREIGN KEY will not allow an orphan, CHECK (amount > 0) rejects a negative amount, UNIQUE will not let a duplicate through. So quite often the right bug reads: "the constraint is missing, and the data already has violations". On large tables an anti-join without an index on account_id is slow, so on a shared environment the query is limited by date or run on a replica.
Common mistakes
NOT IN for the list of allowed statuses without IS NULL: rows with no status never reach the result.
Duplicates by email without lower(): Anna@x.com and anna@x.com stay unnoticed.
Treating a non-empty result as a bug without checking the rule: some findings are legitimate exceptions.
Running such queries with no LIMIT and date on a shared database: a slow query disturbs others.
A one-off check that is not saved: the next release breaks the same thing again and nobody notices.
Check yourself
The query WHERE status NOT IN ('pending','completed','failed') returns 0 rows although the table has rows with no status. Why, and how to fix it?
Answer
For status = NULL the NOT IN condition gives UNKNOWN, and WHERE keeps only true conditions. Add OR status IS NULL as a separate branch.
GROUP BY email HAVING COUNT(*) > 1 found nothing, but the database has Anna@x.com and anna@x.com. What to change?
Answer
Grouping sees two different strings because the comparison is case-sensitive. Group by lower(email). Separately ask whether there is a unique index on lower(email): if not, that is a bug of its own.
Related lessons: “How do you find records that have no match in another table?”, “Why can NOT IN return zero rows?”, “What constraints are there and how do you test them?”.
In an interview.Junior: I keep a set of integrity queries: orphans through an anti-join, duplicates through GROUP BY with HAVING, impossible values such as a negative balance, and stuck statuses. They find bugs that cannot be seen from the UI. Middle/Senior: I write each rule so that the query returns the violations and an empty result means normal. I remember NULL in NOT IN, case in duplicates and that the result is only a suspicion that I check against the requirement. If a class of violations is closed by FOREIGN KEY, CHECK or UNIQUE, I file a bug about the missing constraint.
What should you pay attention to when working with dates and time zones?
In PostgreSQL a point in time is stored in timestamptz, and a calendar day exists only relative to a zone, so one moment can fall on different days. A day report uses a half-open range in the right zone, not equality or BETWEEN. An hour or two of difference between the UI and the database is not always a bug; the zone is clarified first. Daylight-saving days are tested separately.
SQL · QA practice
The report "for 30 September" differs by one transaction between the database and the UI. A bug or time zones?
The database has two transactions for 30 September, while the report in the UI has one. The tester files a bug and the developer answers that the report is built in Warsaw time. Who is right depends on the zone the time is stored in, the zone it is shown in and the day boundaries the report was counted with. This lesson is about how time works in PostgreSQL, why day boundaries differ between zones and which cases deserve separate tests.
How it works and why
TIMESTAMP WITH TIME ZONE (timestamptz) in PostgreSQL stores a point in time: internally it is UTC, and on output it is converted to the session zone (the TimeZone setting). The TIMESTAMP type without a zone stores only "wall-clock" time with no zone, and without an agreement on the zone it was written in, it means nothing. Hence the rule: keep a point in time in timestamptz, while a calendar day exists only relative to a zone. The same moment may fall into different days.
Three transactions in two zones
In UTC
id
UTC time
date
a
09-30 21:30
09-30
b
09-30 22:30
09-30
c
10-01 10:00
10-01
In Warsaw (UTC+2)
id
time
date
a
09-30 23:30
09-30
b
10-01 00:30
10-01
c
10-01 12:00
10-01
Figure 1. Transaction b belongs to 30 September in UTC and to 1 October in Warsaw.
A report for 30 September in UTC contains a and b (two), and in Warsaw only a (one). This is not a bug but different day boundaries. It is a bug when the report does not say which zone it is built in, or when the UI and the export use different zones.
Example: the right day range
The condition created_at = '2026-09-30' looks for exactly midnight, so it finds almost nothing. The range is written half-open, with the bounds in the needed zone:
SHOW timezone; -- the session zoneSELECTCOUNT(*)
FROM transactions
WHERE created_at >= TIMESTAMP '2026-09-30' AT TIME ZONE 'Europe/Warsaw'AND created_at < TIMESTAMP '2026-10-01' AT TIME ZONE 'Europe/Warsaw';
-- on the data above: 1 (only a)-- the date of a transaction in the needed zoneSELECT id, (created_at AT TIME ZONE 'Europe/Warsaw')::date AS day
FROM transactions;
TIMESTAMP '…' AT TIME ZONE 'Europe/Warsaw' turns wall-clock time into a point in time, and created_at AT TIME ZONE 'Europe/Warsaw' does the reverse: it shows the moment as wall-clock time in Warsaw. Comparing two timestamptz values always goes by moments, so the session zone changes only how the result looks, not which rows are selected.
The switch to and from summer time breaks the assumption "a day has 24 hours":
SELECT (TIMESTAMP '2026-10-26' AT TIME ZONE 'Europe/Warsaw')
- (TIMESTAMP '2026-10-25' AT TIME ZONE 'Europe/Warsaw');
-- 1 day 01:00:00, i.e. 25 hours: 25 October 2026 is the autumn switch
In spring, on 29 March 2026, the day lasts 23 hours and local time between 02:00 and 03:00 does not exist. In autumn the time 02:30 occurs twice. Adding INTERVAL '1 day' to a timestamptz counts a calendar day by the session zone, while INTERVAL '24 hours' is exactly 24 hours, so on the switch day the results differ.
Limits and alternatives
If a column has the type timestamp without a zone, first find out which zone the application fills it in: often it is the server zone, and then on a distributed system data silently mixes. That is a question for the architecture, not for the query. Users from different countries need a zone per user, because "today" in Warsaw and in New York are different days. NOW() returns the start time of the current transaction and does not change inside it, while clock_timestamp() shows real time. For tests with time it is better to control the application's clock than to wait for a real midnight.
Common mistakes
= '2026-09-30' instead of a range: finds only rows exactly at 00:00.
BETWEEN '2026-09-30' AND '2026-09-30 23:59:59': loses the moment between 23:59:59 and midnight; a half-open range is safer.
Treating a difference of an hour or two between the UI and the database as a bug without asking about the zone.
Skipping the daylight saving switch days in tests of reports and limits.
Comparing dates as strings: '10-01' and '1-10' do not sort as dates.
Check yourself
Transactions on 30 September definitely exist, but WHERE created_at = '2026-09-30' returns 0 rows. Why?
Answer
A literal with no time means 00:00:00, and equality finds only rows exactly at that moment. A half-open range is needed: >= '2026-09-30' AND < '2026-10-01' in the needed zone.
How many hours does the day of 25 October 2026 have in Warsaw and what to test on that day?
Answer
25 hours: the time 02:30 occurs twice. Test "per day" reports and limits, the order of events with the same wall-clock time, and calculations that add days and hours.
Related lessons: “How do IN, BETWEEN and LIKE work?”, “How do you verify in the database the result of an action in the UI?”, “How do you find anomalies and data integrity violations?”.
In an interview.Junior: With dates I find out which zone the time is stored in and which zone the UI shows: a difference of an hour or two is often not a bug. I write day ranges as "from the start of the day inclusive to the next day exclusive". Middle/Senior: I tell timestamptz and timestamp apart: the first stores a moment, the second only wall-clock time. I build day boundaries in the user's or the report's zone, test the daylight saving switch days separately (23 and 25 hours) and understand that the session zone changes the look, not the selection of rows.
How do you store money correctly and what bugs are there?
Money is stored in NUMERIC(p, s) or as an integer in minimal units (cents), not in float with its binary error. A test checks the invariant: the parts sum to the whole and the remainder has an owner, because 100.00 / 3 three times gives 99.99. It also checks whether the API rejects extra digits or rounds silently, how it returns amounts in JSON, and whether currencies with other decimal counts are handled.
SQL · QA practice
A payment of 100.00 was split into three parts and the total came to 99.99. Where did the cent go?
A fee or a payment is divided into three equal parts: 100.00 / 3 = 33.33, three times. The total is 99.99, one cent has gone. In monthly reports such "micro-remainders" add up to an amount accounting cannot explain. Besides rounding, there is also the column type: in FLOAT money accumulates an error that a test with one amount does not show. This lesson is about how to store money in PostgreSQL, where the vanishing cents come from and what to test.
How it works and why
The types real and double precision (float8) store a number in binary. The decimal 0.1 has no exact binary form, just as 1/3 has no finite decimal one, so the closest approximation is stored. One operation is almost invisible, thousands accumulate a difference. NUMERIC(p, s) stores decimal digits exactly: p is the total number of significant digits, s the digits after the point. The other reliable approach is an integer in minimal units (cents) plus a separate currency column. PostgreSQL also has the money type, but its format depends on the server's lc_monetary setting, so it is not recommended for accounting.
The sum is 0.9999999999999999, and the "equals 1" check does not fire.
Right
numeric
The sum is 1.0: decimal digits are stored exactly.
Figure 1. A float error is not visible in a test with one amount, it appears in sums and comparisons.
Example: splitting an amount
Even NUMERIC does not save you from rounding: when an amount is divided, the remainder has to go somewhere.
SELECT round(100.00 / 3, 2) AS part, -- 33.33
round(100.00 / 3, 2) * 3AS total; -- 99.99-- the remainder goes to the first partSELECT100.00 - 2 * round(100.00 / 3, 2) AS first_part;
-- 33.34
The sum of the parts and the whole
Each part rounded
part
amount
1
33.33
2
33.33
3
33.33
total
99.99
Remainder in the first part
part
amount
1
33.34
2
33.33
3
33.33
total
100.00
Figure 2. Each part rounded separately: a cent is lost. The remainder in one part: exactly 100.00 in total.
A test for such a rule checks not a single part but the invariant: the sum of the parts equals the whole. A few more column type traps: writing 10.005 into NUMERIC(14,2) is silently rounded to 10.01 (PostgreSQL rounds "away from zero") rather than rejected; a value with more integer digits than the type allows gives an overflow error. So test separately what the API does with extra digits: rejects or silently rounds, and whether it matches the requirement. For float8 rounding on a half depends on the platform (most often to the nearest even), while for numeric it is away from zero: round(2.5::numeric) gives 3. Other systems may round differently, so take the rounding mode from the requirements.
Limits and alternatives
Currencies have different numbers of decimal places: JPY has none, and some currencies have three (per ISO 4217), so one NUMERIC(14,2) for all does not fit. An integer in minimal units avoids fractions but requires knowing each currency's scale and not forgetting to divide when displaying. In JSON a number becomes a double in many clients, so an API often returns the amount as a string ("10.05"): that is worth checking too. Currency conversion and percentages are tested separately, with an explicitly written rounding rule.
Common mistakes
Testing only round amounts: 10, 100. Errors and rounding show on 0.01, 0.10, 99.99, 100.005.
Comparing floating-point amounts with =.
Rounding each part separately and not checking that the sum of the parts equals the whole.
Assuming a currency always has two decimal places.
Not finding out what the API does with extra digits: silent rounding hides the client's mistake.
Check yourself
SELECT 0.1::float8 * 3 = 0.3::float8 returns false. Why, and what does the same expression return with numeric?
Answer
0.1 in binary is approximate, so the product differs slightly from the approximate 0.3. In numeric the digits are decimal and exact, and the expression gives true.
A system divides 100.00 among three recipients. Which checks are needed?
Answer
The sum of the parts is 100.00, not 99.99; it is clear who gets the remainder; the result is the same on a retry; behaviour with amounts that do not divide evenly and with currencies that have another number of decimals.
Related lessons: “Which data types should QA know?”, “How do you check that a balance matches the transaction history?”, “How do you verify in the database the result of an action in the UI?”.
In an interview.Junior: Money is not stored in FLOAT because it has a binary error: 0.1 plus 0.2 does not equal exactly 0.3. The right choice is NUMERIC or an integer in minimal units. I test amounts with cents and fee rounding. Middle/Senior: I check invariants: the sum of the parts equals the whole, the remainder has an owner. I look at what the API does with extra digits, how it returns amounts in JSON (string or number) and whether currencies with another number of decimals are covered. I take the rounding mode from the requirements, not from the behaviour of the type.
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
Figure 1. Deleting a parent that still has children is stopped by the foreign key (unless there is ON DELETE CASCADE).
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 (
INSERTINTO users (email)
VALUES ('qa_auto_p1@test.com')
ONCONFLICT (email) DOUPDATESET email = EXCLUDED.email
RETURNING id
)
INSERTINTO 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:
INSERTINTO transactions (account_id, type, amount, status, created_at)
SELECT10, '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:
SELECTCOUNT(*) FROM users WHERE starts_with(email, 'qa_auto_');
BEGIN;
DELETEFROM 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_'));
DELETEFROM accounts WHERE user_id IN (
SELECT id FROM users WHERE starts_with(email, 'qa_auto_'));
DELETEFROM 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
DELETE with no marker in WHERE or with too wide a pattern: other people's data disappears.
LIKE with 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.
Related lessons: “How do you safely change data on a shared test environment?”, “How do you add data with INSERT?”, “How do you run UPDATE and DELETE safely?”, “What is a transaction and how does QA use it?”.
In an interview.Junior: I mark all test data with a marker, for example a prefix in the email, to remove only my own. I create from parents to children and delete in reverse, because foreign keys demand it. For large volumes I generate data through generate_series. Middle/Senior: I make scripts repeatable (ON CONFLICT) and deterministic, clean up in a transaction after checking the count and in a teardown hook, so that a failure leaves no garbage. I remember the underscore trap in LIKE and that SQL bypasses the application's logic, so ordinary setup I do through the API.
What is SQL injection and how do you test for it?
SQL injection happens when a query is built as a string and user input becomes part of its text, so it is parsed as code. Parameterised queries prevent it: the value is passed separately and never parsed as SQL. A parameter does not cover column names or sort direction, which need an allowlist. QA checks every input with a quote and a "1=1" condition; destructive probes run only on an authorised environment.
SQL · QA practice
A single quote typed into the search field returned a database error instead of results. Is that already a bug?
A tester types O'Brien into search and sees a 500 error with the text syntax error at or near. This is not only a failure on a surname with an apostrophe: the input reached the query as code, so with another string the query can be changed. This lesson is about why it happens, how a parameter differs from concatenation and how to check such places without harming the environment.
How it works and why
SQL injection happens when a query is built as a string and user input becomes part of the query text. The database server cannot tell where the developer's code ends and foreign characters begin, so a quote closes a string literal and the rest of the input is read as SQL. In a parameterised query the query text and the values are sent separately: the query is parsed first with the placeholder $1, and the value is supplied afterwards as data and is never parsed as SQL. So a quote in a value is just a quote.
// vulnerable: the input becomes part of the query textawait client.query(
"SELECT * FROM users WHERE email = '" + email + "'",
);
// safe: the value is passed separatelyawait client.query('SELECT * FROM users WHERE email = $1', [email]);
Example: what one string changes
The table has three users. The input ' OR '1'='1 in vulnerable code gives the condition email = '' OR '1'='1', true for every row, so the query returns everyone. A parameterised query looks for a user whose email literally equals this string and finds nobody.
The same input in two implementations
Concatenation
id
email
1
anna@test.com
2
ivan@test.com
3
olga@test.com
Parameter $1
id
email
Figure 1. On the left all users came back, on the right nothing: the input was data.
How QA checks it. The input does not have to be harmful, probes that reveal the behaviour are enough:
Input
What we observe
'
a 500 error or database error text means the quote is not handled
' OR '1'='1
more results than there should be
anna@test.com' AND '1'='1 and anna@test.com' AND '1'='2
different results when only the truth changes: the condition is executed
1 OR 1=1
a numeric parameter without quotes
The expected correct behaviour: the input is handled as plain text ("nothing found" or a 400 validation error), the response has no SQL errors or table names, the response shape is the same. Check all places where input reaches the database: search, filters, sorting parameters, JSON fields, headers, login. Destructive probes such as ; DROP TABLE are not run on a shared environment, and probes with a delay (pg_sleep) and automatic scanners are used only on an environment where it is permitted.
Limits and alternatives
A parameter protects values but not column and table names, keywords and sort direction. A placeholder does not work for ORDER BY ${sort}, an allowlist of permitted values is needed here. An ORM does not guarantee safety: raw queries with string interpolation are just as vulnerable. Manual escaping is unreliable, and the rights of a database user with minimal privileges only reduce the damage but do not remove the vulnerability. Manual probes reveal the obvious, and a systematic check is done with automated tools with the system owner's permission.
Common mistakes
Closing the "500 on a quote" bug with a filter that strips quotes: this does not remove the cause and breaks surnames like O'Brien.
Checking only the search field and forgetting sorting, filters and headers.
Assuming an ORM rules out injection: a raw query with interpolation is vulnerable.
Running destructive probes on a shared environment.
Not noticing that database error text in a response is already an information leak.
Check yourself
Search on ' returns 500 and the body has syntax error at or near. Which defects are here?
Answer
Two. The input reaches the query as code (a potential injection), and the response reveals internal database details. File them as separate bugs, not one.
A sort parameter is put into ORDER BY. Why does the placeholder $1 not help here and what to do?
Answer
A placeholder replaces a value, not an identifier or a keyword, so ORDER BY $1 sorts by a constant string. Accept only values from a list of allowed columns and directions, and reject the rest with a 400.
Related lessons: “How do you use SQL in automated tests?”, “API validation through the DB”, “How do you run UPDATE and DELETE safely?”.
In an interview.Junior: SQL injection is when user input reaches the query as code. The defence is parameterised queries. I check search fields and filters with basic strings containing a quote and the "one equals one" condition and expect them to be handled as plain text, with no database errors in the response. Middle/Senior: I understand the mechanism: parameters are sent separately from the query text, so a value is never parsed as SQL. I know the boundary: identifiers and sorting cannot be protected by a parameter, an allowlist is needed. I check all inputs, not only search, tell a handling error from a leak, and run destructive probes and scanners only with permission.
How do you check that a balance matches the transaction history?
A balance is reconciled with a query that sums each account's completed operations and returns accounts where the sum differs from the stored balance. A normal result is empty. To avoid losing accounts it uses LEFT JOIN with the status condition inside the join, COALESCE and IS DISTINCT FROM instead of <>. The requirements settle whether pending operations count.
SQL · QA practice
The UI shows a balance of 80.00, while the transaction history adds up to 70.00. Which of the two is wrong?
A balance is stored in a separate column so as not to recount the history each time, and the transaction history remains the source of truth. While both numbers change correctly, they match. After a race, a partial failure or a manual edit in the database they diverge, and the user sees an amount no operation confirms. This lesson is about reconciling the stored value with what follows from the history, and about the query details on which it quietly breaks.
How it works and why
A stored balance is a derived value: balance = the sum of completed deposits minus the sum of completed withdrawals. A property that must always hold is called an invariant. Checking an invariant is a query that for each account computes the sum from the history and returns only the accounts where it differs from the stored value. Normally the result is empty. Each element of the query answers a specific danger: LEFT JOIN (or a subquery with LEFT JOIN) so as not to lose accounts with no operations, the status condition inside the join or the subquery so as not to lose them either, COALESCE because the sum of an empty set is NULL, and IS DISTINCT FROM instead of <> because a comparison with NULL is never true.
Example: two mismatches
Account balances: 1 is 150.00, 2 is 80.00, 3 is 0.00 (no operations), 4 is 20.00. The history is in the table below.
SELECT a.id, a.balance, COALESCE(s.total, 0) AS calculated
FROM accounts a
LEFTJOIN (
SELECT account_id,
SUM(CASE type WHEN'deposit'THEN amount
ELSE -amount END) AS total
FROM transactions
WHERE status = 'completed'GROUPBY account_id
) s ON s.account_id = a.id
WHERE a.balance ISDISTINCTFROMCOALESCE(s.total, 0);
The history and the reconciliation result
transactions
account
type
amount
status
1
deposit
200.00
completed
1
withdrawal
50.00
completed
2
deposit
100.00
completed
2
withdrawal
30.00
completed
4
deposit
20.00
pending
Query result
id
balance
calculated
2
80.00
70.00
4
20.00
0
Figure 1. Account 1 matches (200 − 50 = 150), and account 3 with no operations too, so they are not in the result.
Account 2: the history gives 100 − 30 = 70, while 80 is stored. The difference of 10.00 means a lost withdrawal row, a double credit or a manual edit: the cause is sought in the change log of this account. Account 4: the balance is 20.00 and there are no completed operations, only a deposit with status pending. Whether this is a defect depends on the rule: if the balance must count only completed operations, it is a bug, if it reserves expected ones, the rule is different. So the question "what to count" is clarified in the requirements before running the query.
A variant with the same expression repeated twice in HAVING works too, but the subquery reads better and does not multiply rows if another table is joined to accounts later.
Where the status condition goes
Wrong
in WHERE after LEFT JOIN
Accounts with no completed operations are filtered out and the mismatch of account 4 disappears.
Right
in the subquery or in ON
All accounts stay, a sum with no operations becomes 0.
Figure 2. The same rule as for any LEFT JOIN: a condition on the right table does not go in WHERE.
Limits and alternatives
Reconciling during writes gives false mismatches: a transaction has already inserted a row but not yet updated the balance. The query is run on a "quiet" environment, in a transaction with the REPEATABLE READ level (one data snapshot) or with a time cutoff. The expression ELSE -amount treats any type other than deposit as a withdrawal, so before reconciling check which type values exist: a fee, a refund or an adjustment may have the opposite sign. To find the operation where the mismatch arose, compute a running total with a window function. On large tables aggregating the whole history is slow: in a test, reconcile a single account.
Common mistakes
JOIN instead of LEFT JOIN: accounts with no operations vanish, and with them possible defects.
The status condition in WHERE after LEFT JOIN.
No COALESCE: balance <> NULL is never true, and an account with no operations quietly drops out.
Counting all types as withdrawals without looking at the list of types.
Running reconciliation under load and treating a race as a data defect.
Check yourself
Why does the reconciliation use IS DISTINCT FROM and not <>?
Answer
If the balance column contains NULL, NULL <> 0 gives UNKNOWN and the row does not reach the result. IS DISTINCT FROM treats NULL as a value of its own and shows such an account.
Reconciliation showed an account with a balance of 20.00 and a single deposit with status pending. Is it a bug?
Answer
It depends on the rule: if the balance must count only completed operations, yes, a defect. If expected credits are reserved, the reconciliation rule must change. The question is clarified in the requirements, not guessed.
Related lessons: “How do you store money correctly and what bugs are there?”, “What is the difference between a condition in ON and in WHERE with a LEFT JOIN?”, “How do you compute a running total?”, “How do you find anomalies and data integrity violations?”.
In an interview.Junior: I sum the completed transactions of each account with their direction and compare with the stored balance. The query returns only mismatches, normally it is empty. Middle/Senior: The details matter: LEFT JOIN so as not to lose accounts with no operations, the status condition not in WHERE, COALESCE for an empty sum and IS DISTINCT FROM for NULL. I reconcile on a data snapshot or without load, check the list of operation types and clarify whether pending is part of the balance.
How do you use SQL in automated tests?
In automated tests SQL prepares data, checks what the client cannot see and cleans up by a marker; the query runs in Node. Cypress uses cy.task, because the test runs in the browser, while Playwright connects to the database straight from the test. The pg driver returns NUMERIC and BIGINT as strings and cy.task is not retried, so a write is awaited with a recursive call in Cypress and expect.poll in Playwright.
SQL · QA practice
Cypress cannot connect to a database directly. Where does the SQL run and what goes into the test?
A Cypress test clicks a button and must check a row in the database. But import { Client } from 'pg' in the test file does not work: the test code runs in the browser, and a connection to PostgreSQL is a TCP connection a browser does not open. Playwright does not have this problem, but has others: the time of the write, the number type and the connection lifecycle. This lesson is about how SQL gets into automated tests in both tools and which rules give stable checks.
How it works and why
In Cypress the configuration runs in a separate Node.js process. A task is added there by name, and the test calls it with the cy.task command: the arguments are serialised and passed to the Node process, the code with the database driver runs there, and the result goes back to the browser. A task must return a value: Cypress treats undefined as an error, so return null or an array of rows. Playwright runs tests in Node.js right away, so the database client connects directly, conveniently through a fixture that opens a connection pool once per worker.
The path of an SQL query from a Cypress test
Figure 1. The browser never sees the database: a Node process stands between it and PostgreSQL.
Example: checking a record after a click
Cypress: the task in the config and the call in the test.
cy.contains('button', 'Top up 500').click();
// cy.task is not retried: .should checks what was already returned
cy.task('dbQuery', {
sql: 'SELECT COUNT(*)::int AS n FROM transactions WHERE account_id = $1',
params: [10],
}).its('0.n').should('eq', 1);
Playwright: a fixture and a test with polling.
// fixtures.tsimport { test as base, expect } from'@playwright/test';
import { Pool } from'pg';
exportconst test = base.extend<{}, { db: Pool }>({
db: [
async ({}, use) => {
const pool = newPool({ connectionString: process.env.DB_URL });
awaituse(pool);
await pool.end();
},
{ scope: 'worker' }, // one connection pool per worker
],
});
export { expect };
test('top-up is saved once', async ({ page, db }) => {
await page.goto('/wallet');
await page.getByRole('button', { name: 'Top up 500' }).click();
// polling, not a pause: the record may appear with a delayawait expect
.poll(async () => {
const { rows } = await db.query(
'SELECT COUNT(*)::int AS n FROM transactions WHERE account_id = $1',
[10],
);
return rows[0].n;
})
.toBe(1);
});
Two small things on which first attempts break. First, the pg driver returns NUMERIC and BIGINT (including the result of COUNT(*)) as strings so as not to lose precision, so expect(rows[0].balance).toBe(750) fails because the value is '750.00'. Hence COUNT(*)::int in the examples, and sums are compared to a string or converted explicitly. Second, cy.task is a command, not a query: .should after it does not repeat the task itself. So waiting for a record in Cypress is written as a recursive function that calls the task again until success or a timeout, while in Playwright it is expect.poll.
Limits and alternatives
A test that goes into the database is tied to the schema: renaming a table breaks it, although nothing changed for the user. So the database is used where the client sees nothing, and the rest is checked through the API or the UI. Rules that make such tests maintainable: a separate database user for tests with minimal rights (read, and write only in a test schema); the password and address in environment variables, not in the repository; the test creates its own data and does not depend on another test's data; cleanup by marker in a teardown hook; one connection or pool, not a new connection per query. The default cy.task timeout is 60 seconds (taskTimeout), so a slow query is visible at once.
Common mistakes
Importing a database driver directly into a Cypress test file: the code runs in the browser and does not bundle.
A task with no return: Cypress reports that the task did not return a value.
Comparing NUMERIC with a number: the driver returns a string.
A query right after a click with no waiting: the test is unstable on a slow CI.
An SQL string built from the test's input instead of parameters: the same risks as in the application.
Database credentials in the test code or the repository.
Check yourself
In a test expect(rows[0].balance).toBe(750) fails with Expected 750, Received "750.00". Why and what to do?
Answer
The pg driver returns NUMERIC as a string so as not to lose precision. Compare with the string '750.00', or cast the type in the query, or parse the number explicitly, keeping in mind that for money exact decimal arithmetic is better than float.
A Cypress test checks a record with cy.task(...).its('0.n').should('eq', 1) but on CI sometimes sees 0. Why does the retry not help?
Answer
cy.task is a command: it runs once, and .should repeats only the check of the value already received. A recursive function is needed that calls the task again until it gets 1 or time runs out.
Related lessons: “API validation through the DB”, “How do you verify in the database the result of an action in the UI?”, “How do you prepare and clean up test data with SQL?”, “What is SQL injection and how do you test for it?”.
In an interview.Junior: In Cypress browser code has no access to the database, so the query runs in Node through cy.task with the pg library and parameters. In Playwright I connect to the database directly, conveniently through a fixture. I keep credentials in environment variables and clean up data by marker. Middle/Senior: I know the nuances: a task must return a value, cy.task is not retried, pg returns NUMERIC and BIGINT as strings, so in Playwright I wait for a record with expect.poll and in Cypress with a recursive call. I use the database where the client sees nothing, because a test that knows the schema is more fragile.
API validation through the DB
Validation through the DB checks what the server stored, because the response shows only what it decided to say. The id from the response locates the row, which is compared: sent fields must match, server-set fields follow a rule, and derived and related records are checked. For an update, snapshots before and after are compared; for a delete, physical and soft deletion are distinguished. For simple CRUD a repeat GET is enough.
SQL · QA practice
The API answered 201 with the right body. Is the record in the database really the same as in the response?
An API response is what the server decided to say. The database holds what it saved. Between them there is a layer of transformations: serialisation, rounding, field mapping, default values. A test that looks only at the response can pass when an amount is saved with lost precision, a password is written in plain text, and a delete only removed the record from the response. This lesson is about what to check in the database after creating, updating and deleting through the API.
How it works and why
The scheme is simple: send a request, take the identifier from the response, read the row by it and compare. Fields fall into three groups. Sent by the client must match the row. Filled by the server: created_at, the default status, the author. They are compared not with what was sent but with a rule: the time is close to "now", the status equals the initial one. Derived and related: order items, stock, an audit entry. Separately look at the storage format: the password is hashed, the date is a point in time (timestamptz), the amount is in a type with precision.
Example: create, update, delete
Create, with a check of the sent and server fields:
const res = await request.post('/api/orders', {
data: { sku: 'A-1', qty: 2 },
});
expect(res.status()).toBe(201);
const { id } = await res.json();
const { rows } = await db.query(
'SELECT sku, qty, status, created_at FROM orders WHERE id = $1',
[id],
);
expect(rows).toHaveLength(1);
expect(rows[0]).toMatchObject({ sku: 'A-1', qty: 2, status: 'new' });
// a server-filled field: the creation time close to "now"expect(Date.now() - rows[0].created_at.getTime()).toBeLessThan(60_000);
The response and the row in the database
API response
field
value
id
501
sku
A-1
qty
2
total
99.99
orders, id = 501
field
value
sku
A-1
qty
2
status
new
total
99.90
Figure 1. The fields match except total: 99.99 in the response against 99.90 in the database. Only comparing with the row reveals this.
For an update the state before and after is compared: only what is expected should change. After a PATCH that changes the quantity, qty, the derived total and updated_at change, while created_at, the author and the rest stay:
const read = async () =>
(await db.query('SELECT * FROM orders WHERE id = $1', [id])).rows[0];
const before = awaitread();
await request.patch('/api/orders/' + id, { data: { qty: 3 } });
const after = awaitread();
// Date compares by reference, so compare through JSONconst changed = Object.keys(after).filter(
(k) => JSON.stringify(after[k]) !== JSON.stringify(before[k]),
);
expect(changed.sort()).toEqual(['qty', 'total', 'updated_at']);
For a delete check what exactly happened to the row. A physical delete removes the record, while a soft delete keeps it with a deleted_at mark. In both cases the API may answer 404 to a repeated GET, so the response alone proves nothing here. Look separately at related tables: whether order items were removed, whether orphan rows are left, whether the stock was returned.
Two ways to delete: what stays in the database
Physical delete
DELETE
The row is gone. Check related tables and that other rows are intact.
Soft delete
deleted_at
The row exists and deleted_at is set. Check that lists do not show it.
Figure 2. Both approaches are legitimate: which one the requirement wants is found out before the test.
Limits and alternatives
Tying to the schema makes a test fragile, so for simple CRUD a repeated GET through the API is enough. The database is needed where the client does not see the truth: the storage format, values the API does not return (a password hash), side records, the consequences of a failure in the middle of an operation. If the response returns before the commit or processing is asynchronous, a query right after the response finds nothing, so waiting is done by polling. Database access on a test environment is best given read-only: a test that writes to the database bypassing the API checks no longer the system but its own data.
Common mistakes
Treating a 201 response as proof of saving: the record may be saved differently or not saved.
Comparing server fields with what was sent instead of a rule: created_at never equals what went into the request.
Comparing Date objects with !==: different instances are always "different".
Not checking related tables after a delete or an update.
Accepting a password in the database that matches the one sent: that is plain text.
Check yourself
DELETE /orders/5 answered 204 and GET /orders/5 gives 404. What else to check in the database?
Answer
Whether the row was deleted physically or marked deleted_at (as required), whether related items were removed with no orphans left, whether the stock changed and whether there is an audit entry.
After PATCH { qty: 3 } a test checks only qty in the database. What does it miss?
Answer
Side changes: whether the derived total was recalculated, whether updated_at was updated and whether other fields did not change, for example created_at or the author. Comparing snapshots before and after catches extra changes.
Related lessons: “How do you verify in the database the result of an action in the UI?”, “How do you use SQL in automated tests?”, “How do you check that a balance matches the transaction history?”, “What is SQL injection and how do you test for it?”.
In an interview.Junior: After creating I take the id from the API response, make a SELECT by it and check that the record exists and the fields match what was sent. I also look at server fields: created_at, the default status. Middle/Senior: For an update I compare snapshots before and after so that only the expected fields change. For a delete I tell physical from soft and look at related tables. I check the storage format: password hash, dates, amount precision. The database is for what the client does not see, the rest is cheaper to read through the API, and I ask for read-only database access.
How do you use a copy of the production database for tests without breaking privacy?
Real personal data is not copied into a test database: it is masked before the copy leaves the perimeter, or synthetic data is used. The mask must be stable across tables to keep the links. A hash, even with a secret key, is not anonymisation. QA scans for leftovers with queries against the mask and checks integrity, formats and every copy, including logs and dumps.
SQL · SQL in QA work
The test database holds real customer emails, and a dump ended up in a CI attachment. How to avoid that?
A copy of the production database gives the most realistic data: real volumes, dirty values, rare combinations. But together with them the personal information of customers travels into the test environment, logs, snapshots and dumps. A team that once "just copied production" turns every laptop and every CI artifact into a place where a leak can happen. This lesson is about making the copy fit for tests and safe: masking, its limits and the checks QA performs.
How it works and why. Two notions are distinguished. Pseudonymisation replaces identifiers but keeps the ability to restore them with additional information (a mapping table, a key). Recital 26 of the GDPR says such data is still treated as information about an identifiable person. Anonymisation makes the person not identifiable, and then the data protection principles do not apply; this is judged by whether identification is "reasonably likely" given cost, time and available technology. For tests, in practice this means: masking happens before the copy leaves the protected perimeter, and whether it is truly anonymous is decided together with the person responsible for data protection. This is not legal advice.
Technique
Example
Risk
Substitution
user1@example.test
loses format and distribution
Hash with a secret key (HMAC)
same input, same output
without the key values are guessed
Generalisation
birth date, year only
rare combinations
NULL
phone = NULL
breaks phone tests
Example: masking and links between tables. The schema has people (name, email, phone) and logins, where the email repeats. Masking one table breaks the link:
UPDATE people SET
full_name = 'User ' || id,
email = 'user' || id || '@example.test',
phone = '+3800000' || lpad(id::text, 5, '0');
SELECTcount(*) FROM people p
JOIN logins l ON l.email = p.email; -- 0
Before masking both rows joined, after it the result is 0: logins kept the real addresses, so it is a leak and a lost link at once. The fix: first collect the mapping of old to new addresses, mask both tables through it, then delete the mapping itself: it is the key to re-identification. Then count(*) is 2 again and the leftover scan returns 0.
Only people was masked
people
id
email
1
user1@example.test
2
user2@example.test
logins
email
anna@mail.test
ivan@mail.test
Figure 1. In people the addresses are already masked, in logins the real ones stayed: a JOIN on email finds no pair, and the real addresses are still in the test database.
-- instead of the UPDATE people above, on the still unmasked copyCREATE TEMP TABLE email_map ASSELECT email AS old,
'user' || id || '@example.test'AS new
FROM people;
UPDATE logins l SET email = m.new
FROM email_map m WHERE l.email = m.old;
UPDATE people p SET email = m.new
FROM email_map m WHERE p.email = m.old;
DROPTABLE email_map;
SELECTcount(*) FROM logins
WHERE email !~ '@example\.test$'; -- 0
What QA checks.
A scan for leftovers: a query that looks for values that do not match the mask. In the example WHERE email !~ '@example\.test$' returned 0 rows, and after one name was edited by hand the check against the name mask found that row.
Integrity: foreign keys, uniqueness and links by value (like the email above) still work.
Fitness: phone and email formats pass the application validation, and the data distribution did not become identical for every row.
All copies: free text, JSON fields, log tables, replicas, backups and dumps QA creates itself.
Limits and alternatives. Plain hashes of an email or a phone do not protect: the value space is small and they are guessed by brute force, so a hash with a secret key (HMAC) is used, with the key stored apart from the data; this is still pseudonymisation, not anonymisation. Even without names a person can be recognised by a combination of city, birth date and job title, so rare combinations are generalised. When masking is impossible or the risk is high, synthetic data replaces the copy: it is generated from the schema and domain rules, and dirty cases are added by hand. This gives reproducibility, but real production anomalies have to be invented. The approach depends on the risk level and the rules of the organisation.
Common mistakes.
Masking only the main table and leaving the same values in neighbouring tables, logs or JSON: the leak stays.
Masking each table randomly and differently: links by value stop matching and tests fail with no cause in the code.
Treating a hash, even a keyed one, as anonymisation.
Masking already on the test environment: by then the real data is outside the perimeter.
Check yourself
After masking, a login-by-email test fails, although people and logins used to share the addresses. What most likely happened?
Answer
The email was masked in one table and the real values stayed in the other, so the link by value disappeared and a leak appeared as well. The mask is computed once and applied to every table, for example through a mapping of old to new addresses.
A team replaced the email with md5(email) and considers the data anonymous. What do you say?
Answer
At best this is pseudonymisation: the value space is small and the hash can be recovered by brute-forcing known addresses. A hash with a secret key stored separately makes guessing harder, but the data stays pseudonymised. Anonymity needs generated replacement values and generalised rare combinations.
Related lessons: "How do you prepare and clean up test data with SQL?", "Test data strategies", "Secrets and PII in logs, noise and retention".
In an interview.Junior: Real personal data is not copied into a test database: it is masked or generated data is used. Middle/Senior: I distinguish pseudonymisation from anonymisation, I mask before the copy leaves the perimeter by a stable rule to keep the links, and I check for leftovers with queries against the mask. I do not count a hash as anonymisation, and for risky data I use synthetic data.
What does QA check before, during and after a schema migration: compatibility, rollback, locking?
QA checks a schema migration in three directions: compatibility, rollback and locking. During a deployment both old and new code run, so both pairs of versions and schemas are checked. QA watches who waits for whom in pg_stat_activity and measures how long a lock is held. After a failure it looks for invalid indexes and unvalidated constraints, and the rollback is rehearsed.
SQL · SQL in QA work
The migration is green in CI, but during the deployment half of the servers still run the old code and fail. What was not checked?
The usual migration check answers the question "is the data right after it". But in a live system a migration runs while users work, and old and new code share one database for a while. The separate questions: will the old version fail, can we go back, and how long will the table stay locked. Comparing data before and after is covered in the lesson on testing migrations; this one is about the rest: compatibility, rollback and locking.
How it works and why. During a rolling deployment two dangerous pairs are possible: the old application with the new schema (the migration has run, servers are still updating) and the new application with the old schema (a schema rollback or a delayed migration). So for every change QA asks about both pairs. Renaming a column breaks the first: in a test the old version query SELECT email after RENAME COLUMN email TO mail gave column "email" does not exist. Adding a nullable column does not break it.
Phase
Question
Evidence
Before
Which lock does each statement take?
rehearsal on a copy
Before
Does the old version work?
its tests on the new schema
During
Who waits for whom?
pg_stat_activity
After
What was left unfinished?
system catalogs
During: who blocks whom. While the migration runs in the rehearsal, ordinary traffic or at least a few queries are run in parallel and QA watches whether they wait. The migration total time matters less than how long a strong lock is held: a batched backfill can take long while the table stays available.
SELECT pid, wait_event_type,
pg_blocking_pids(pid) AS blockers,
left(query, 40) AS query
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0;
The queue behind an ALTER is covered in the lesson "How do you change a schema without downtime: expand/contract, CONCURRENTLY and NOT NULL?"; here what matters is that no ordinary queries appear in the output during the rehearsal. If they do, the migration statement takes an excess lock or waits too long, and it is rewritten (lock_timeout, CONCURRENTLY).
After: what was left unfinished. A failed migration is not always rolled back completely: invalid indexes remain after a failed CREATE INDEX CONCURRENTLY, and a NOT VALID constraint without VALIDATE checks only new rows. Both states are visible in the catalogs:
-- indexes that queries ignoreSELECT indexrelid::regclass FROM pg_index
WHERENOT indisvalid;
-- constraints that skip old rowsSELECT conname FROM pg_constraint
WHERENOT convalidated;
In a test the first query returned an index after a uniqueness violation (indisvalid = false), the second showed a constraint before VALIDATE (convalidated = false) and true after it. An empty result of both queries is part of the done criteria.
Rollback. The rollback plan is checked, not written as "see the down script". Questions: does it lose data (dropping a column is permanent), is it compatible with the code that already runs, and is there a faster way forward. For big tables a fix forward (a new migration) is often safer than a rollback. In PostgreSQL most DDL runs in a transaction and rolls back completely, but CONCURRENTLY does not work in a transaction, so it has no rollback: its leftovers are cleaned up by hand (see the lesson "How do you change a schema without downtime…"). A rollback rehearsal on a copy: after the new code has run for a while, a query on the new column shows how many values the down script would lose. If it is not zero, a rollback without a backup of the column is unsafe and the plan becomes a fix forward.
-- before running the down scriptSELECTcount(*) FROM orders
WHERE note ISNOTNULL; -- N valuesALTERTABLE orders DROP COLUMN note;
-- the N values are gone for good
Limits and alternatives. A rehearsal on a copy does not reproduce the real concurrency and long transactions of production, so locking is checked under a load of similar shape (long reports, batch jobs). For critical tables the migration is started with a wait limit and a ready retry plan. In MySQL the analogue of a lock check is the explicit ALGORITHM and LOCK in the statement: if the operation does not support the requested mode it is rejected, and that shows already in the rehearsal.
Common mistakes.
Testing only the new application version on the new schema: the pair "old code, new schema" is left out.
Considering a migration safe because it is fast: what matters is how long the lock is held and the queue behind it.
Not checking the catalogs after a failure: an invalid index or an unvalidated constraint stays silently.
Having a down script nobody has run: the first run happens during an incident.
Check yourself
A migration renames a column and every test of the new code is green. Which pair do you check additionally and what do you expect?
Answer
The old application on the new schema: its queries to the old name fail with a missing-column error. That is why a rename is split into expand/contract.
After the migration everything works. Which two catalog queries do you run before closing the task?
Answer
A search for invalid indexes (pg_index, indisvalid) and unvalidated constraints (pg_constraint, convalidated): both must return an empty result.
The down script drops a column added yesterday. What do you check before rolling back?
Answer
How much data the new code has already written to it: DROP COLUMN loses it for good, so either keep the column or fix forward.
Related lessons: "How do you test database migrations?", "How do you change a schema without downtime: expand/contract, CONCURRENTLY and NOT NULL?", "What is EXPLAIN and how do you use it?".
In an interview.Junior: After a migration I check that the data is in place, the application works and there is a way back. Middle/Senior: I check both version pairs during a deployment, I see who waits for whom (pg_stat_activity) and I measure how long the lock is held, not only the duration. After a failure I look for invalid indexes and unvalidated constraints, and I do not consider a rollback safe without a rehearsal.