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

SQL

Database structure

constraints, indexes, normalization, migrations

What constraints are there and how do you test them?

Constraints are rules the database checks itself on every data change. They are PRIMARY KEY, FOREIGN KEY, NOT NULL, UNIQUE and CHECK (DEFAULT only supplies a value) and apply to every write path. For QA they are ready negative cases: the application must turn a refusal into a clear answer, for example 409, not 500. CHECK and UNIQUE let NULL through.

SQL · Constraints and indexes

Registering an existing email returns 500 with the database text. Whose bug is it?

A test registers a second user with the same email. The application answers "500 Internal Server Error" and the body shows the table and constraint name. The database did its job: it refused the duplicate. The bug is that the application did not turn the refusal into a clear answer. Constraints give QA a ready list of negative cases, and this lesson is about how to read and check them.

How it works and why. A constraint is a rule the database checks itself on every INSERT and UPDATE. Validation in a form or an API can miss a separate write path: an import, a script, another service. A constraint in the database applies to all paths at once, so it is the last line of defence. There is one more reason: a race. The application first runs SELECT "is there such an email", then INSERT. Two parallel requests both see "none" and both insert. Only a UNIQUE constraint in the database guarantees uniqueness, because the database serialises such conflicts.

The set: PRIMARY KEY (unique and not NULL, creates an index), FOREIGN KEY (a reference to an existing row), NOT NULL, UNIQUE, CHECK (any condition), DEFAULT (a value when the field is not passed; not a constraint, but it affects tests). Each violation has its own SQLSTATE code, from which the application must choose its answer.

ConstraintSQLSTATEWhat to check
NOT NULL23502a request without the field, with null and with an empty string
UNIQUE, PRIMARY KEY23505a duplicate, a duplicate in another case, parallel requests
FOREIGN KEY23503INSERT/UPDATE of a child with a missing parent, DELETE/UPDATE of the parent
CHECK23514boundaries: -0.01, 0, the largest value

Example: tables and two refusals.

CREATE TABLE users (
  id    integer PRIMARY KEY,
  email text NOT NULL,
  CONSTRAINT users_email_unique UNIQUE (email)
);
CREATE TABLE accounts (
  id      integer PRIMARY KEY,
  user_id integer NOT NULL REFERENCES users (id),
  balance numeric(12,2),
  CONSTRAINT balance_non_negative CHECK (balance >= 0)
);

The database rejects a duplicate email, and this is the code (23505) the application must catch:

INSERT INTO users VALUES (1, 'ana@test.com');
INSERT INTO users VALUES (2, 'ana@test.com');
-- ERROR:  duplicate key value violates unique constraint
--         "users_email_unique"
-- DETAIL: Key (email)=(ana@test.com) already exists.
-- (message shortened)

The correct API behaviour: 409 Conflict (or 422 naming the email field) and a text like "this email is already registered". The wrong one: 500 and the raw database text, which also reveals table and constraint names.

Now the trap. CHECK rejects a row only when the condition is false. If the condition gives UNKNOWN because of NULL, the row passes:

INSERT INTO accounts VALUES (1, 1, -5.00);
-- ERROR:  new row for relation "accounts" violates check
--         constraint "balance_non_negative"

INSERT INTO accounts VALUES (2, 1, NULL);
-- INSERT 0 1: accepted, although the balance is unknown

So CHECK (balance >= 0) without NOT NULL does not guarantee a non-negative balance: it can be unknown. Likewise UNIQUE treats two NULLs as different, so in a nullable column several rows with email = NULL pass (an empty string is an ordinary value, and a second one is a duplicate) (in PostgreSQL 15+ NULLS NOT DISTINCT changes this). And UNIQUE compares values literally: "Ana@test.com" and "ana@test.com" differ until uniqueness is built on lower(email).

Where the uniqueness rule lives

Code only

SELECT, then INSERT

Two parallel requests both see "none". The database holds two equal emails.

Database and code

UNIQUE + handling 23505

The database rejects the second request. The application turns the refusal into 409.

Figure 1. A check in code is for friendly messages, a constraint in the database is for the truth.

Limits and alternatives. A new constraint on a table with data may fail to apply: ALTER TABLE … ADD CONSTRAINT checks all existing rows. For CHECK and foreign keys the NOT VALID option applies only to new writes and checks old rows later with VALIDATE CONSTRAINT. Not everything fits a constraint: the rule "balance not less than the sum of reserves" across tables needs a trigger or a check in code. Constraints also slow bulk loading, so an import sometimes defers them, and then the data must be checked with a query after the load.

Common mistakes.

  • Checking only form validation and never bypassing it with a direct API request: the rule may exist only in the front end.
  • Assuming CHECK or UNIQUE catches NULL: both let it through.
  • Testing a duplicate sequentially and never trying two parallel requests.
  • Accepting 500 with database text as "error handling": it is a defect and a leak of schema details.
  • Forgetting the empty string: NOT NULL lets it through, a separate CHECK is needed.

Check yourself

The accounts table has CHECK (balance >= 0). A test inserts an account with balance = NULL and the insert succeeds. Is it a database bug?

Answer

No, this is how SQL works: CHECK rejects a row only when the condition is false, and NULL >= 0 gives UNKNOWN. If the balance must be set, NOT NULL is needed too (or DEFAULT 0). A finding for QA: the requirement "balance is non-negative" is incomplete without "balance is mandatory".

users.email has UNIQUE. A test registers ana@test.com, then Ana@test.com, and both succeed. What now?

Answer

UNIQUE compares strings literally, so these are different values to the database. If the requirement says email is case-insensitive, it is a defect: a unique index on lower(email) (or the citext type) and email normalisation in the application are needed. The decision depends on the requirement, so clarify it first.

In an interview. Junior: The main constraints are primary and foreign keys, NOT NULL, UNIQUE and CHECK (DEFAULT is not a constraint but a column default). For QA they are ready negative cases: I check how the application answers when the database rejects a write, for example a duplicate email must give a clear message, not 500. Middle/Senior: A constraint in the database is the last line of defence and the only protection from a race, so I check uniqueness with two parallel requests. I remember that CHECK and UNIQUE let NULL through and UNIQUE is case-sensitive. I look at the error code (23505, 23503, 23514) and at the user not seeing raw database text.

What happens to child records when a parent is deleted?

What happens to child records is set by the ON DELETE option of the foreign key, not by application code. NO ACTION (the default) and RESTRICT refuse the delete while child rows exist, CASCADE deletes them with the parent, SET NULL nulls the reference (the column must be nullable), SET DEFAULT sets the default. A cascade runs as a chain, so rows are counted in all dependent tables.

SQL · Constraints and indexes

A user was deleted and the whole history of their payments went with them. Is that intended?

The admin panel has a "Delete user" button. A tester presses it on an account with two accounts and nothing bad happens. A week later accounting cannot find this customer's payments: they were removed by a cascade. What happens to child records is decided not by application code but by the ON DELETE option on the foreign key. This lesson is about how to read it and which scenarios to check.

How it works and why. A foreign key guarantees that a reference does not dangle. So when the parent is deleted, the database must decide what to do with the rows that point to it. The options: NO ACTION (the default) and RESTRICT refuse the delete while child rows exist. The difference is subtle: NO ACTION is checked at the end of the statement and can be deferred to the end of the transaction (DEFERRABLE), while RESTRICT fires at once and cannot be deferred. CASCADE deletes the child rows together with the parent. SET NULL keeps them and clears the reference. SET DEFAULT sets the default value. Each option answers a business question: may a child exist without a parent.

Example: the same DELETE under different options. Accounts 1 and 2 belong to user 1, account 3 to user 2.

CREATE TABLE accounts (
  id      integer PRIMARY KEY,
  user_id integer NOT NULL
          REFERENCES users (id) ON DELETE CASCADE,
  balance numeric(12,2) NOT NULL
);
-- users: 1 = Ana, 2 = Bo
-- accounts: (1, user 1), (2, user 1), (3, user 2)
DELETE FROM users WHERE id = 1;

The accounts table before and after DELETE with CASCADE

before
iduser_idbalance
11100.00 lost
2150.00 lost
3270.00
after
iduser_idbalance
3270.00
Figure 1. Deleting one user silently took two accounts. A cascade does not report how many rows vanished.
-- the same with ON DELETE NO ACTION (the default)
DELETE FROM users WHERE id = 1;
-- ERROR:  update or delete on table "users" violates foreign
--         key constraint "accounts_user_id_fkey" on table "accounts"
-- DETAIL: Key (id)=(1) is still referenced from table "accounts".
-- (message shortened)

Note the chain. If transactions also reference accounts with CASCADE, deleting the user takes them as well. A user with 2 accounts and 100 transactions each gives 1 + 2 + 200 = 203 deleted rows from one command. With SET NULL it is different: the column must be nullable, otherwise the clearing itself violates NOT NULL and the delete fails with error 23502. And the rows left with an empty user_id ("orphans") break reports that JOIN and lose them.

Two legitimate delete policies

Hard

ON DELETE CASCADE

Child data is gone for good. Fits service data (tokens, drafts), not financial history.

Soft

deleted_at

The row stays and queries hide it. History survives, but every query needs the filter and the email must be freed.

Figure 2. The choice depends on requirements: what law or business says must be kept.

Soft deletion moves the complexity into queries and uniqueness:

UPDATE users SET deleted_at = now() WHERE id = 1;

-- email uniqueness among live rows only
CREATE UNIQUE INDEX users_email_live
  ON users (email) WHERE deleted_at IS NULL;

Limits and alternatives. A cascade in the database knows nothing about files, caches and external systems: rows vanished while document scans stayed in storage. Deleting a parent with CASCADE on an unindexed foreign key column can be slow, because for each parent the database looks for children by a full scan (see the lesson on indexes). For personal data the requirement may be the opposite: delete not only the row but all copies. Then the test checks complete erasure, not "nothing broke".

Common mistakes.

  • Testing only the deletion of a parent without children: ON DELETE does not fire and the rule stays unchecked.
  • Not counting rows before and after: a cascade shows nothing, vanished data is visible only in counters.
  • Treating "500 on delete" as normal: it should be a clear "there are linked accounts".
  • Forgetting "orphans" after SET NULL and soft-deleted rows in reports and search.
  • Checking on an empty database: the rule shows only on data with relations.

Check yourself

accounts.user_id has NOT NULL and ON DELETE SET NULL. What happens on DELETE of a user who has an account?

Answer

The delete fails: the database tries to set user_id = NULL but NOT NULL forbids it (23502). The combination is contradictory, a finding in the schema: either the column must be nullable or another option is needed.

A user has 2 accounts, each with 100 transactions. Both foreign keys have CASCADE. How many rows vanish after DELETE of this user?

Answer

203: 1 user, 2 accounts and 200 transactions. That is why before a cascade test you count rows in all dependent tables, not only the one being deleted.

In an interview. Junior: It is set by ON DELETE on the foreign key: RESTRICT and NO ACTION forbid the delete while child records exist, CASCADE deletes them with the parent, SET NULL clears the reference. I check that the behaviour matches the requirements. Middle/Senior: I count rows in all dependent tables before and after, because a cascade runs in a chain and reports nothing. Separately I check that history which must be kept is not lost, that no orphans remain after SET NULL, and that soft deletion does not break uniqueness and reports.

What is an index and why is it needed?

An index is a separate ordered structure, most often a B-tree, that finds rows in a few steps instead of reading the whole table (Seq Scan). It speeds up reads but takes space and slows down writes. PostgreSQL indexes PRIMARY KEY and UNIQUE itself, while foreign keys must be indexed by hand. Whether an index works shows only in the query plan.

SQL · Constraints and indexes

The transactions filter is instant on dev and takes 4 seconds on a staging with millions of rows. What to check?

The feature works, tests are green, but on a staging close to production the history page opens in seconds. On dev there were a hundred rows and any way of searching looked fast. The first hypothesis in such a case: there is no index for this filter. The lesson explains what an index is, why it speeds up reads and slows down writes, and how to check that it really works.

How it works and why. Without an index, to find the rows of one account the database reads the whole table: Seq Scan, and the time grows with the number of rows. An index is a separate ordered structure, most often a B-tree: keys are stored sorted and a lookup descends the tree in a few steps instead of scanning everything. The analogy with a book's subject index is exact. The price is real too: an index takes space, and every INSERT, UPDATE of a key column and DELETE must update it as well. So you index not everything but what is searched, joined and sorted by.

PostgreSQL creates an index itself for PRIMARY KEY and UNIQUE, but not for foreign keys: the account_id column in transactions must be indexed by hand, otherwise JOINs and cascading deletes read the whole table. The planner decides itself whether to use an index: on a small table, or when the filter returns most rows, Seq Scan is cheaper, and that is fine.

Example: a composite index and column order. The query from the history tab: an account and a period.

CREATE INDEX idx_transactions_account_created
  ON transactions (account_id, created_at);

-- on a big live table, without blocking writes
CREATE INDEX CONCURRENTLY idx_transactions_status
  ON transactions (status);

The composite index (account_id, created_at) is sorted first by account and inside it by date. So it serves the filter "account = 10" and "account = 10 and date from…" well, and also sorting by date within an account. A filter on created_at alone it usually serves badly: rows of one date are scattered across all accounts. (Newer PostgreSQL versions can sometimes skip the first column, but do not rely on it.) Such a filter needs its own index on the date. Hence the rule: the first column is the one you always filter by, usually by equality.

The (account_id, created_at) index: what fits

Fits

account_id = 10

Also account_id = 10 AND created_at >= date, and ORDER BY created_at within an account.

Poor

created_at >= …

No first column: mostly Seq Scan or a slow pass over the whole index.

Figure 1. The column order of a composite index decides which filters it speeds up.

Another trap: an index that exists but is not used. A function over the column, such as lower(email), does not match an index on email. The same goes for LIKE '%abc' (a B-tree searches by the start of a string) and for comparing with another type that forces a cast of the column.

-- an index on email will not help this query
SELECT * FROM users WHERE lower(email) = 'ana@test.com';

-- an expression index will help
CREATE INDEX idx_users_email_lower ON users (lower(email));

The existing indexes are visible in the catalogue:

SELECT indexname, indexdef
FROM pg_indexes
WHERE tablename = 'transactions';

Limits and alternatives. A plain CREATE INDEX blocks writes to the table while it builds, so on a live table CREATE INDEX CONCURRENTLY is used (it is slower and cannot run inside a transaction). Extra indexes slow writes, so they are reviewed too: an unused index is a cost with no benefit. A B-tree is not the only kind: for full-text search and JSON there is GIN, for ranges and geography GiST. For frequent filters on a small subset of rows there are partial indexes (WHERE status = 'pending'). An index does not cure a bad query: SELECT * without a limit and fetching half the table stay slow.

Common mistakes.

  • Judging speed on a dev with a hundred rows: the plan depends on volume and statistics.
  • Indexing every column "just in case": writes slow down with no benefit.
  • Forgetting an index on a foreign key: JOINs and cascading deletes read the whole table.
  • Getting the column order of a composite index wrong.
  • Assuming an index "exists, so it works": that is visible only in the query plan.

Check yourself

There is an index (account_id, created_at). A query filters only WHERE created_at >= '2026-09-01'. Should you expect this index to work fast?

Answer

Usually not: the index is sorted by account_id first, so rows of one date are scattered across it. A separate index on created_at or another column order is needed if such a filter is common. EXPLAIN gives the real answer.

users.email has a plain index, but WHERE lower(email) = 'ana@test.com' does a Seq Scan. Why, and what to do?

Answer

The index is built on the value of email while the query compares lower(email): a different expression, so the index does not match. The fix: an expression index CREATE INDEX ON users (lower(email)) or a query that does not wrap the column in a function.

In an interview. Junior: An index is a separate structure, like a book's index: it lets you find rows without scanning the whole table. It speeds up search, JOIN and sorting, but takes space and slows down writes. Middle/Senior: The first hypothesis for a slow filter on large data: there is no index or it is not used. I remember that PostgreSQL does not index foreign keys itself, that the column order of a composite index matters and that a function over a column breaks the match. I confirm the hypothesis with the query plan, not a guess.

What is EXPLAIN and how do you use it?

EXPLAIN shows a query's execution plan: how the database intends to read the tables. EXPLAIN ANALYZE also runs the query and adds actual time and row counts. A plan is read for the node type, discarded rows and the gap between estimate and actual, and cost is not milliseconds. For UPDATE and DELETE, ANALYZE really changes data, so it is run in a transaction with ROLLBACK.

SQL · Constraints and indexes

A bug "the page is slow" with no numbers gets bounced. What exactly to bring the developer?

A ticket "transaction history opens slowly" is returned with "what exactly is slow?". The execution plan answers: which node spends the time, how many rows the database read and discarded, whether an index was used. EXPLAIN shows the plan the database intends to run, and EXPLAIN ANALYZE runs the query and adds actual figures. The lesson is about reading this output and not harming the data.

How it works and why. A query says what is needed, and the plan is how: the order and method of reading tables. The planner estimates the cost of options from statistics (how many rows in the table, how values are distributed) and picks the cheapest. So the plan depends on the data: on a dev with a hundred rows it differs from a staging with a million. That is also why analysis must run on data close to production. Plan nodes are read from the inside out and bottom up, and cost is in arbitrary units, not milliseconds: it is compared only with itself.

The key nodes:

  • Seq Scan: reads the whole table. Suspicious on a big table with a selective filter, normal on a small one.
  • Index Scan, Index Only Scan, Bitmap Heap Scan: a search through an index, different ways of fetching rows after it.
  • Nested Loop, Hash Join, Merge Join: ways to join tables.
  • Sort: sorting an index could have removed.

Example: from "slow" to the cause. A table of a million rows, the history query of one account:

EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM transactions
WHERE account_id = 10 AND created_at >= '2026-09-01';

An illustrative output without an index (shortened, numbers made up for the example). It is built so the figures agree: a million rows minus 48 found is 999,952 discarded.

Seq Scan on transactions  (cost=0.00..21450.00 rows=52 width=48)
  (actual time=0.02..95.40 rows=48 loops=1)
  Filter: (account_id = 10 AND created_at >= '2026-09-01')
  Rows Removed by Filter: 999952
Planning Time: 0.15 ms
Execution Time: 95.50 ms
  1. Seq Scan: the whole table was read for 48 rows.
  2. 999,952 rows were read and discarded: this is where the time goes.
  3. The actual time is 95 ms. It is the sum of all nodes, and in production under many queries it multiplies.

After creating the index (account_id, created_at) the same query (also an illustrative output):

Index Scan using idx_transactions_account_created
  on transactions  (cost=0.42..12.10 rows=52 width=48)
  (actual time=0.03..0.21 rows=48 loops=1)
  Index Cond: (account_id = 10 AND created_at >= '2026-09-01')
Planning Time: 0.20 ms
Execution Time: 0.30 ms

The node changed to Index Scan, the condition moved to Index Cond, no rows were discarded, the time is 0.3 ms. For a bug report this is ideal evidence: "the plan shows a Seq Scan discarding 999,952 rows, an index on (account_id, created_at) is needed". The estimate (rows=52) and the actual (rows=48) are close, a good sign. If the estimate were 1 and the actual 48,000, the statistics are stale or the data is unevenly distributed: ANALYZE table, which refreshes them, helps.

EXPLAIN and EXPLAIN ANALYZE

EXPLAIN

Plan only

The query does not run and no data changes. You see estimates, not facts.

EXPLAIN ANALYZE

Plan and facts

The query really runs: actual time and rows appear, but UPDATE and DELETE will change data.

Figure 1. Both modes are legitimate: the choice depends on what you need to know.

A safe way for queries that change data:

BEGIN;
EXPLAIN ANALYZE
DELETE FROM transactions WHERE status = 'failed';
ROLLBACK;  -- the data is back

Limits and alternatives. A rollback undoes row changes but not everything: used sequence values are not returned, triggers fired, and the query may have taken locks and load. On a shared staging and on production, do not run EXPLAIN ANALYZE on modifying queries. BUFFERS adds the number of pages read: useful when the time is unstable because of the cache. For a slow page a single plan is not enough: you must find which SQL the application actually sends (query logs, pg_stat_statements) and only then analyse it. The plan points to the cause, but the fix (an index, a rewritten query, a limit) is chosen by the developer.

Common mistakes.

  • Running EXPLAIN ANALYZE for UPDATE or DELETE without a transaction and ROLLBACK: the data is really changed.
  • Analysing a plan on a small database and drawing conclusions about production.
  • Reading cost as milliseconds.
  • Seeing a Seq Scan and demanding an index at once: on a small table or with a wide filter it is the right choice.
  • Analysing not the query the application sends (other parameters, another plan).

Check yourself

In a plan a node has rows=1 as the estimate while the actual is rows=48000. What does it mean and what to try?

Answer

The planner estimated badly: the statistics are stale or the values are unevenly distributed. Because of it, it may have chosen a poor node. First run ANALYZE on the table and look at the plan again; if the gap stays, it is a reason for the developer to consider extended statistics or another query.

A colleague runs EXPLAIN ANALYZE DELETE FROM transactions WHERE status = 'failed' on a shared staging "just to look". What is wrong and how to make it safer?

Answer

ANALYZE really executes the DELETE, so the rows will be deleted. Safer: plain EXPLAIN without ANALYZE (it only builds the plan), or BEGIN, EXPLAIN ANALYZE, ROLLBACK. Even then on a shared staging the query creates load, so a copy is better.

In an interview. Junior: EXPLAIN shows the execution plan of a query and EXPLAIN ANALYZE also runs it and shows actual time. I look at whether an index is used or the table is scanned fully. I remember that ANALYZE on UPDATE and DELETE really changes data. Middle/Senior: In a bug report about a slow page I attach the plan on data close to production: the node, the number of discarded rows, the gap between estimate and actual. I do not read cost as time, I analyse modifying queries in a transaction with a rollback and draw no conclusions from a small database.

What are normalisation and denormalisation?

Normalisation splits data across tables so each fact is stored once, removing update anomalies. Denormalisation is deliberate duplication for read speed, for example a stored balance. Every copy can drift from its source, so QA finds out whether it is an intentional snapshot required by the specification (a price in an order) or a cache of a derived value, which needs a consistency check.

SQL · Constraints and indexes

A user changed their email and old payments still show the old one. A bug or by design?

In the payment history the same customer appears with two different emails: the new one in newer rows, the old one in older rows. One developer says "it is stored that way, a snapshot at payment time". Another says it was simply forgotten. The answer depends on how the schema is designed and whether the copy is deliberate. This lesson is about normalisation, denormalisation and what follows for tests.

How it works and why. Normalisation splits data across tables so that each fact is stored once. The aim is to remove update anomalies. If the email sits in every transaction, changing it means dozens of rows and some can be missed. The normal forms in plain words: 1NF, one value per cell (not a list "+380…, +380…" separated by commas); 2NF, every non-key column depends on the whole key, not part of it; 3NF, non-key columns do not depend on one another (the email belongs to the user, not to the transaction). The result: a transaction stores user_id, the email lives in users, and a change happens in one place.

Denormalisation is deliberate duplication for read speed: a separately stored balance instead of summing all transactions, a comment counter, a copy of a product name in an order. The price: copies can drift from the source, so they must be maintained (code, a trigger, a background job) and checked.

Example 1: an update anomaly. A non-normalised table and detecting the drift with a query:

-- before: the email repeats in every row
-- transactions_flat: (id, user_id, user_email, amount)
--   (1, 10, 'ana@old.com', 100)
--   (2, 10, 'ana@old.com',  50)
--   (3, 11, 'bo@test.com',  70)

-- the user changed email, only one row was updated
UPDATE transactions_flat
SET user_email = 'ana@new.com' WHERE id = 1;

SELECT user_id, COUNT(DISTINCT user_email) AS emails
FROM transactions_flat
GROUP BY user_id
HAVING COUNT(DISTINCT user_email) > 1;
-- result: user_id 10, emails 2

The query groups by user and counts distinct emails. For user 10 there are two: a drift. Such a check (the number of distinct values of a "dependent" field per owner) finds under-normalised data. Note: if by requirement the email in a payment is a snapshot, the drift is not a bug. First find out whether the copy is deliberate.

An update anomaly in the transactions_flat table

after updating one row
iduser_iduser_email
110ana@new.com
210ana@old.com missed
311bo@test.com
the drift query
user_idemails
102
Figure 1. User 10 has two different emails in the table: row 1 was updated and row 2 was missed. The query above finds exactly this kind of drift.

Example 2: a denormalised balance. The balance is stored in the account and the source of truth is the sum of transactions. A consistency check:

-- accounts: (1, balance 150), (2, balance 80), (3, balance 0)
-- transactions: account 1: 100 and 50; account 2: 100 and -30; account 3: none
SELECT a.id, a.balance, COALESCE(SUM(t.amount), 0) AS calc
FROM accounts a
LEFT JOIN transactions t ON t.account_id = a.id
GROUP BY a.id, a.balance
HAVING a.balance <> COALESCE(SUM(t.amount), 0);
-- result: id 2, balance 80, calc 70

Verification against the data above: account 1 has 100 + 50 = 150 and matches; account 3 with no transactions has calc 0 thanks to COALESCE and matches too; account 2 has 100 + (-30) = 70 while the field holds 80: a mismatch, a synchronisation bug. Without LEFT JOIN an account with no transactions would drop out of the check, and without COALESCE its sum would be NULL.

A copy in the database: a snapshot or a forgotten duplicate

A deliberate snapshot

order_items.unit_price

The price at purchase time must not follow the catalogue. You check that it does not change.

A cache of a derived value

accounts.balance

Must always equal the sum of transactions. You check with a consistency query after every change.

Figure 2. Both copies are legitimate, but they are checked in opposite ways.

Limits and alternatives. Normalisation is not a goal in itself: more tables mean more JOINs and slower reads, and for reports and analytics wide denormalised tables or materialised views are convenient. Read-heavy systems often denormalise on purpose. Higher normal forms (BCNF, 4NF) are rare in practice. For a tester another thing matters more: knowing where the schema holds copies and having a consistency check for each.

Common mistakes.

  • Treating any copy as a bug without asking whether it is a snapshot by requirement.
  • Checking only one place after a change: users was updated, but was the copy?
  • Forgetting a path without UI (an import, a background job) that changes the source data and misses the copy.
  • Checking consistency only on new data: old data may hold the drift.
  • Writing a check without LEFT JOIN and COALESCE: empty cases (an account with no transactions) drop out.

Check yourself

The order_items table has a unit_price column copying the price from products. A developer changed the price in products and old orders did not change. Is it a defect?

Answer

No, it is a deliberate snapshot: the price at purchase time must stay as it was, otherwise order history would drift. A defect would be old orders changing. The test checks precisely that the snapshot is unchanged.

The phones column stores "+380501112233, +380671112233". Which normal form is violated and what is the practical problem?

Answer

1NF is violated: the cell holds several values. Problems: searching by one number needs LIKE, uniqueness or a foreign key cannot be set reliably, changing one number means rewriting the string. A separate phones table with one number per row is better.

In an interview. Junior: Normalisation is designing tables so each fact is stored in one place, without duplication. Denormalisation is deliberate duplication for speed, for example a separately stored balance. For QA every such copy is a desync risk. Middle/Senior: First I find out whether the copy is a snapshot by requirement (a price in an order) or a cache of a derived value (a balance). For a cache I write a consistency query with LEFT JOIN and COALESCE and run it after every change and on old data. For a snapshot I check that it does not change with the source.

How do you test database migrations?

A migration is tested by comparing the state before and after on data close to production. On an empty database NOT NULL, UNIQUE and foreign keys prove nothing. The comparison covers counts by group, values (including NULLs of source columns), how new columns are filled for old rows, rollback, re-run, duration and locking. A migration already applied to production is fixed by a new one, not edited.

SQL · Constraints and indexes

The migration passed on an empty dev database and failed on staging. What should have been checked?

A developer adds a column status NOT NULL. On the empty local database the migration passes and CI is green. On a staging with real data it fails, and had it passed it could have silently damaged the data. A migration changes a schema or data that already exists, so it is tested differently from a new feature: you compare the state before and after. The lesson is about what exactly to compare and where migrations break.

How it works and why. A migration is a versioned script (Flyway, Liquibase, Prisma Migrate, Alembic, Django or Rails migrations) that runs once on every environment and is recorded in a service table. Two consequences follow. First: on the same script, environments differ by data, so the result on an empty database proves nothing. Second: a migration already applied in production is not edited but corrected by a new one. PostgreSQL runs most DDL in a transaction, so a failed migration usually rolls back whole, but a rollback does not undo the downtime a long lock has already caused, and work done outside a transaction is not rolled back (for example, a failed CREATE INDEX CONCURRENTLY leaves an invalid index behind).

The order of testing a migration

1. Snapshot beforecounts, group sums, NULLs2. Migrate upon a copy close to production3. Comparethe same queries: what changed, what did not4. The applicationold records open and save5. Roll back and up againstate without loss, a clean rerun
Figure 1. A snapshot before the migration gives something to compare with: without it "it matches" cannot be proved.

Example 1: NOT NULL on existing data.

ALTER TABLE transactions ADD COLUMN status text NOT NULL;
-- ERROR:  column "status" of relation "transactions"
--         contains null values
-- on an empty dev database the migration passes

The safe sequence splits the change into three steps: add nullable, backfill old rows, only then set the constraint.

-- 1) add nullable, 2) backfill, 3) make mandatory
ALTER TABLE transactions ADD COLUMN status text;

UPDATE transactions
SET status = CASE WHEN is_failed THEN 'failed' ELSE 'completed' END;

ALTER TABLE transactions ALTER COLUMN status SET NOT NULL;

Example 2: a data migration and NULL. The backfill looks right, but there is a trap. The column is_failed is boolean and in ten rows it is: two true, seven false and one NULL.

-- before: 10 rows; is_failed: true = 2, false = 7, NULL = 1
-- after the migration:
SELECT status, COUNT(*) FROM transactions GROUP BY status ORDER BY status;
-- completed | 8
-- failed    | 2

-- the row with is_failed = NULL became completed: ELSE caught the NULL
SELECT COUNT(*) FROM transactions
WHERE status = 'completed' AND is_failed IS NULL;  -- 1

CASE WHEN NULL does not fire (the condition is unknown), so the row goes to ELSE and gets "completed": 7 + 1 gives 8 completed and 2 failed. The group counts agree on the total (10), but in substance a payment with an unknown outcome became successful. That is why besides counts you check values per group and the NULLs of the source columns.

Where the NULL went after the backfill

before: is_failed
is_failedrows
true2
false7
NULL1 → completed
after: status
statusrows
completed8 7 + 1
failed2
Figure 2. The total agrees (10 rows) but the NULL vanished among completed: 7 false + 1 NULL = 8. Only a query on the source field will show it.

What to check, in short:

  • Counts: rows, and per group, before and after; any difference must be explained.
  • Values: sums and selected rows, especially with NULL, empty, the largest values.
  • New columns: what the old rows hold: NULL, DEFAULT or a computed value.
  • Constraints and indexes: new NOT NULL, UNIQUE, foreign keys did not fail on old data.
  • Application: old records open, edit and save.
  • Rollback: the down migration restores the state without loss; dropping a column loses its data for good.
  • Time and locks: duration on a volume close to production.

Limits and alternatives. Duration and locking depend on the operation. In PostgreSQL 11+ adding a column with a constant DEFAULT is fast and does not rewrite the table, while a volatile default (a random value, for instance) does rewrite it. ALTER COLUMN SET NOT NULL scans the table under a strong lock; on a large table the safer route is CHECK (status IS NOT NULL) NOT VALID, then VALIDATE CONSTRAINT under a weaker lock, after which SET NOT NULL skips the full scan. Indexes on a live table are built with CONCURRENTLY. Large data migrations use batched updates to avoid one long transaction. All this can be tested only on a copy with real volume; for personal data it is anonymised. Checking that the old version of the application works with the new schema is needed during deployment too, when old and new code versions share one database for a while.

Common mistakes.

  • Testing only on an empty database: NOT NULL, UNIQUE and foreign keys show up only on data.
  • Comparing only the total row count: values may change while the count is kept.
  • Not recording the "before" state: later there is nothing to compare with.
  • Checking "up" and not "down" and the rerun.
  • Treating rollback as safe: a down migration that drops a column loses data.

Check yourself

A migration fills status with CASE WHEN is_failed THEN 'failed' ELSE 'completed' END. In 1 of 10 rows is_failed = NULL. What happens and how to find it?

Answer

NULL gives UNKNOWN, the WHEN condition does not fire and the row gets "completed". It is found by a query for rows where status = 'completed' and the source field IS NULL; total counts will not show it. It is a question for requirements: what to do with an unknown outcome, usually not "completed".

Why does the migration "ADD COLUMN … NOT NULL" without DEFAULT pass on an empty database and fail on staging?

Answer

An empty table has no rows that would lack the new value. On staging the existing rows would get NULL, violating NOT NULL, so the database refuses. So migrations are tested on data close to production and the change is split into "add nullable, backfill, set NOT NULL".

In an interview. Junior: For migrations I compare the state before and after: row counts and group checksums must match. I check how new columns were filled for old records and whether the application works with old data. Middle/Senior: I test on a copy with the volume and shape of production data, because NOT NULL, UNIQUE and NULL traps show only there. I look not only at counts but at values per group and the NULLs of source columns, check the rollback and a rerun, and measure the duration and table locks.

How does a view differ from a materialized view and how do you test stale data?

A view is a stored query: it keeps no data and returns the current state on every read. A PostgreSQL materialized view stores the query result and reads fast, but goes stale until REFRESH runs. QA compares it with its source query through EXCEPT and checks the refresh schedule and the acceptable delay. MySQL has no built-in materialized views.

SQL · Database structure

A test added an order of 100 and the report still shows the old total. A bug or by design?

The report "orders total per customer" reads not a table but a materialized view. A test added an order and checked the report at once: the total did not change. Compared with the table the report "lies", but the database broke nothing: a materialized view stores the query result and is refreshed only on command. This lesson is about how it differs from a plain view and how to check whether the data is stale.

How it works and why. A plain VIEW is a stored query: it keeps no data and runs its SELECT over the base tables at every read, so it always shows the current state, but costs the same each time. A MATERIALIZED VIEW in PostgreSQL runs the query once and stores the rows physically, like a table. Reads are fast and indexes can be built on it, but the data stays a "snapshot" until the next REFRESH MATERIALIZED VIEW. It is not refreshed after an INSERT into a base table or by time: a person, a job scheduler (for example pg_cron) or the application starts the refresh. This trades freshness for speed: expensive report aggregates are computed once a night or an hour, not on every page open.

Example: the view is fresh, the materialized view is stale.

CREATE TABLE ord (id serial PRIMARY KEY, customer_id int, amount int);
INSERT INTO ord (customer_id, amount) VALUES (1, 10), (1, 20), (2, 5);

CREATE VIEW v_tot AS
  SELECT customer_id, sum(amount) AS total FROM ord GROUP BY customer_id;
CREATE MATERIALIZED VIEW mv_tot AS
  SELECT customer_id, sum(amount) AS total FROM ord GROUP BY customer_id;

INSERT INTO ord (customer_id, amount) VALUES (2, 100);

SELECT * FROM v_tot  ORDER BY 1;  -- (1, 30), (2, 105)
SELECT * FROM mv_tot ORDER BY 1;  -- (1, 30), (2, 5)

After the insert the view returns 105 for customer 2, while the materialized view still returns 5. After REFRESH MATERIALIZED VIEW mv_tot both return (1, 30) and (2, 105).

After the insert: view and materialized view

v_tot (VIEW)
customer_idtotal
130
2105
mv_tot (MATERIALIZED VIEW)
customer_idtotal
130
25 stale
Figure 1. A read right after the INSERT of 100 for customer 2: the view reruns its query and gives 105, the materialized view returns the stored snapshot with 5 until REFRESH.

How QA checks for stale data.

  • Compare the materialized view with the query it is built on, in both directions: an EXCEPT without rows means the data is fresh. In the example above the result is (2, 105) and (2, 5), so there is a difference.
  • After changing data the test starts a refresh (or waits for the scheduled one) and only then checks the report. A separate test checks that the refresh job really runs on schedule and that the acceptable freshness delay is known and written down.
  • A query to pg_matviews shows whether the view is populated (ispopulated). After REFRESH ... WITH NO DATA a read fails with materialized view "mv_tot" has not been populated.

Limits and alternatives. A plain REFRESH blocks reads while it runs, so under load REFRESH MATERIALIZED VIEW CONCURRENTLY is used. It needs at least one UNIQUE index on column names only, without expressions or a WHERE, and a populated view; without such an index PostgreSQL fails with cannot refresh materialized view "mv_tot" concurrently and a hint to create a unique index with no WHERE clause. Only one refresh of a given view runs at a time. MySQL has no built-in materialized views: they are imitated with a table filled by a scheduled job, while a plain view works there as in PostgreSQL. When an always-fresh number is needed, a plain view or an indexed query is used.

Common mistakes.

  • Calling a mismatch between the report and the table a code bug without checking that the report reads a materialized view: what is needed is a refresh.
  • Testing only "after the refresh": nobody learns how long the data stays stale or whether the schedule works.
  • Running CONCURRENTLY without a unique index or on an unpopulated view and getting an error on an environment where everything passed in development.
  • Assuming a MySQL view also "caches" the result: it always runs the query anew.

Check yourself

After an INSERT into the table a SELECT from the view shows the new row, but from the materialized view it does not. Is it a bug?

Answer

No, that is how a materialized view works: it stores a snapshot and changes only after REFRESH. It would be a bug if the data did not appear even after the refresh.

REFRESH MATERIALIZED VIEW CONCURRENTLY returns an error. What do you check first?

Answer

Whether the view has a unique index without expressions or a WHERE, and whether it is populated (ispopulated in pg_matviews). Without them CONCURRENTLY does not work.

In an interview. Junior: A view is a stored query that reads current data each time. A materialized view stores the result and is faster, but goes stale until it is refreshed. Middle/Senior: I check freshness by comparing the view with its query through EXCEPT, I check the refresh schedule and the acceptable delay, and I know about CONCURRENTLY and the unique index. MySQL has no built-in materialized views.

How do you change a schema without downtime: expand/contract, CONCURRENTLY and NOT NULL?

A schema is changed without downtime in small compatible steps. An ALTER takes a strong lock and queues others behind it, so the migration sets lock_timeout. An index is built with CREATE INDEX CONCURRENTLY outside a transaction and invalid ones are checked. NOT NULL is introduced through CHECK ... NOT VALID, VALIDATE and SET NOT NULL, and a rename is done as expand/contract over several releases.

SQL · Database structure

A migration "only adds a column" and the service does not answer for a minute. What happened?

A migration adds one column to the orders table and in CI it runs in an instant. On the live environment it stands in a queue, and ordinary SELECTs and INSERTs to that table queue behind it: the application is silent until the migration ends. The command itself is fast, the lock is to blame. This lesson is about how to change a schema so that users do not notice: the order of steps, long operations and NOT NULL constraints.

How it works and why. In PostgreSQL most forms of ALTER TABLE take an ACCESS EXCLUSIVE lock unless the documentation says otherwise. It conflicts with any other access to the table, even a read. If some transaction already holds the table (a long report, a forgotten open session), the ALTER waits and new queries line up behind it, although they do not conflict with that transaction themselves. So the downtime comes not from the migration runtime but from the lock wait. Reproduced with three sessions (figure 1).

The queue behind ALTER

Session A: open transactionholds the table after a SELECTB waits for ASession B: ALTER TABLEasks for ACCESS EXCLUSIVE and waitsC waits for BSession C: a plain SELECTno conflict with A, yet queued behind ALTERdowntime = the lock wait
Figure 1. One long reader stops the migration and everyone who arrived after it.

A query to pg_stat_activity with pg_blocking_pids(pid) showed two rows: the ALTER and the ordinary SELECT, both waiting on a Lock event. After a ROLLBACK in session A the ALTER ran first, then the SELECT. The defence: limit the wait in the migration session and retry later.

SET lock_timeout = '3s';
ALTER TABLE orders ADD COLUMN note text;
-- ERROR: canceling statement due to lock timeout

The documentation advises against setting lock_timeout in postgresql.conf because it would affect all sessions: it is set in the migration session. A failed attempt changed nothing and is safe to run again.

An index without blocking writes. A plain CREATE INDEX blocks writes to the table for the whole build. CREATE INDEX CONCURRENTLY builds the index without locks that prevent INSERT, UPDATE and DELETE, but it makes two passes over the table and waits for transactions that could have modified it, so it takes longer. It cannot run inside a transaction: PostgreSQL answers CREATE INDEX CONCURRENTLY cannot run inside a transaction block, and many migration tools wrap every migration in a transaction by default, so the wrapper is switched off for this step. After a failure (for example a uniqueness violation) an invalid index is left behind: queries ignore it, while table updates still maintain it. In a test with a duplicate email pg_index.indisvalid showed false for such an index. It is dropped and built again, or rebuilt with REINDEX INDEX CONCURRENTLY.

-- outside a transaction block
CREATE INDEX CONCURRENTLY idx_orders_user
  ON orders (user_id);

-- after a failure: find leftovers
SELECT indexrelid::regclass
FROM pg_index
WHERE NOT indisvalid;

NOT NULL on a large table. SET NOT NULL checks the whole table under a strong lock. The documentation describes a way around it: if a valid CHECK constraint exists that proves no NULL can exist, the full scan is skipped. The constraint is added as NOT VALID (new rows are already checked, old ones are not), then VALIDATE CONSTRAINT takes only SHARE UPDATE EXCLUSIVE and does not stop writes. Skipping the scan appeared in PostgreSQL 12. Since PostgreSQL 18 a NOT NULL constraint itself can be added as NOT VALID and then validated with VALIDATE CONSTRAINT, without the intermediate CHECK.

ALTER TABLE orders
  ADD CONSTRAINT status_nn
  CHECK (status IS NOT NULL) NOT VALID;
-- backfill old rows first, then:
ALTER TABLE orders VALIDATE CONSTRAINT status_nn;
ALTER TABLE orders ALTER COLUMN status SET NOT NULL;
ALTER TABLE orders DROP CONSTRAINT status_nn;

In a test the NOT VALID constraint rejected a new row with NULL at once, while VALIDATE failed as long as old NULLs remained: the error check constraint ... is violated by some row. So old rows are backfilled first, in batches.

Expand/contract for a rename. A direct RENAME COLUMN is instant, but the old application version fails at once: in a test SELECT email after the rename gave column "email" does not exist. During a deployment old and new code run together, so the change is split into compatible steps, each in its own release:

  1. Expand: add the new column, nullable, with no default. The old version does not notice it.
  2. The new version writes to both columns, and old rows are copied in batches (UPDATE ... WHERE id BETWEEN ...) so no long transaction is held.
  3. The new version reads from the new column. The old column is kept: it is the way back.
  4. Contract: when no old version runs any more, the old column is dropped in a following release.

Limits and alternatives. Adding a column with a constant DEFAULT is fast and does not rewrite the table, while a volatile one (for example gen_random_uuid()) rewrites all of it. MySQL (InnoDB) describes similar operations as online DDL: creating a secondary index permits concurrent changes and does not rebuild the table, renaming a column without changing its type runs with ALGORITHM=INSTANT, and switching to NOT NULL rebuilds the table in place and fails if the column holds NULLs. If the requested ALGORITHM or LOCK is impossible, MySQL returns an error instead of silently taking a stronger lock or a slower algorithm. Expand/contract is slower than one ALTER, but it can be stopped at any step.

Common mistakes.

  • Measuring a migration by its runtime on an empty database: downtime comes from the lock wait when long transactions exist.
  • Running CONCURRENTLY inside the migration tool transaction and getting an error only at this step.
  • Not checking for invalid indexes after a failure: they stay and slow down writes.
  • Renaming and dropping a column in one release: the old application version fails before the deployment ends.

Check yourself

An ADD COLUMN migration runs in milliseconds in CI, but on the live environment even reads stand still. What do you check first?

Answer

Whether a long open transaction holds this table: the ALTER waits for it and other queries line up behind it. Look at pg_stat_activity and pg_blocking_pids, set lock_timeout in the migration and retry.

Why does a developer add CHECK ... NOT VALID instead of SET NOT NULL straight away, and what must happen before VALIDATE?

Answer

SET NOT NULL scans the whole table under a strong lock, while VALIDATE takes a weaker one and does not stop writes. Old rows with NULL must be backfilled before VALIDATE, or it fails.

In an interview. Junior: A schema change locks the table. To avoid downtime it is done in steps: first add, then move the data, then remove the old. Middle/Senior: Downtime comes from the queue behind the ALTER, so I set lock_timeout and look for long transactions. I build indexes with CONCURRENTLY outside a transaction and check for invalid ones, I introduce NOT NULL through CHECK NOT VALID and VALIDATE, and I do a rename as expand/contract over several releases.