Common Mistakes to Avoid
Most SQL bugs aren't exotic — they're the same handful of gotchas showing up again and again, often because the mistake looks perfectly reasonable at first glance. This page is a quick reference to the ones that trip people up most often, so you can recognize them before they cause a problem instead of after.
Mistake | Why it hurts |
|---|---|
Forgetting | Without a |
Using |
|
Confusing |
|
| If the subquery or list used with |
|
|
Assuming | Column order is not a guaranteed contract — a later schema change can reorder or add columns, silently breaking code that reads results positionally instead of by name. |
Building queries with string concatenation | Splicing user input directly into a SQL string opens the door to SQL injection and breaks on ordinary input like an apostrophe in a name. Always use parameterized queries. |
Over-indexing or under-indexing | Too few indexes means slow lookups and full table scans on large tables; too many indexes slows down every |
Skipping transactions on multi-step operations | Running related statements independently means a failure partway through can leave data in an inconsistent state, with some changes applied and others not. |
Ignoring | Assuming a query is fast because it "looks simple" instead of checking whether the planner is actually using an index — a missing index often only becomes visible in |
The NULL comparison trap, illustrated
This returns zero rows, even for rows where email really is NULL
SELECT * FROM users WHERE email = NULL; -- always empty, this is wrong SELECT * FROM users WHERE email IS NULL; -- correct
The NOT IN with NULLs trap, illustrated
A single NULL in the subquery silences the whole query
-- if any refunded order has a NULL customer_id, this returns NO rows, -- even for customers who clearly never appear in refunded_orders: SELECT * FROM customers WHERE id NOT IN (SELECT customer_id FROM refunded_orders); -- NOT EXISTS does not have this problem: SELECT * FROM customers c WHERE NOT EXISTS ( SELECT 1 FROM refunded_orders r WHERE r.customer_id = c.id );