QA AND TEST AUTOMATION · PART 4 · API TESTING · TECHNIQUE · 47 OF 112

Database Testing with SQL: Verify What the API Saved

Using SQL to check what an API really did: when to look in the database, read-only access, ShopRung's tables and SQL console, a real pytest check that placing an order reduces stock (it catches the stock-not-reduced bug that the API response hides), JDBC in Java, SQL queries testers use, data integrity checks and the risks of coupling tests to the schema.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 67
  63. 68
  64. 69
  65. 70
  66. 71
  67. 72
  68. 73
  69. 74
  70. 75
  71. 76
  72. 77
  73. 78
  74. 79
  75. 80
  76. 81
  77. 82
  78. 83
  79. 84
  80. 85
  81. 86
  82. 87
  83. 88
  84. 89
  85. 90
  86. 91
  87. 92
  88. 93
  89. 94
  90. 95
  91. 96
  92. 97
  93. 98
  94. 99
  95. 100
  96. 101
  97. 102
  98. 103
  99. 104
  100. 105
  101. 106
  102. 107
  103. 108
  104. 109
  105. 110
  106. 111
  107. 112
1 / 12

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Check side effects the API hides
  • read-only access
  • parameterised SQL
  • integrity queries
  • mind the coupling

Notes

Why look?

When is a database check worth it? For side effects the response does not show: was the stock reduced, was the cart emptied, was an audit row written? For data the API never returns, like checking a password is stored as a hash, not plain text. For checking integrity after migrations or batch jobs. A simple rule: if the API can show you the same thing, prefer the API; use the database for what it cannot.

When a DB check helps
  • side effects the response does not show: stock reduced? cart emptied? audit row written?
  • data the API never returns (password stored as a hash?)
  • setting up rare data quickly
  • checking data integrity after migrations or batch jobs
  • prefer the API when it can show the same thing

ShopRung's tables

ShopRung stores everything in a SQLite database with seven tables. Users, with a password hash and a role. Products, with price in cents and stock. Coupons, with their kind, amount, minimum subtotal and expiry date. Carts and cart items for each user. And orders, with status and every amount in cents, plus order items. Notice the column names use underscores, like total underscore cents, while the API uses total cents. The database and the API are different layers.

Schema (main columns)
users(id, email, name,
  password_hash, role)
products(id, sku, name,
  category, price_cents, stock)
coupons(code, kind, amount,
  min_subtotal_cents, expires_on)
carts(user_id, coupon_code)
cart_items(user_id, product_id,
  quantity)
orders(id, user_id, status, ...,
  total_cents)  + order_items

Read-only access

Tests should look at the database, not change it behind the application's back. Use a read only user or connection. ShopRung's SQL console, on the slash sql page or the test SQL endpoint, runs one select query on a read only connection. Ask for the stock of product three: three. Try delete from orders: four hundred, the console runs one select query at a time. Real teams give testers the same kind of read only access.

ShopRung SQL console
POST /api/test/sql
{"query": "SELECT stock FROM
  products WHERE id = 3"}
→ {"rows": [{"stock": 3}]}

"DELETE FROM orders"
→ 400 select_only
  "The console runs one
   SELECT query at a time"
also in the browser: /sql

A real check

Here is a real test. The db fixture opens ShopRung's database file in read only mode. The test reads the stock of the Bug Hunter's Diary, product three, which starts at three. It adds two to Alice's cart and places the order: two hundred and one. Then it checks the stock is now the old value minus two. Against the normal ShopRung, it passed. The same test then checks the new order row has status placed and the same total as the response.

test_db.py
def test_order_reduces_stock(alice, db):
    before = stock(db, 3)
    alice.post("/api/cart/items",
      json={"productId": 3, "quantity": 2})
    r = alice.post("/api/orders", json={})
    assert r.status_code == 201
    assert stock(db, 3) == before - 2

db = sqlite3.connect(
  f"file:{DB}?mode=ro", uri=True)

The hidden bug

Then we switched on the stock not reduced bug. The order response was identical: two hundred and one, placed, forty two ninety seven. A test that only checks the response passes. But the database check failed: assert three equals three minus two. The stock never went down, so the shop would keep selling books it does not have. That is the kind of bug database checks exist for.

Same response, wrong data
POST /api/orders → 201
  {"status": "PLACED",
   "totalCents": 4297, ...}
  (identical with the bug on)

pytest -q test_db.py
  assert 3 == (3 - 2)
  1 failed

stock stayed 3 → overselling

In Java

In Java, JDBC does the same job. Open a connection with read only properties, inside try with resources so it always closes. Use a prepared statement with a question mark placeholder, set the id, execute the query, and read the integer. Always use placeholders, never string concatenation, even in tests: it avoids quoting bugs, and it is the habit that prevents SQL injection in real code.

JDBC helper
int stock(long id) throws Exception {
  try (var con = DriverManager
         .getConnection(DB_URL, ro);
       var ps = con.prepareStatement(
    "SELECT stock FROM products" +
    " WHERE id = ?")) {
    ps.setLong(1, id);
    var rs = ps.executeQuery();
    rs.next(); return rs.getInt(1);
  }
}

Queries testers use

A few query patterns cover most needs. Joins combine tables, like orders with their items. Group by with having finds broken totals: every order whose items do not add up to its subtotal. Simple where clauses find impossible data, like negative stock. Expected result: zero rows. These integrity checks are especially valuable after migrations and batch jobs, and many teams run them on a schedule.

Useful SQL
-- each order's items add up?
SELECT o.id FROM orders o
 JOIN order_items i
   ON i.order_id = o.id
 GROUP BY o.id, o.subtotal_cents
 HAVING SUM(i.price_cents *
   i.quantity) <> o.subtotal_cents;
-- no negative stock
SELECT * FROM products
 WHERE stock < 0;

Trade-offs

Database checks have costs. They couple tests to the schema, so renaming a column breaks tests even when the behaviour is fine. Pointed at the wrong environment, they can read real customer data. Background jobs may not have written yet, so poll with a timeout instead of checking once. And caches mean the database and the API can disagree for a while. Keep SQL in a few helper functions, read only, and on test data only.

Use with care
  • schema changes break tests even when behaviour is fine
  • wrong environment = real data
  • timing: async jobs may not have written yet (poll)
  • caches: DB updated, API still shows old data, or reverse
  • keep SQL in a few helpers, read-only, test data only

Common mistakes

Mistakes to avoid. Writing to the database in the middle of a test to fix data, which hides real bugs. Building SQL by string concatenation. Connections that are never closed, which slowly exhausts the pool. The same SQL copied into every test. Checking the database for everything, even what the API shows. And production credentials anywhere in test configuration.

Avoid these
  • writing to the DB to "fix" test data mid-test
  • SQL by string concatenation
  • connections never closed
  • SQL copied into every test
  • checking the DB instead of the API for everything
  • production credentials in test config

Say it like this

In the interview: yes, when the response cannot show the side effect, such as stock, audit rows or hashed passwords. I use a read only connection, parameterised queries kept in a few helpers, and polling for asynchronous writes. For example, my order test checks that stock went down, which caught a bug the response alone completely missed. I also write SQL integrity checks for joins and totals.

In the interview
  • "When the response cannot show
  • the side effect: stock, audit
  • rows, hashed passwords. I use
  • a read-only connection, parameterised queries in a few
  • helpers, and poll for async
  • writes. For example, an order
  • test checks stock went down;
  • the response alone missed that bug."

Interview questions

Q1Why check the database in API tests?

To verify side effects and stored data the response does not show, such as stock updates, cleared carts, audit rows or hashed passwords.

Q2Should automated tests write to the database directly?

Generally only for setting up test data in a controlled way; checks should use read-only access and never patch data mid-test.

Q3Why use prepared statements in test code?

Placeholders avoid quoting errors and SQL injection, and keep queries readable and reusable.

Q4What is a data integrity check?

A query that should return zero rows if data is consistent, for example orders whose items do not sum to the subtotal or products with negative stock.

Q5What SQL should a tester know?

SELECT with WHERE, ORDER BY, JOINs, GROUP BY with HAVING, aggregate functions, subqueries, and basic INSERT/UPDATE/DELETE for test data setup.

Q6What are the risks of database assertions?

Coupling to the schema, environment mistakes exposing real data, timing with asynchronous writes, and caches that make the DB and API disagree temporarily.

Q7How do you check an asynchronous database write?

Poll the query with a timeout until the expected value appears, instead of checking once or sleeping a fixed time.

Q8Give an example of a bug only a database check would catch.

An order API returns 201 with correct totals but never reduces stock, so the response is identical and only the products table shows the problem.