How do you use SQL to verify data?
SQL verifies what was actually stored after an action in the UI or API, including side effects and invariants that the API response does not show. The check goes top-down: response, row, side effects, invariants (for example, the ledger entries of a transfer sum to zero). On shared environments it is read-only, and before an UPDATE or DELETE the same WHERE is run as a SELECT.
QA Fundamentals · SQL for QA
The API returned 201 and the database is empty. What do you check, and with what?
The test for creating a transfer is green: the response is 201 and the body has the right fields. A week later reconciliation shows that for such transfers money was debited from one account and not credited to the other. An API response tells only what the server decided to say to the client. What is really happening to the data is visible only in the database. This lesson is about when and why QA turns to the database, which checks really pay off and which safety rules apply on shared environments.
How it works and why. Each layer of the system tells about the state from its own side. The UI shows what was rendered, the API what it decided to return, and the database holds what is really stored, together with consequences the client does not see: ledger entries, audit records, service statuses, events for other services. A failure between layers looks like "all good" on the upper layers and a defect on the lower ones. So the check is built from the top down: the response, the row, side effects, invariants.
What to check after one action
An invariant is a property that must always hold, whatever the scenario. For money it is "the entries of each transfer sum to zero", "a balance equals the sum of entries", "a payment has exactly one record with this key". Invariants are especially valuable because they check a lot of data with one query and catch failures that no single test anticipated.
Example: from "201" to a handful of queries. The test made a transfer of 100.50 UAH from acc-1 to acc-2 and got 201. Earlier the check ended there. Now after the action a series of queries runs:
-- 1. the transfer row
SELECT id, from_account, to_account, amount, status
FROM transfers WHERE id = 't-501';
-- 2. ledger entries: we expect two
SELECT account_id, amount
FROM ledger_entries WHERE transfer_id = 't-501';
-- 3. invariant: the entries sum to zero
SELECT SUM(amount)
FROM ledger_entries WHERE transfer_id = 't-501';
-- 4. an audit log entry
SELECT COUNT(*) FROM audit_log WHERE transaction_id = 't-501';
Expectation: one transfer row, two entries (minus 100.50 and plus 100.50), the entries sum to zero, an audit record. The actual result:
Result (an illustration, shortened):
1. t-501 | acc-1 | acc-2 | 100.50 | pending OK
2. acc-1 | -100.50 only one entry
3. SUM = -100.50 must be 0.00
4. COUNT = 1 OK
A partial failure is found: the debit entry exists, the credit does not. The API response knew nothing about it. The bug report will show everything needed: the transfer ID, the queries that show the mismatch and the expectation from the requirement. And now scaling: the same invariant (the sum of a transfer's entries is not zero) can be run over the whole table to see how many transfers are affected:
SELECT transfer_id, SUM(amount) AS diff
FROM ledger_entries
GROUP BY transfer_id
HAVING SUM(amount) <> 0;
Such a check belongs to reconciliation at a minimal level, which a separate lesson covers. Among other typical queries in QA's work: finding duplicates and checking integrity.
SELECT idempotency_key, COUNT(*) AS cnt
FROM payments
GROUP BY idempotency_key
HAVING COUNT(*) > 1;
The query shows payments where the same idempotency key occurs more than once, that is, the protection against repeats did not work (more in the lesson on idempotency). Orphans are found in a similar way with LEFT JOIN … IS NULL, and data is prepared by finding a user in the needed state (with a balance above some amount, with a blocked card) instead of creating one by hand.
Two checks of the same test
201, fields match
The test is green although there is no credit. Accounting will find the defect in a week.
row, entries, invariant
The test is red at once: the entries do not sum to zero. The defect is found before the release, with exact queries in the report.
Safety rules. On shared environments the default is SELECT only. Changing data with a direct query is allowed only with explicit permission and on test records. Before UPDATE or DELETE, run the same WHERE as a SELECT and check the row count; on a local database a transaction with ROLLBACK is handy. A production database is not open to arbitrary queries: people work with replicas, masked copies and dashboards under company policy. Personal data and card details are not copied into bug reports, and queries with results do not contain them.
-- before an UPDATE or DELETE run the same WHERE as a SELECT
SELECT id, status FROM users WHERE email LIKE 'qa+%@example.com';
-- only if the number of rows is exactly what you expect
UPDATE users SET status = 'blocked'
WHERE email LIKE 'qa+%@example.com';
Limits and alternatives. Going to the database ties a test to the schema: after a table rename or a migration the queries break, and the schema is an internal detail that a client must not rely on. So for an ordinary state check prefer the API first (a GET after the POST) and leave SQL for side effects and invariants that the API does not expose. There are more nuances. Asynchronous processing means a row may appear with a delay, so in automation the query is repeated with a timeout rather than with a fixed pause. A replica may lag behind the primary. Time columns are stored in UTC, while the reporting date depends on the user's time zone. An uncommitted transaction of another session is not visible. Some teams give QA dedicated views or service endpoints for checks, which decouples tests from the schema.
Common mistakes.
- Treating an API response as proof of persistence: the state in the database and the side effects stay unchecked.
- Changing data on a shared environment without permission or without a preceding SELECT with the same WHERE: other people's tests can be ruined.
- Putting a fixed pause before checking an asynchronous result: the test fails one time and passes another. Polling with a timeout is needed.
- Copying personal data from the database into a bug report or chat: a breach of the data policy.
- Writing a query that relies on row order without
ORDER BYor on "the last" record: the result is unstable. - Checking everything through the database: tests become brittle to schema changes. The database complements the API, it does not replace it.
Check yourself
After POST /payments the API returned 201, and a database query by the payment ID found nothing. Name three possible causes before writing a bug.
Answer
Asynchronous processing (the record will appear later, so repeat the query with a timeout), the query goes to a different database or schema than the application writes to (the environment, a lagging replica), or the transaction was not committed (a rollback after the response). If after waiting and checking the environment the record is still missing, it is a bug: a 201 with no stored record.
Why is it useful, before an UPDATE or DELETE on a test environment, to run the same WHERE as a SELECT first?
Answer
To see which rows the change will touch and compare the count with the expected one. A mistake in the condition (a missing filter, the wrong range) can touch other people’s data, and without a transaction or a backup it cannot be rolled back. A SELECT is safe and changes nothing.