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

SQL › SQL in QA work

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
fieldvalue
id501
skuA-1
qty2
total99.99
orders, id = 501
fieldvalue
skuA-1
qty2
statusnew
total99.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 = await read();
await request.patch('/api/orders/' + id, { data: { qty: 3 } });
const after = await read();

// Date compares by reference, so compare through JSON
const 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.

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 give database access as read-only.

More articles in this chapter