Skip to content
Bugwise
Menu
Tutorials

SQL for Testers 2: Advanced Queries

Go beyond the basics. Join many tables without multiplying rows, use EXISTS and NOT EXISTS safely, write readable queries with WITH and CASE, find the latest row per group with window functions, handle dates and time zones, and reconcile data, then find four bugs in a payments database.

advanced Mobile & web
Short on time? Switch to the quick version.

The FoodDash finance team has a question: “Card payments for October add up to €4,000 more than the orders. Can QA check the database?” You know SELECT, WHERE, GROUP BY and a JOIN or two from SQL for Testers. But this question needs more: orders, payments and refunds together, only the latest status of each order, the right days in the right time zone, and sums that don’t double by accident.

This lesson covers the queries that answer questions like that. Every example uses the FoodDash payments database you’ll practice on at the end: orders, their items, every payment attempt, refunds, couriers, and the full status history of each order.

Part Not started

Joining many tables

Real questions span several tables. Follow the keys: each JOINJOIN (SQL)Combining rows from two tables that belong together, for example each order with its customer.Open in glossary → connects one foreign keyForeign keyA column that points to the primary key of a row in another table, like orders.user_id → users.id.Open in glossary → to the table it points to.

SELECT o.id, u.name AS customer, r.name AS restaurant, c.name AS courier
FROM orders o
JOIN users u       ON u.id = o.user_id
JOIN restaurants r ON r.id = o.restaurant_id
JOIN couriers c    ON c.id = o.courier_id
WHERE o.status = 'delivered';

Short aliases (o, u, r, c) keep it readable, and prefixing every column (o.id, u.name) avoids “ambiguous column” errors when two tables share a column name.

Trap 1: a LEFT JOIN filter in WHERE

You want restaurants without a delivered order. A LEFT JOIN keeps every restaurant and fills NULLs where nothing matches. But a condition on the joined table in WHERE throws those NULL rows away again:

Condition in ON: keeps the empty matches

SELECT r.name, o.id
FROM restaurants r
LEFT JOIN orders o
  ON o.restaurant_id = r.id
 AND o.status = 'delivered'
WHERE o.id IS NULL;

Green Bowl and Le Petit Café, both with NULL.

Condition in WHERE: turns it into an INNER JOIN

SELECT r.name, o.id
FROM restaurants r
LEFT JOIN orders o ON o.restaurant_id = r.id
WHERE o.status = 'delivered'
  AND o.id IS NULL;

No rows: o.status is NULL on exactly the rows you wanted.

Trap 2: joins that multiply rows

A JOIN returns one row for every matching pair. Join an order with 3 items to its payment, and that payment appears 3 times. Sum the payments afterwards, and the sum is three times too high:

RestaurantPaid, correctPaid, after also joining order_items
Sushi Zen Garden151.50255.00
Pizzeria Napoli106.00176.00
Balkan Grill Kod Žike64.50129.00
Burger Brothers61.00159.00

This multiplying is called fan-out. The rule: join only the tables the question needs, and when you need sums from two “many” tables (items and payments), sum each one separately first, then join the totals. If a total looks suspiciously big, count the rows before summing.

This is called fan-out, and it’s one of the most common reasons a report “doesn’t match”. Three ways to avoid it:

  1. Join only what the question needs. Payments per restaurant need restaurants, orders and payments. Not items.
  2. Aggregate first, then join. Sum the items per order in one query, the payments per order in another, and join the two totals on order_id:
WITH items AS (
  SELECT order_id, SUM(quantity * unit_price) AS items_total
  FROM order_items GROUP BY order_id
),
paid AS (
  SELECT order_id, SUM(amount) AS paid
  FROM payments WHERE status = 'succeeded' GROUP BY order_id
)
SELECT o.id, items.items_total, paid.paid
FROM orders o
JOIN items ON items.order_id = o.id
LEFT JOIN paid ON paid.order_id = o.id;
  1. Check the row count. Before summing, SELECT COUNT(*) with the same joins. If 14 orders turn into 31 rows, something multiplied.

Check this part

  1. You LEFT JOIN restaurants to orders and add WHERE o.status = 'delivered'. What happens to restaurants with no delivered order?

  2. A restaurant's paid total doubles after you add order_items to the query. Why?

Join many tables by following keys, put LEFT JOIN conditions in ON, and watch for joins that multiply rows and inflate sums.

Part Not started

Subqueries, EXISTS and NOT EXISTS

A subquerySubqueryA query inside another query, such as a list for IN, a check for EXISTS, or a single value used like a column.Open in glossary → is a query inside another query. Testers use three kinds all the time.

“Is in this list”: IN

-- customers who paid with Apple Pay at least once
SELECT name FROM users
WHERE id IN (
  SELECT o.user_id FROM orders o
  JOIN payments p ON p.order_id = o.id
  WHERE p.method = 'apple_pay'
);

“Has (or has no) matching row”: EXISTS and NOT EXISTS

EXISTS asks “is there at least one row like this?” It’s the clearest way to write the questions testers ask most: delivered but never paid, customers without orders, orders without items.

-- delivered orders without any succeeded payment
SELECT o.id
FROM orders o
WHERE o.status = 'delivered'
  AND NOT EXISTS (
    SELECT 1 FROM payments p
    WHERE p.order_id = o.id AND p.status = 'succeeded'
  );

The SELECT 1 doesn’t matter: EXISTS only checks whether a row is found. The important part is the link to the outer query, p.order_id = o.id.

The NOT IN trap

NOT IN looks like the same thing, but it breaks when the subquery contains a NULLNULLA database marker for "no value" or "unknown". It's not zero and not an empty string.Open in glossary →:

-- couriers who never had an order?
SELECT name FROM couriers
WHERE id NOT IN (SELECT courier_id FROM orders);
-- returns no rows!

The canceled order 2005 has no courier, so the list contains NULL. 5 NOT IN (1, 2, 3, 4, NULL) isn’t true, it’s unknown, so no row qualifies. The same question with NOT EXISTS correctly returns Dragan.

A single value: scalar subqueries

A subquery that returns one value can be used like a column:

SELECT o.id, o.total,
       (SELECT SUM(amount) FROM payments p
        WHERE p.order_id = o.id AND p.status = 'succeeded') AS paid
FROM orders o;

It’s readable for small checks. For many rows, a JOIN with GROUP BY is usually faster.

Check this part

  1. Why does WHERE id NOT IN (SELECT courier_id FROM orders) return no rows?

  2. What does EXISTS (SELECT 1 FROM payments p WHERE p.order_id = o.id) check?

Use IN for lists, EXISTS and NOT EXISTS for 'has a matching row', avoid NOT IN with NULLs, and use a scalar subquery for one value.

Part Not started

Readable queries: WITH and CASE

WITH: name the steps

A common table expressionCommon table expression (CTE)A named step in an SQL query, written with WITH, that makes complex queries readable.Open in glossary → (CTE) gives a subquery a name, so a complex check reads top to bottom like a recipe:

WITH paid AS (
  SELECT order_id, SUM(amount) AS paid
  FROM payments
  WHERE status = 'succeeded'
  GROUP BY order_id
)
SELECT o.id, o.total, COALESCE(paid.paid, 0) AS paid
FROM orders o
LEFT JOIN paid ON paid.order_id = o.id
WHERE o.status = 'delivered'
  AND COALESCE(paid.paid, 0) <> o.total;

Result: order 2004 (total 42, paid 84: charged twice) and order 2006 (total 27, paid 0). One query, two bugs. COALESCE(x, 0) turns a NULL into 0, so orders with no payment at all are compared too.

CASE: categories and flags

CASE works like “if … then … else” inside a query:

SELECT CASE
         WHEN status IN ('preparing', 'on_the_way') THEN 'open'
         WHEN status = 'delivered' THEN 'done'
         ELSE 'canceled'
       END AS stage,
       COUNT(*) AS orders
FROM orders
GROUP BY stage;

CASE also builds conditional sums, which turn rows into columns, a handy shape for comparing:

SELECT order_id,
       SUM(CASE WHEN status = 'succeeded' THEN amount ELSE 0 END) AS paid,
       SUM(CASE WHEN status = 'failed'    THEN 1      ELSE 0 END) AS failed_attempts
FROM payments
GROUP BY order_id;

And flags that name the problem in the result, which reads well in a bug report:

SELECT o.id,
       CASE WHEN o.status = 'delivered' AND p.order_id IS NULL THEN 'delivered, not paid'
            ELSE 'ok' END AS check_result
FROM orders o
LEFT JOIN (SELECT DISTINCT order_id FROM payments WHERE status = 'succeeded') p
  ON p.order_id = o.id;

Check this part

  1. What does WITH (a CTE) do?

  2. Why use COALESCE(paid, 0) when comparing payments with totals?

WITH (common table expressions) splits a query into named steps; CASE turns values into categories, flags and conditional sums.

Part Not started

Window functions: latest per group and row-to-row checks

Some of the most useful tester questions are about the latest row in each group: the latest status of every order, the most recent login of every user, the current price of every product. GROUP BY can’t easily return the whole latest row. Window functionsWindow functionAn SQL function that computes a value for each row while looking at a group of rows, without collapsing them.Open in glossary → can.

ROW_NUMBER: the latest row per group

WITH latest AS (
  SELECT order_id, status, changed_at,
         ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY changed_at DESC) AS rn
  FROM order_status_history
)
SELECT order_id, status, changed_at
FROM latest
WHERE rn = 1;
  • PARTITION BY order_id restarts the numbering for each order.
  • ORDER BY changed_at DESC makes the newest row number 1.
  • Unlike GROUP BY, nothing is collapsed: every row stays, with its number.

That’s exactly what you need to check whether orders.status matches the real history, which is one of the lab exercises.

Two more you’ll meet: LAG(column) gives the value from the previous row in the window (great for “did the status go backwards?” or “how long did each step take?”), and SUM(amount) OVER (ORDER BY created_at) gives a running total.

LAG: compare a row with the previous one

LAG(changed_at) returns the previous row’s value in the same window. For order 2004:

statuschanged_atprevious
placed18:45NULL
preparing18:4818:45
on_the_way19:0718:48
delivered19:2619:07
SELECT order_id, status, changed_at,
       LAG(status)     OVER (PARTITION BY order_id ORDER BY changed_at) AS previous_status,
       LAG(changed_at) OVER (PARTITION BY order_id ORDER BY changed_at) AS previous_at
FROM order_status_history;

From there, a WHERE in an outer query finds impossible transitions (delivered after canceled), steps that took too long, or duplicate events.

Running totals and ranks

-- running total of succeeded payments over time
SELECT created_at, amount,
       SUM(amount) OVER (ORDER BY created_at) AS running_total
FROM payments WHERE status = 'succeeded';

-- each customer's orders numbered: is this their first order?
SELECT id, user_id,
       ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY created_at) AS nth_order
FROM orders;

The second one is how you’d test a “first order discount”: every order with nth_order = 1 should have it, and no other.

Check this part

  1. What does PARTITION BY order_id do in ROW_NUMBER() OVER (PARTITION BY order_id ORDER BY changed_at DESC)?

  2. How is a window function different from GROUP BY?

Window functions compute per row while looking at a group: ROW_NUMBER finds the latest row per group, LAG compares a row with the previous one.

Part ProNot started

Dates, time zones and data checks

Dates and time zones

Most databases store times in UTC, the world’s reference time. Users live in time zonesTime zoneThe local time of a region. Bugs appear when apps mix up the user's time zone with the server's.Open in glossary →. A question like “orders placed on 2 October” depends on whose 2 October:

QueryResult
WHERE date(created_at) = '2025-10-02' (a UTC day)2003, 2004
WHERE created_at >= '2025-10-01 22:00' AND created_at < '2025-10-02 22:00' (2 October in Belgrade, UTC+2)2001, 2003, 2004

Order 2001 was placed at 22:35 UTC, which is 00:35 on 2 October in Belgrade. A daily report built on UTC days puts it on the wrong day. That’s a classic bug in “today’s orders” screens and end-of-day reports.

Dev note

Date functions differ between databases. SQLite has date(), datetime() and strftime(); PostgreSQL uses ::date, date_trunc() and AT TIME ZONE; MySQL uses DATE() and CONVERT_TZ(). The ideas (UTC storage, half-open ranges) are the same everywhere.

Reconciliation: do the tables agree?

ReconciliationData reconciliationChecking that two places that should agree really do, such as orders and payments, or a report and the database.Open in glossary → means checking that two places that should agree really do: orders vs payments, payments vs refunds, the app’s status vs the history, the database vs a report or an export.

  • Paid vs total: every delivered order has succeeded payments equal to its total (the WITH example above).
  • Refunds vs payments: no payment has more refunded than it was paid.
  • Status vs history: each order’s status matches its latest history row.
  • Report vs database: a dashboard’s “October revenue” equals the SUM from the database for the same days and time zone.

Checks before and after a migration or import

When data is moved, imported or transformed (a migrationData migrationCode that converts data saved by an older app version into the format a newer version expects.Open in glossary →), testers compare before and after:

SELECT COUNT(*)            AS orders,
       COUNT(DISTINCT id)  AS unique_ids,     -- duplicates?
       SUM(total)          AS total_amount,   -- money lost or added?
       SUM(CASE WHEN courier_id IS NULL THEN 1 ELSE 0 END) AS without_courier,  -- NULLs appeared?
       MIN(created_at), MAX(created_at)       -- dates shifted?
FROM orders;

Run it on the old and the new database and compare: here, 14 orders, 14 unique ids, 383.00 in total. Any difference has to be explained.

Read-only, always

Everything in this lesson is reading. On shared environments, keep it that way: ask for a read-only account, never run UPDATE or DELETE on data you don’t own, and add LIMIT while exploring big tables. Heavy queries on production can slow down the app for real users. Ask before running them, or use a replica (a read-only copy of the database). See the safety rules in SQL for Testers.

Check this part

  1. An order was placed at 22:35 UTC on 1 October. On which day does a Belgrade user (UTC+2) expect to see it?

  2. Which filter finds every order on 2 October, whatever the time?

Dates are stored in UTC; filter with half-open ranges in the user's time zone. Reconcile tables, check counts, sums, NULLs and duplicates before and after migrations.

The rest of this lesson is in Bugwise Pro

The last parts of every lesson are part of Bugwise Pro. Sign in to unlock them if you have it.

Part ProNot started

Lab: the FoodDash payments database

Eight exercises, four of them are bugs hidden in the data. Use the schema on the left, preview tables, and press Check answer to compare your result with the expected one. The database runs in your browser, so you can’t break anything; Reset database restores it.

FoodDash payments DB

SQLite, running in your browser

Loading the database engine (about 700 KB, once)…
0 / 8 solved
Exercise 1Medium

Who delivered what

For every delivered order, show the order id, the customer’s name, the restaurant’s name and the courier’s name.

Return: id customer restaurant courier (column names and order don't matter)

Check this part

  1. Order 2008 has a failed payment and then a succeeded one. Is that a double charge?

  2. Why put the SQL query into the bug report?

Eight exercises in the FoodDash payments database: multi-table joins, NOT EXISTS, CASE, window functions, a fan-out trap, and four real bugs in the data.

The rest of this lesson is in Bugwise Pro

The last parts of every lesson are part of Bugwise Pro. Sign in to unlock them if you have it.

Checklist

Advanced SQL checklist

0 of 12 checked

Key takeaways

  • Join along keys, put LEFT JOIN conditions in ON, and beware of fan-out: extra joins multiply rows and inflate sums.
  • Use EXISTS / NOT EXISTS for “has a matching row”; NOT IN breaks when the list contains NULL.
  • WITH names the steps of a complex query; CASE builds categories, flags and conditional sums.
  • Window functions find the latest row per group (ROW_NUMBER) and compare rows with the previous one (LAG).
  • Times are usually stored in UTC: filter with half-open ranges in the user’s time zone.
  • Reconcile tables that should agree, and compare counts, sums and NULLs before and after migrations.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.