QA Interview Hub · Knowledge base · Quizzes · Українська

QA Fundamentals

SQL for QA

checking data in the database

What basic SQL queries should QA know?

QA needs basic SQL: SELECT with WHERE, ORDER BY, LIMIT, DISTINCT, and aggregates with GROUP BY and HAVING. A row condition goes in WHERE and an aggregate condition in HAVING. NULL means an unknown value: comparing with it yields UNKNOWN, so <> and NOT IN silently drop rows, and the check must use IS NULL.

QA Fundamentals · SQL for QA

The report shows 118 transactions and the table has 121. Where did three go?

A tester writes a query "all transactions except failed ones": WHERE status <> 'failed'. The table has 121 rows, two failed, so 119 are expected. The query returns 118. One row vanished with no error and no warning. Queries like this are reassuring, because they run successfully while the result is wrong. This lesson is about the basic SQL set QA needs, the order in which the database executes a query and NULL, the source of most silent mistakes.

How it works and why. SQL is declarative: you describe which result you want, not how to compute it. Still, inside, a query is logically executed in a fixed order, and knowing that order explains almost every "why does this not work". First FROM defines the table, then WHERE filters individual rows, GROUP BY collects them into groups, HAVING filters groups, SELECT computes columns and aliases, ORDER BY sorts, LIMIT cuts. (Physically the optimiser may act differently, but the result must match this order.)

The logical order of executing a query

1. FROMwhere the rows come from2. WHEREfilters rows3. GROUP BYbuilds groups4. HAVINGfilters groups5. SELECTcomputes columns6. ORDER BYsorts the result7. LIMITcuts the number
Figure 1. WHERE works on individual rows before grouping, HAVING on groups after it. So an aggregate in WHERE is impossible, and an alias from SELECT does not exist in WHERE yet.

Simple rules follow. A condition on a row lives in WHERE, a condition on an aggregate (SUM(amount) > 10000) in HAVING. An alias created in SELECT does not exist in WHERE yet. Without ORDER BY the row order is not guaranteed, so "the first" or "the last" row and LIMIT without sorting give an unpredictable result. QA's basic set: SELECT with WHERE (comparison, IN, BETWEEN, LIKE, IS NULL), ORDER BY, LIMIT, DISTINCT, aggregates (COUNT, SUM, AVG, MIN, MAX) and GROUP BY with HAVING.

Why the row vanished: NULL. NULL means "the value is unknown", not "an empty string" or zero. A comparison with NULL gives not "false" but a third value, UNKNOWN, and WHERE keeps only rows where the condition is true. So status <> 'failed' is not true for a row with status = NULL and the row is dropped. In the same way status = NULL never fires: you must use IS NULL. A second consequence: COUNT(*) counts rows, while COUNT(status) counts only those where the value is not NULL.

Example: from a wrong number to a data defect. The initial query and its result:

SELECT COUNT(*)
FROM transactions
WHERE status <> 'failed';
-- 118

Instead of guessing the cause, look at what is in the table. A diagnostic query compares the counts:

SELECT COUNT(*)      AS total,
       COUNT(status) AS with_status,
       SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) AS failed
FROM transactions;
-- illustration: total 121, with_status 120, failed 2

The gap between 121 and 120 says that one row has no status, and 118 is 121 minus 2 failed minus 1 row with NULL. The fixed query and a separate query for the defect itself:

-- everything except failed, including an empty status: 119
SELECT COUNT(*)
FROM transactions
WHERE status <> 'failed' OR status IS NULL;

-- the data defect itself: rows with no status
SELECT id, user_id, created_at
FROM transactions
WHERE status IS NULL;

Two conclusions here. First: the query is fixed and now counts what was intended. Second, and more important: a row with no status is itself a finding. If the status is mandatory by the requirement, there is a defect in the data (its cause is sought in the code that creates the record), and it must be written up as a bug. This is how SQL in the hands of QA works as a way to learn about the system, not only as a way to count.

Another sample of what QA writes most often: a monthly report with grouping and a filter on groups.

SELECT status, currency, COUNT(*) AS cnt, SUM(amount) AS total
FROM transactions
WHERE created_at >= '2026-10-01' AND created_at < '2026-11-01'
GROUP BY status, currency
HAVING SUM(amount) > 10000
ORDER BY total DESC
LIMIT 10;

The date range is written as "from the start of October inclusive to the start of November exclusive". The variant BETWEEN '2026-10-01' AND '2026-10-31' on a column with time drops everything that happened on 31 October after midnight, because the bound "2026-10-31" means 00:00. Money amounts must be stored in fixed-precision types (DECIMAL/NUMERIC), not FLOAT: otherwise SUM accumulates errors.

The same search for non-failed rows, written two ways

Wrong

status <> 'failed'

Rows with NULL in the status silently vanish. The result 118 looks plausible and alarms nobody.

Right

<> 'failed' OR IS NULL

The condition handles NULL explicitly. The result is 119, and the row with no status is found separately as a data defect.

Figure 2. A condition with NULL needs explicit handling. Compare counts through COUNT(*) and COUNT(column).

Limits and alternatives. SQL differs between databases. Limiting the number of rows is LIMIT in PostgreSQL and MySQL, TOP in SQL Server, FETCH FIRST in the standard. ILIKE exists only in PostgreSQL. Case sensitivity in string comparison depends on the collation: in MySQL it is insensitive by default, in PostgreSQL sensitive. So first find out which database the project uses. On large tables SELECT * without WHERE can load a shared environment: add LIMIT and a filter, and for slow queries look at EXPLAIN. Some checks can be done without the database: through the API or an admin panel. The database is needed when you must see what the user is not shown: side effects, service states, the state after a failure.

Common mistakes.

  • = NULL or <> NULL instead of IS NULL / IS NOT NULL: the condition never becomes true.
  • A <> or NOT IN filter on a column where NULL is possible: rows vanish without a warning.
  • An aggregate in WHERE: SQL rejects the query. For a condition on a group there is HAVING.
  • LIMIT without ORDER BY: the set of "first" rows is different every time.
  • BETWEEN for dates with time: the last day of the range is lost. A half-open interval is better.
  • SELECT * without limits on a large table of a shared environment: slow and harmful for others.
  • Money in FLOAT: differences of cents in sums and comparisons.

Check yourself

The orders table has 50 rows. SELECT COUNT(discount) FROM orders returns 32. What does it mean and how does it differ from COUNT(*)?

Answer

COUNT(discount) counts only rows where discount is not NULL, so 18 orders have no discount set (NULL). COUNT(*) would return 50, because it counts all rows. The difference is useful for checking: whether empty fields are expected or are a data defect.

Why does SELECT user_id, COUNT(*) FROM payments WHERE COUNT(*) > 1 GROUP BY user_id fail and how do you fix it?

Answer

WHERE runs before grouping, when there are no aggregates yet. A condition on an aggregate moves to HAVING: GROUP BY user_id HAVING COUNT(*) > 1. The general rule: a condition on a row goes in WHERE, a condition on a group in HAVING.

In an interview. Junior: I confidently use SELECT with filtering through WHERE, sorting and LIMIT, and the aggregate functions COUNT and SUM with GROUP BY. HAVING is for filtering already grouped results, unlike WHERE, which filters rows before grouping. Middle/Senior: I remember the logical order of executing a query, and it explains why an aggregate is impossible in WHERE and an alias is not available in it. I watch NULL separately: a comparison with it gives UNKNOWN, so <> and NOT IN silently drop rows, and COUNT(*) and COUNT(column) give different numbers. I write date ranges half-open, check money in fixed-precision types and clarify the database dialect at the start.

What kinds of JOIN are there?

JOIN kinds differ in how they treat an unmatched row: INNER drops it, LEFT and RIGHT keep their side with NULLs, FULL keeps both, CROSS pairs everything. A one-to-many join multiplies rows and inflates sums. A condition on the right table of a LEFT JOIN goes in ON; orphans are found with LEFT JOIN … IS NULL or NOT EXISTS, not NOT IN, which breaks on NULL.

QA Fundamentals · SQL for QA

After adding a JOIN the report total became bigger than the total in the table. Why?

A tester reconciles total revenue: the transactions table says 250, while a query with a JOIN to the audit log shows 300. It looks like an error in the data or in the system. In fact the query counted one transaction twice, because the log has two entries for it, and did not count another at all, because the log has none for it. This lesson is about how JOIN works, how its kinds differ and which mistakes it adds to checks.

How it works and why. The relational model splits data across tables: transactions in one, audit log entries in another, and the link is the transaction_id column. JOIN puts them back together: for each row of the left table it looks in the right one for rows that satisfy the ON condition and outputs one result row per pair. The kinds of JOIN differ in what happens to rows with no pair, and everything people expect from them follows from that.

Pairs of rows and a row with no pair

transactionsaudit_logt1t2t3a1 → t1a2 → t1a3 → t2t3 has no pair: INNER JOIN drops it,LEFT JOIN keeps it with NULLs on the right.
Figure 1. Each arrow is a result row. Row t1 has two entries, so it gives two rows. Row t3 has no pair.
KindWhat it returnsWhat QA uses it for
INNER JOINonly rows that have a pair in both tablescombine data when the link is mandatory
LEFT JOINall rows of the left; from the right the pair if there is one, otherwise NULLfind records without related data ("orphans")
RIGHT JOINthe mirror of LEFTrarely: the same is easier to write as LEFT with the tables swapped
FULL JOINall rows of both tables, with NULL where there is no paircompare two sets and see mismatches on both sides
CROSS JOINall possible pairs without a conditiongenerate combinations for test data

A special case, the self join: a table is joined to itself, for example an employee and their manager, or finding two records with the same value. MySQL has no FULL JOIN: it is replaced by a UNION of two LEFT JOINs. Choosing the kind is an answer to the question "what do I do with a row that has no pair": drop it, keep it with NULL or show it from both sides.

Example: the sum that grew, and orphans. The initial query and its result on a simplified data set (three transactions, two log entries for t1, one for t2, none for t3):

-- transactions: t1 = 100, t2 = 100, t3 = 50 (250 in total)
-- audit_log: two entries for t1, one for t2
SELECT SUM(t.amount)
FROM transactions t
JOIN audit_log a ON a.transaction_id = t.id;
-- 300: t1 counted twice, t3 is gone

Let us take it apart. For t1 there are two log entries, so its row is duplicated in the result and 100 is added twice. For t3 there is no entry, INNER JOIN drops it, and 50 disappears. A coincidence of two errors (an overstatement and an understatement) is especially dangerous, because the total looks plausible. This is "row multiplication" (fan-out): a one-to-many join repeats the left row as many times as there are right rows. The rule: before aggregating after a JOIN, think about how many rows will appear and whether the values you sum get duplicated. The fix depends on the goal:

-- the sum without a join: the source of truth is 250
SELECT SUM(amount) FROM transactions;

-- transactions with no audit entry (t3)
SELECT t.id, t.amount
FROM transactions t
LEFT JOIN audit_log a ON a.transaction_id = t.id
WHERE a.id IS NULL;

-- the same with NOT EXISTS (safer with NULL)
SELECT t.id, t.amount
FROM transactions t
WHERE NOT EXISTS (
  SELECT 1 FROM audit_log a WHERE a.transaction_id = t.id
);

The sum is taken from one table, where each transaction counts once. And the orphan search shows that t3 has no audit log entry: if it is mandatory by the requirement, it is a defect. The second query with LEFT JOIN … IS NULL and the third with NOT EXISTS give the same result. The third is more reliable, especially compared with NOT IN (SELECT …): if the subquery contains even one NULL, NOT IN returns no rows at all, and the check silently "passes".

The result on the same data

INNER JOIN

3 rows

t1, t1, t2. Transaction t3 vanished, and t1 appeared twice.

LEFT JOIN

4 rows

t1, t1, t2, t3. For t3 the right columns are NULL: that is what orphans are found by.

Figure 2. Both variants are right: they answer different questions. The difference is what to do with a row that has no pair.

Limits and alternatives. LEFT JOIN has one more subtlety: a condition on the right table belongs in ON, not in WHERE. A condition in WHERE on the right table drops rows with NULL and turns LEFT JOIN into INNER, and transactions with no event vanish from the report:

-- wrong: WHERE on the right table makes LEFT effectively INNER
SELECT t.id, a.event
FROM transactions t
LEFT JOIN audit_log a ON a.transaction_id = t.id
WHERE a.event = 'approved';

-- right: the condition in ON, transactions with no event stay
SELECT t.id, a.event
FROM transactions t
LEFT JOIN audit_log a
  ON a.transaction_id = t.id AND a.event = 'approved';

Besides JOIN, to check "is there a related record" EXISTS often fits, without duplicating rows. To compare two sets of values, use UNION or EXCEPT (MINUS in some databases). JOIN performance depends on indexes on the link columns, and on large tables of a shared environment a query with a stray CROSS JOIN can grow into hundreds of millions of rows, so start by limiting the selection.

Common mistakes.

  • Aggregating after a one-to-many JOIN without checking the row count: sums and counts are overstated.
  • Using INNER JOIN where you look for "what is missing": a row with no pair just disappears from the result.
  • Writing the condition on the right table of a LEFT JOIN in WHERE: the join quietly becomes INNER.
  • NOT IN with a subquery that contains NULL: an empty result that looks like "no orphans".
  • Forgetting the ON condition or writing it wrongly: a Cartesian product, millions of rows.
  • Not knowing that MySQL has no FULL JOIN: a UNION of two LEFT JOINs is needed.

Check yourself

The orders table has 100 orders and order_items has 3 items for each. How many rows does SELECT * FROM orders o JOIN order_items i ON i.order_id = o.id return, and what happens to SUM(o.total)?

Answer

There will be 300 rows if every order has exactly 3 items. Each row of orders is repeated as many times as it has items, so SUM(o.total) grows threefold against the real sum. For the sum of orders do not join with items, or aggregate separately.

How do you find customers who have no orders at all, and why is NOT EXISTS better than NOT IN?

Answer

LEFT JOIN orders ON orders.customer_id = customers.id WHERE orders.id IS NULL, or NOT EXISTS (SELECT 1 FROM orders WHERE customer_id = customers.id). NOT IN (SELECT customer_id FROM orders) returns an empty result when at least one customer_id in the subquery is NULL, and the mistake stays unnoticed.

In an interview. Junior: INNER JOIN returns only rows that have a pair in both tables, LEFT JOIN returns all rows of the left one and from the right one if there is a pair. I often use LEFT JOIN with a NULL check to find records with no mandatory related data, for example transactions with no audit log entry. Middle/Senior: I choose the kind of JOIN by what to do with a row that has no pair. I watch for row multiplication in one-to-many links: before summing after a JOIN I check the row count. I keep a condition on the right table of a LEFT JOIN in ON, use LEFT JOIN … IS NULL or NOT EXISTS to find orphans and avoid NOT IN because of NULL. I know FULL JOIN is emulated through UNION in MySQL.

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

1. API or UI response201 and a body: what the client sees2. The row in the databasethe record exists, values and status are right3. Side effectsledger entries, audit log, a queued event4. Invariantssum of entries = 0, the balance adds up
Figure 1. The first layer is visible to the client, the second is the one most often checked. The two highlighted lower layers find defects that the response will not show.

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

Response only

201, fields match

The test is green although there is no credit. Accounting will find the defect in a week.

Response and state

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.

Figure 2. Checking the state catches defects that are invisible from the status. It is cheap once the queries are ready.

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 BY or 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.

In an interview. Junior: After an action in the UI or API I check in the database that the record was created with the right values. I also look for duplicates and records without mandatory links, and I find users in the needed state for tests. On shared environments I only read unless I have permission to change data. Middle/Senior: I check in layers: the response, the row, side effects and invariants (the entries of a transfer sum to zero), because partial failures are not visible from the status. I parameterise queries and can run them over the whole table. For asynchronous results I poll with a timeout instead of sleeping. I keep SQL for what the API does not expose, because tests tied to the schema are brittle. I do not copy personal data into reports and make changes only on test records after a preceding SELECT.