SQL Debugging Lab

Updated · 6 min read

Each case here starts the way real problems do: with a complaint, not a bug report. A total is too big, a list is empty, a report never finishes, a save hangs, the app runs out of connections, a page shows yesterday's data. For each one you get the evidence, then you find the cause and the fix. Work with the method from Troubleshooting a Database: symptom, evidence, cause, fix, prevent. Cases 1 to 3 run in Try it; cases 4 to 6 need several sessions or servers, so their evidence is described as you would see it, and the fix is the SQL or setting you'd apply.

Case 1: The Doubled Total

Symptom: "The finance report says Srihitha paid $6,800.00. Her receipts add up to $1,700.00."

Evidence: the report's query.

SQL
SELECT s.first_name, sum(p.amount_usd) AS total_paid_usd
FROM students s
JOIN enrollments e ON e.student_id = s.student_id
JOIN payments    p ON p.student_id = s.student_id
GROUP BY s.first_name
ORDER BY s.first_name;
Show solution
SQL▶ Try it
-- Cause: each payment is repeated once per enrollment of the same student.
-- Evidence: count the rows the join produces for Srihitha.
SELECT count(*) AS joined_rows,
       count(DISTINCT p.payment_id) AS real_payments
FROM students s
JOIN enrollments e ON e.student_id = s.student_id
JOIN payments    p ON p.student_id = s.student_id
WHERE s.first_name = 'Srihitha';
 
-- Fix: payments already carry student_id; don't join enrollments.
SELECT s.first_name, sum(p.amount_usd) AS total_paid_usd
FROM students s
JOIN payments p ON p.student_id = s.student_id
GROUP BY s.first_name
ORDER BY s.first_name;
Output
 joined_rows | real_payments
-------------+---------------
          20 |             5
(1 row)
 
 first_name | total_paid_usd
------------+----------------
 Navika     |         450.00
 Srihitha   |        1700.00
(2 rows)

Cause: Srihitha has 4 enrollments and 5 payments; joining both to her student row pairs every payment with every enrollment, so the join produces 20 rows and each payment counts 4 times: 4 × $1,700.00 = $6,800.00. Prevent: before summing after several joins, compare count(*) with count(DISTINCT key); if they differ, rows are multiplying (Joining Many Tables).

Case 2: The Empty List

Symptom: "The 'students who haven't paid' page is blank, but I know Advitha hasn't paid."

Evidence: the query, and one recent change: a payment imported from the bank with no student yet.

Show solution
SQL▶ Try it
CREATE TEMP TABLE imported AS SELECT student_id FROM payments;
INSERT INTO imported VALUES (NULL);   -- the unassigned bank payment
 
-- The page's query: returns nothing
SELECT first_name FROM students
WHERE student_id NOT IN (SELECT student_id FROM imported);
 
-- Fix: NOT EXISTS isn't affected by the NULL
SELECT first_name FROM students s
WHERE NOT EXISTS (SELECT 1 FROM imported i WHERE i.student_id = s.student_id)
ORDER BY first_name;
Output
SELECT 7
 
INSERT 0 1
 
 first_name
------------
(0 rows)
 
 first_name
------------
 Advitha
(1 row)

Cause: x NOT IN (..., NULL) is never true, because x <> NULL is unknown. One NULL in the subquery empties the result. Prevent: use NOT EXISTS for anti-joins, and make columns NOT NULL when a value is always required (EXISTS).

Case 3: The Report That Never Finishes

Symptom: "The yearly report times out." It runs on a table of 100,000 payments.

Show solution
SQL▶ Try it
CREATE TABLE big_payments (
  payment_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  student_id INTEGER NOT NULL, paid_on DATE NOT NULL,
  amount_usd NUMERIC(8,2) NOT NULL, method TEXT, note TEXT
);
INSERT INTO big_payments (student_id, paid_on, amount_usd, method, note)
SELECT 1000 + (g % 5000), DATE '2024-01-01' + (g % 730), 100 + (g % 400),
       (ARRAY['card', 'check', 'cash'])[1 + g % 3], 'payment ' || g
FROM generate_series(1, 100000) AS g;
ANALYZE big_payments;
 
-- Evidence: the plan reads every row
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT count(*), sum(amount_usd) FROM big_payments
WHERE EXTRACT(YEAR FROM paid_on) = 2025 AND student_id = 1234;
 
-- Fix: an index for the filter, and a range instead of a function on the column
CREATE INDEX big_payments_student_paid_idx ON big_payments (student_id, paid_on);
 
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT count(*), sum(amount_usd) FROM big_payments
WHERE paid_on >= '2025-01-01' AND paid_on < '2026-01-01' AND student_id = 1234;
Output
CREATE TABLE
 
INSERT 0 100000
 
ANALYZE
 
                                        QUERY PLAN
------------------------------------------------------------------------------------------
 Aggregate (actual rows=1.00 loops=1)
   ->  Seq Scan on big_payments (actual rows=10.00 loops=1)
         Filter: ((student_id = 1234) AND (EXTRACT(year FROM paid_on) = '2025'::numeric))
         Rows Removed by Filter: 99990
(4 rows)
 
CREATE INDEX
 
                                                       QUERY PLAN
------------------------------------------------------------------------------------------------------------------------
 Aggregate (actual rows=1.00 loops=1)
   ->  Bitmap Heap Scan on big_payments (actual rows=10.00 loops=1)
         Recheck Cond: ((student_id = 1234) AND (paid_on >= '2025-01-01'::date) AND (paid_on < '2026-01-01'::date))
         Heap Blocks: exact=10
         ->  Bitmap Index Scan on big_payments_student_paid_idx (actual rows=10.00 loops=1)
               Index Cond: ((student_id = 1234) AND (paid_on >= '2025-01-01'::date) AND (paid_on < '2026-01-01'::date))
               Index Searches: 1
(7 rows)

Cause: no index matched the filter, and EXTRACT(YEAR FROM paid_on) hides paid_on from an index anyway. The scan read 100,000 rows to keep 10. Fix: an index on (student_id, paid_on) and a plain date range let PostgreSQL find the 10 rows directly (Index Design).

Case 4: The Save That Hangs

Symptom: "Saving a payment spins forever since 2:10 p.m."

Evidence, from pg_stat_activity with pg_blocking_pids(pid) on the production server:

pidstatewaiting forblocked bystartedquery
4121activeLock38772:12 p.m.UPDATE payments SET method = 'card' WHERE payment_id = 5
3877idle in transaction(none)(none)2:10 p.m.UPDATE payments SET amount_usd = 200.00 WHERE payment_id = 5

Cause: session 3877 updated payment 5, then the app stopped using its connection without committing (idle in transaction), so its row lock never released, and every later update of that row waits.

Fix: end the blocker, then fix the code path that left the transaction open:

SQL
SELECT pg_terminate_backend(3877);   -- rolls back its open transaction
ALTER ROLE fee_app SET idle_in_transaction_session_timeout = '30s';
ALTER ROLE fee_app SET lock_timeout = '5s';

Prevent: the timeouts stop one stuck session from freezing the app again (Locks and Deadlocks).

Case 5: Out of Connections

Symptom: "Users see 'sorry, too many clients already' since the morning deploy."

Evidence: max_connections is 100. Counting sessions by state shows 4 active, 93 idle and 3 reserved for administrators. The deploy raised the app from 6 copies to 12, each with a pool of 8 connections.

Cause: 12 copies × 8 connections = 96 connections, nearly all idle but all held open, plus the background tools: the server is full before any real work starts.

Fix: shrink each pool to what one copy really uses (the 4 active sessions suggest 2 or 3 per copy), or put PgBouncer in transaction mode in front of the database; don't just raise max_connections (Replication and Scaling).

Case 6: Yesterday's Data

Symptom: "The dashboard is missing today's payments, but the payments page shows them."

Evidence: the dashboard reads from a replica. On the primary, pg_stat_replication shows the replica with replay_lag of 6 hours 12 minutes; on the replica, a dashboard export query has been running for 6 hours.

Cause: the long query on the replica conflicts with changes it must replay, and the replica is set to delay replay rather than cancel queries, so it has fallen hours behind.

Fix: stop the long query, move huge exports to a separate replica or the analytics store, and alert on replay_lag over a few minutes (Troubleshooting a Database).

What to Practice Next

Was this tutorial helpful?