SQL bugs usually come from a small set of causes: an unexpected join relationship, a filter applied at the wrong stage, NULL behavior, duplicate source rows, or a plan that scans more data than necessary. This checklist gives you a repeatable way to find the cause, verify the result, and improve performance without changing query behavior accidentally.
Overview
When a SQL query returns the wrong rows or runs slowly, resist the temptation to rewrite everything at once. First establish what the query is supposed to return, then isolate the smallest part that produces the unexpected result. A reliable debugging process separates correctness from performance: a fast query that returns incorrect data is still broken, while a correct query can usually be optimized safely after its behavior is understood.
Start with these four questions:
- What is one row in the intended result supposed to represent?
- Which table or subquery defines that row?
- Can each join produce one matching row, many matching rows, or no matching row?
- What does the database actually do according to its execution plan?
Keep a known input and expected output while testing. Run the query against a small, representative set of records before changing indexes or production code. If the query serves an API, also compare its SQL parameters with the values shown in the application request. The database may be correct while the application sends an unexpected date, status, limit, or identifier.
Checklist by scenario
When a join returns duplicate rows
Duplicates usually indicate that the join relationship is one-to-many or many-to-many, not that SQL has repeated a row by mistake. For example, one customer may have several orders, and each order may have several line items. Joining all three tables naturally produces multiple result rows for one customer.
- Identify the intended grain: customer, order, line item, or another entity.
- Check the uniqueness of the join columns in both tables.
- Count matches before selecting the full result.
- Decide whether you need detail rows, an aggregate, or an existence check.
SELECT c.id, COUNT(o.id) AS order_count
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.id
GROUP BY c.id;
If you only need to know whether a related record exists, EXISTS is often clearer than joining and removing duplicates with DISTINCT:
SELECT c.id, c.email
FROM customers AS c
WHERE EXISTS (
SELECT 1
FROM orders AS o
WHERE o.customer_id = c.id
);
Use DISTINCT only when duplicate result values are genuinely equivalent. It can conceal an incorrect relationship and may add unnecessary work.
When an outer join behaves like an inner join
A LEFT JOIN preserves rows from its left table, but a condition on the right table in the WHERE clause can remove the NULL-extended rows and effectively turn the result into an inner join.
-- Keeps customers with no qualifying order
SELECT c.id, o.created_at
FROM customers AS c
LEFT JOIN orders AS o
ON o.customer_id = c.id
AND o.status = 'paid';
Compare that with a filter in WHERE:
-- Removes customers without a matching paid order
SELECT c.id, o.created_at
FROM customers AS c
LEFT JOIN orders AS o ON o.customer_id = c.id
WHERE o.status = 'paid';
Neither placement is universally right. Put a condition in the join when it defines which related rows may match while preserving the left-side row. Put it in WHERE when unmatched rows should be excluded.
When NULL produces surprising results
NULL represents an unknown or missing value, so comparisons such as value = NULL do not match it. Use IS NULL or IS NOT NULL instead.
SELECT id
FROM users
WHERE deleted_at IS NULL;
Also check expressions that can become NULL. A condition like price > 0 does not match rows where price is NULL. If a missing value should be treated as zero for a specific business rule, make that rule explicit with a function such as COALESCE, while recognizing that applying a function to a column can affect index use depending on the database and query.
When filtering or grouping gives the wrong result
Separate row filtering from group filtering. WHERE is evaluated before aggregation, while HAVING filters grouped results.
SELECT customer_id, COUNT(*) AS paid_orders
FROM orders
WHERE status = 'paid'
GROUP BY customer_id
HAVING COUNT(*) >= 3;
Check that every selected column is either grouped or aggregated according to your database's rules. If a query mixes detail columns with aggregate values, it may be expressing an ambiguous requirement. Decide whether you need the latest row, the maximum value, or all matching rows; then use an explicit aggregate or a window function appropriate to your database.
When pagination is inconsistent
Pagination requires a deterministic order. Ordering only by a non-unique column can cause records to move between pages when ties are resolved differently. Add a unique tie-breaker:
SELECT id, created_at, title
FROM articles
ORDER BY created_at DESC, id DESC
LIMIT 25 OFFSET 50;
For large or frequently changing datasets, investigate cursor or keyset pagination. The choice affects the SQL, indexes, API contract, and client loop; see this guide to REST API pagination patterns before changing an established endpoint.
When the query is correct but slow
- Run the query with representative parameters, not only a tiny development dataset.
- Inspect the execution plan and, where supported, the plan with runtime details.
- Look for full scans on large tables, unexpectedly large intermediate results, repeated work, and expensive sorts or joins.
- Compare estimated and actual row counts if the database exposes both.
- Check whether predicates are selective and whether suitable indexes exist for the access pattern.
- Test one change at a time and record execution time, rows returned, and resource behavior.
Use the plan command provided by your database engine, such as an explain facility, but verify the syntax and options in that engine's documentation. Plan output is an investigation aid, not a guarantee that one plan will remain unchanged as data volume, statistics, parameters, or indexes change.
What to double-check
| Area | Question | Typical correction |
|---|---|---|
| Join type | Should unmatched rows be preserved? | Choose inner, left, or another join deliberately. |
| Join key | Is the relationship based on the correct columns? | Verify identifiers, tenant keys, and data types. |
| Filters | Should the condition apply before or after the join or aggregation? | Move it between ON, WHERE, and HAVING as required. |
| NULLs | Can missing values occur? | Use NULL-aware predicates and explicit fallback rules. |
| Duplicates | What is the intended result grain? | Aggregate, use EXISTS, or correct the relationship instead of masking rows. |
| Ordering | Is the order stable across pages? | Add a unique tie-breaker. |
| Performance | Does the plan process more rows than expected? | Review predicates, statistics, indexes, and query shape. |
For application-level debugging, capture the final SQL shape and bound parameters without exposing secrets or personal data. A request that appears identical in application logs may use different parameter types or values. Browser request details can help connect an API symptom to its database input; the Browser DevTools Network workflow covers that part of the investigation.
Common mistakes
- Adding DISTINCT as a first fix: this hides duplicate-producing joins without explaining why they exist.
- Changing several clauses at once: you lose the ability to identify which change affected correctness or speed.
- Testing only with a small dataset: a query can appear fast until it encounters realistic cardinality.
- Ignoring data types: implicit conversions, mismatched identifiers, and date comparisons can change results or prevent efficient access.
- Using SELECT * in long-lived queries: it increases coupling to schema changes and may read columns the consumer does not need.
- Trusting an old execution plan: plans depend on data distribution, statistics, indexes, parameters, and engine behavior.
- Skipping transaction context: concurrent writes can make two otherwise identical reads appear different, depending on the isolation and timing.
When to revisit
Return to this checklist whenever a report, API endpoint, background job, or migration changes its data shape or workload. Recheck queries before seasonal planning cycles or other predictable periods of increased activity, especially when date ranges, customer counts, or event volumes will grow.
Also revisit a query after:
- adding or removing an index;
- changing a join, filter, grouping rule, or pagination method;
- upgrading the database engine or changing configuration;
- loading a substantially different data distribution;
- changing an API response contract or parameter type;
- observing a production slowdown that a small test dataset did not reproduce.
Make the final check practical: save the corrected query, its intended row grain, representative parameters, and the plan or measurements that justified the change. Then test both a normal case and an edge case, such as no related rows, duplicate relationships, NULL values, tied sort keys, and an empty page. This creates a compact regression reference for the next investigation rather than relying on memory.