QA AND TEST AUTOMATION · PART 1 · MANUAL TESTING, PROPERLY · TOOLS · 19 OF 112

SQL for Testers: Queries to Check the Data

The SQL a tester actually uses: SELECT with WHERE, ORDER BY and LIMIT, COUNT and GROUP BY, JOINs across tables, and LEFT JOIN to find what is missing, then data checks that catch bugs the screen hides. Every query runs on the ShopRung database in its read-only SQL console, with the real results, plus the SQL questions SDET interviews ask.

  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 / 14

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

Key takeaways

  • SELECT, WHERE, ORDER BY
  • COUNT and GROUP BY
  • JOIN and LEFT JOIN
  • zero-row checks
  • before and after

Notes

Why SQL

Testers use SQL for four jobs. To verify that an action stored the right data, like stock going down after an order. To set up a test, by finding data that fits it, like a product with low stock. To investigate whether a bug lives in the page, the API or the data. And to attach evidence to a bug report. Almost all of it is reading with SELECT. In ShopRung, the console at slash S Q L only allows reading, so you cannot break anything.

Why testers use SQL
  • verify: an action stored the right data (ORD-2 stock)
  • set up: find test data (a product with low stock)
  • investigate: is the bug in the UI, the API or the data?
  • evidence: a query result in the bug report
  • mostly SELECT, read-only

The tables

First, know the tables. ShopRung has users, products, coupons, carts and cart items, orders and order items. Money is stored in whole cents, so fifty dollars is five thousand. The links are the id columns: an order has a user id that points to a user, and each order item has an order id and a product id. Read the schema before you write queries. In a real job, ask for the diagram or run the database's describe command.

ShopRung tables
users        id, email, name, role
products     id, sku, name, category,
             price_cents, stock
coupons      code, kind, amount,
             min_subtotal_cents
cart_items   user_id, product_id, qty
orders       id, user_id, status,
             subtotal..total_cents
order_items  order_id, product_id,
             name, price_cents, qty

SELECT

The basic query has four parts. SELECT the columns you want, FROM a table, WHERE a condition, ORDER BY a column. Here: the sku, name and stock of every product with fewer than ten in stock, lowest first. ShopRung returns four rows: the red mug with zero, the Bug Hunter's Diary with three, the headphones with five and the keyboard with eight. That is exactly the test data you need for the out of stock and stock limit cases.

Low stock products
SELECT sku, name, stock
FROM products
WHERE stock < 10
ORDER BY stock;

MG-202  Red Build Mug        0
BK-103  The Bug Hunter's ..  3
HD-403  Noise-Cancelling ..  5
KB-401  Quiet Mechanical ..  8

Filters

Filters combine with AND and OR. BETWEEN gives a range, including both ends. IN matches a list, like orders that are placed or paid. LIKE matches a pattern, where the percent sign means any text, so percent mug percent finds both mugs. And to find empty values, write IS NULL, never equals NULL, which matches nothing. Strings go in single quotes. On a real database with millions of rows, add LIMIT so a query returns quickly.

Useful filters
WHERE category = 'Books'
  AND price_cents BETWEEN 1000
                  AND 2000
WHERE status IN ('PLACED','PAID')
WHERE name LIKE '%Mug%'
WHERE coupon_code IS NULL

-- strings in single quotes
-- NULL needs IS, not =
-- LIMIT 10 for big tables

Counting

Aggregate functions summarise rows: COUNT, SUM, MIN, MAX and AVG. With GROUP BY they work per group. Here we count products and find the cheapest price in each category. Electronics and books have three products each, stickers, home and clothing two each, and the cheapest item in the shop is a sticker pack at four ninety nine. Counting is a quick sanity check: the page says three books, and so does the database.

Products per category
SELECT category, COUNT(*) AS n,
       MIN(price_cents) AS cheapest
FROM products
GROUP BY category
ORDER BY n DESC;

Electronics  3  2550
Books        3  1250
Stickers     2   499
Home 2 1500 · Clothing 2 2000

JOIN

Real questions need more than one table. A JOIN combines rows where the ids match. Here we join orders to users on the user id, so each order shows the customer's email. The letters o and u are short names, called aliases. On a fresh ShopRung, both seed orders belong to Alice: order one is delivered with a total of thirty four ninety nine, and order two is shipped with a total of seventy five dollars.

Orders with the customer
SELECT o.id, u.email, o.status,
       o.total_cents
FROM orders o
JOIN users u ON u.id = o.user_id
ORDER BY o.id;

1  alice@shoprung.test
   DELIVERED  3499
2  alice@shoprung.test
   SHIPPED    7500

LEFT JOIN

A plain join only keeps rows that match on both sides. A LEFT JOIN keeps every row from the left table, and fills the right side with NULL where nothing matches. That makes it the tester's favourite for finding what is missing. Which products were never ordered? Left join products to order items, and keep rows where the order id is NULL. Ten products come back, everything except the green mug and the keyboard, which Alice ordered.

Products never ordered
SELECT p.sku
FROM products p
LEFT JOIN order_items i
  ON i.product_id = p.id
WHERE i.order_id IS NULL;

10 rows: every product except
MG-201 and KB-401

INNER JOIN: only matches
LEFT JOIN: all left + matches

Data checks

The most powerful queries are checks that should return zero rows. Orders whose total does not equal subtotal minus discount plus shipping, which is price ten. Emails that appear more than once, which account four forbids; HAVING filters groups after counting. Products with negative stock. On a healthy ShopRung, all three return nothing. Run them after a test session, and any row they return is a bug, with the evidence already attached.

Should return 0 rows
-- totals add up (PRICE-10)
SELECT id FROM orders
WHERE total_cents <>
  subtotal_cents - discount_cents
  + shipping_cents;
-- duplicate emails (ACC-4)
SELECT email, COUNT(*) FROM users
GROUP BY email
HAVING COUNT(*) > 1;
-- negative stock
SELECT sku FROM products WHERE stock<0;

Before and after

The everyday pattern is before and after. Query the stock of the Bug Hunter's Diary: three. Buy one in the shop. Query again: two, as rule order two requires. Now switch on the stock bug and repeat: the order is placed, but the query still says three. You have found the bug and your evidence in one move. This is exactly what you will do in the bug report lab.

Checking ORD-2
SELECT stock FROM products
WHERE sku = 'BK-103';   -- 3

-- in the shop: buy 1 Diary

SELECT stock FROM products
WHERE sku = 'BK-103';   -- 2 ok

bug stock-not-reduced on:
  still 3 → evidence for B-7

Safety

On real systems, some rules. Use a read only account when you can. Never update or delete rows in a shared test database without telling the team, because other people's tests depend on that data. Never touch production data without written permission. Add LIMIT to queries on big tables. Treat personal data with care and look only at what the test needs. And save your useful queries in Git, so the whole team can reuse them.

Rules for real databases
  • use a read-only account
  • never UPDATE or DELETE on a shared test DB without telling the team
  • never touch production data without written permission
  • add LIMIT to big queries
  • personal data: look only at what the test needs
  • save useful queries in Git

Common mistakes

These mistakes give wrong answers without any error. Writing equals NULL instead of IS NULL. Using an inner join when you needed a left join, so rows silently vanish. Forgetting the join condition, so rows multiply. Comparing cents with dollars. Filtering a count with WHERE instead of HAVING. And trusting a query without checking the number of rows makes sense. If the shop has twelve products and your query says forty, something is wrong.

Avoid these
  • = NULL instead of IS NULL
  • JOIN when you needed a LEFT JOIN (rows vanish)
  • forgetting a join condition (rows multiply)
  • comparing cents to dollars
  • WHERE on a COUNT (use HAVING)
  • trusting one query without checking the row count

Say it like this

Interviewers ask how you use SQL, then give a small task. Say: I use SELECT queries to find test data, to verify that actions stored the right values, and to add evidence to bug reports, and I write checks that should return zero rows, like totals that do not add up or duplicate emails. Be ready for classic tasks: inner versus left join, GROUP BY with HAVING, duplicates, and the second highest salary.

In the interview
  • "I use SELECT queries to set
  • up data, verify that actions
  • stored the right values, and add evidence to bug reports.
  • I write checks that should
  • return zero rows, like totals
  • that do not add up or duplicate emails. Common asks: JOIN vs LEFT JOIN, GROUP BY with HAVING, the 2nd highest."

Interview questions

Q1What is the difference between INNER JOIN and LEFT JOIN?

INNER JOIN returns only rows that match in both tables. LEFT JOIN returns every row from the left table, with NULLs where the right table has no match, which helps find missing data.

Q2What is the difference between WHERE and HAVING?

WHERE filters rows before grouping; HAVING filters groups after aggregation, for example HAVING COUNT(*) > 1.

Q3How do you find duplicate emails in a users table?

SELECT email, COUNT(*) FROM users GROUP BY email HAVING COUNT(*) > 1;

Q4How do you find the second highest salary?

SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees); or use ORDER BY salary DESC with LIMIT 1 OFFSET 1 on distinct salaries, or DENSE_RANK().

Q5How do you use SQL when testing an order flow?

Query stock, order and order item rows before and after placing an order, check totals add up, statuses are right, and no duplicate or orphan rows were created.

Q6Why does WHERE column = NULL return nothing?

NULL means unknown, and comparing anything to unknown is not true. Use IS NULL or IS NOT NULL.

Q7What is a zero-row check?

A query that should return no rows when the data is correct, such as orders whose totals do not add up; any row returned is a defect.

Q8What precautions do you take with SQL on shared environments?

Use read-only access where possible, avoid UPDATE and DELETE on shared data, never touch production without permission, limit large queries and protect personal data.