SQL Anti-Patterns and How to Fix Them
A catalogue of common SQL mistakes in queries, schemas and applications, with the fix for each: NOT IN with NULLs, join fan-out hidden by DISTINCT, floating-point money, comma-separated lists, BETWEEN on timestamps, deep OFFSET paging, N+1 queries, EAV tables and more.
kvi5hnuCode Sprout team member11 min readOn this page
Some mistakes come up again and again in real SQL code. They're not syntax errors: the queries run, often return plausible answers, and pass tests on small data. Then they give wrong results on an edge case, or grind to a halt on production volumes.
This article collects the most common of these anti-patterns, shows each one failing, and gives the fix. Many were introduced in earlier articles, and the links lead to fuller explanations. Use it as a checklist when reviewing SQL, your own or anyone else's.
Queries that return wrong results
NOT IN with a NULL
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- NOT IN with a NULL in the list: no rows at all
-- Which customers have never been referred to anyone? (referred_by holds a NULL)
SELECT name FROM customers
WHERE customer_id NOT IN (SELECT referred_by FROM customers);
-- NOT EXISTS gives the intended answer
SELECT c.name FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM customers r WHERE r.referred_by = c.customer_id)
ORDER BY c.name;
name
------
(0 rows)
name
--------------
Dana Cruz
Eli Novak
Farah Haddad
(3 rows)
The question "which customers have never referred anyone?" should list three people, but NOT IN returns nothing. The subquery's referred_by values include NULL, for customers nobody referred, and x NOT IN (1, 2, 3, NULL) is never true: comparing with NULL is unknown (article 8).
Fix: use NOT EXISTS, which isn't affected by NULLs, or filter the NULLs out of the subquery (article 16). Make NOT EXISTS the habit for anti-joins.
Join fan-out, hidden with DISTINCT

-- Joining two child tables at once multiplies rows ("fan-out")
CREATE TABLE inv (inv_id INTEGER PRIMARY KEY, customer TEXT);
CREATE TABLE inv_lines (inv_id INTEGER, amount NUMERIC(8, 2));
CREATE TABLE inv_payments (inv_id INTEGER, paid NUMERIC(8, 2));
INSERT INTO inv VALUES (1, 'Asha');
INSERT INTO inv_lines VALUES (1, 100.00), (1, 50.00); -- invoice total 150
INSERT INTO inv_payments VALUES (1, 75.00), (1, 75.00); -- two equal payments: 150
-- Wrong: each line pairs with each payment, so both sums double
SELECT i.inv_id, SUM(l.amount) AS billed, SUM(p.paid) AS paid
FROM inv i
JOIN inv_lines l ON l.inv_id = i.inv_id
JOIN inv_payments p ON p.inv_id = i.inv_id
GROUP BY i.inv_id;
-- "Fixed" with DISTINCT: it hides the symptom, and drops one of the equal payments
SELECT i.inv_id, SUM(DISTINCT l.amount) AS billed, SUM(DISTINCT p.paid) AS paid
FROM inv i
JOIN inv_lines l ON l.inv_id = i.inv_id
JOIN inv_payments p ON p.inv_id = i.inv_id
GROUP BY i.inv_id;
-- Right: aggregate each child table before joining
SELECT i.inv_id, l.billed, p.paid
FROM inv i
JOIN (SELECT inv_id, SUM(amount) AS billed FROM inv_lines GROUP BY inv_id) l ON l.inv_id = i.inv_id
JOIN (SELECT inv_id, SUM(paid) AS paid FROM inv_payments GROUP BY inv_id) p ON p.inv_id = i.inv_id;
inv_id | billed | paid
--------+--------+--------
1 | 300.00 | 300.00
(1 row)
inv_id | billed | paid
--------+--------+-------
1 | 150.00 | 75.00
(1 row)
inv_id | billed | paid
--------+--------+--------
1 | 150.00 | 150.00
(1 row)
Joining an invoice to both its lines and its payments pairs every line with every payment: two lines times two payments gives four rows, and both sums double (article 17). A common "fix" is DISTINCT, here SUM(DISTINCT ...), which happens to fix the lines but turns two equal payments of 75.00 into one, reporting 75.00 paid instead of 150.00.
Fix: aggregate each child table before joining, in derived tables or CTEs, so each side contributes one row per invoice. In general, a DISTINCT added to make duplicates disappear is a sign that a join is wrong. Find out where the extra rows come from.
Floating-point money
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Floating-point money: binary fractions can't represent 0.10 exactly
SELECT SUM(0.10::double precision) = 1.0 AS float_sum_is_one,
SUM(0.10::numeric) = 1.0 AS numeric_sum_is_one,
SUM(0.10::double precision) AS float_sum
FROM generate_series(1, 10);
SELECT 0.1::float8 + 0.2::float8 = 0.3::float8 AS float_equal,
0.1::numeric + 0.2::numeric = 0.3 AS numeric_equal;
float_sum_is_one | numeric_sum_is_one | float_sum
------------------+--------------------+--------------------
f | t | 0.9999999999999999
(1 row)
float_equal | numeric_equal
-------------+---------------
f | t
(1 row)
REAL, DOUBLE PRECISION and FLOAT store binary fractions, which can't represent most decimal amounts exactly. Adding 0.10 ten times gives 0.9999999999999999, and 0.1 + 0.2 = 0.3 is false. Over millions of transactions, rounding errors add up and totals stop matching.
Fix: store money in NUMERIC/DECIMAL with a fixed scale, such as NUMERIC(12, 2), or as an integer number of the smallest unit, such as cents (article 35). Use floating point for measurements where tiny errors don't matter.
BETWEEN with timestamps
-- BETWEEN with timestamps misses most of the last day
CREATE TABLE events (event_id INTEGER, happened_at TIMESTAMP);
INSERT INTO events VALUES
(1, TIMESTAMP '2026-03-01 09:00'),
(2, TIMESTAMP '2026-03-31 00:00'),
(3, TIMESTAMP '2026-03-31 18:45'),
(4, TIMESTAMP '2026-04-01 00:00');
SELECT COUNT(*) AS between_count
FROM events WHERE happened_at BETWEEN DATE '2026-03-01' AND DATE '2026-03-31';
-- A half-open range includes all of March and nothing else
SELECT COUNT(*) AS half_open_count
FROM events WHERE happened_at >= DATE '2026-03-01' AND happened_at < DATE '2026-04-01';
between_count
---------------
2
(1 row)
half_open_count
-----------------
3
(1 row)
BETWEEN DATE '2026-03-01' AND DATE '2026-03-31' compares timestamps with midnight at the start of 31 March, so the event at 18 that day is missed. Only two of the three March events are counted.
Fix: use a half-open range: >= start AND < day after end (article 40). It works for dates and timestamps of any precision, and consecutive ranges never overlap or leave gaps.
Other wrong-result patterns
= NULLinstead ofIS NULL: never true (article 8).COUNT(column)when you meantCOUNT(*): it skips NULLs (article 18).- Integer division, such as
5 / 2returning 2 in many databases: cast one side to a decimal type (article 38). - An outer join undone by
WHERE: a condition on the outer table's columns inWHEREturns aLEFT JOINinto an inner join. Put it inON(article 13). ORDER BYmissing or not unique underLIMITorFETCH FIRST: the rows returned can change between runs. Add a unique tiebreaker (article 9).- Selecting non-grouped columns where the database allows it, as older MySQL did: you get a value from an arbitrary row (article 19).
Schema designs that cause trouble
Lists in a column
-- A comma-separated list in a column
CREATE TABLE gear_tags_csv (gear TEXT, tags TEXT);
INSERT INTO gear_tags_csv VALUES
('Ridge 2 tent', 'camping,shelter'),
('Glow head torch', 'camping-light,running'),
('Merino socks', 'hiking,running');
-- Searching it with LIKE finds the wrong rows
SELECT gear FROM gear_tags_csv WHERE tags LIKE '%camping%' ORDER BY gear;
-- One row per tag: exact matches, joins, counts and constraints all work
CREATE TABLE gear_tags (gear TEXT, tag TEXT, PRIMARY KEY (gear, tag));
INSERT INTO gear_tags
SELECT gear, unnest(string_to_array(tags, ',')) FROM gear_tags_csv;
SELECT gear FROM gear_tags WHERE tag = 'camping' ORDER BY gear;
SELECT tag, COUNT(*) AS items FROM gear_tags GROUP BY tag ORDER BY items DESC, tag;
gear
-----------------
Glow head torch
Ridge 2 tent
(2 rows)
gear
--------------
Ridge 2 tent
(1 row)
tag | items
---------------+-------
running | 2
camping | 1
camping-light | 1
hiking | 1
shelter | 1
(5 rows)
Storing several values in one text column, such as 'camping,shelter', breaks first normal form (article 51), and every query pays for it. LIKE '%camping%' also matches camping-light. There's no way to enforce valid tags, count items per tag efficiently, or index the values.
Fix: a junction table with one row per item and tag, as gear_tags shows. Exact matches, joins, counts, foreign keys to a tags table and indexes all work normally. PostgreSQL arrays or JSON can be reasonable for values that are only ever read together, but not for values you search, join or constrain.
Entity-attribute-value (EAV) tables
A table such as attributes(entity_id, name, value), holding every property of every entity as rows of text, promises total flexibility. In practice:
- Every value is text, so there are no types, no
CHECKconstraints, noNOT NULLand no foreign keys. - Reading one entity's properties needs a pivot (article 44), and filtering on two properties needs a join per property.
- Queries are long, slow and easy to get wrong.
Fix: real columns for the attributes you know about. For genuinely open-ended attributes, such as product specifications that vary by category, a JSON column (article 43) keeps the flexibility with far better query support, and can be indexed with GIN.
Other schema problems
- No primary key, or no unique constraint on the natural key, so duplicates creep in (article 52).
- Missing foreign keys "for performance": the database can't stop orphaned rows, and they appear (article 52).
- Unindexed foreign keys: slow joins and slow parent deletes (articles 53 and 57).
- Polymorphic associations: a
commentable_idwith acommentable_typesaying which table it refers to. No foreign key is possible. Use a separate nullable foreign key per parent table with aCHECKthat exactly one is set, or a separate table per parent. - Dates and numbers stored as text: invalid values get in, sorting is wrong (
'10' < '9'), and every query needs conversions (article 35). - Wide tables of repeated columns, such as
phone1,phone2,phone3: a repeating group that belongs in a child table (article 51).
Queries that are slow
Deep OFFSET pagination
-- Deep OFFSET pagination reads and throws away every skipped row
CREATE TABLE feed (post_id INTEGER PRIMARY KEY, body TEXT);
INSERT INTO feed SELECT g, 'post ' || g FROM generate_series(1, 200000) AS g;
ANALYZE feed;
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT post_id, body FROM feed ORDER BY post_id LIMIT 10 OFFSET 150000;
-- Keyset pagination: start after the last row the user saw
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF)
SELECT post_id, body FROM feed WHERE post_id > 150000 ORDER BY post_id LIMIT 10;
QUERY PLAN
-----------------------------------------------------------------------
Limit (actual rows=10 loops=1)
-> Index Scan using feed_pkey on feed (actual rows=150010 loops=1)
(2 rows)
QUERY PLAN
-------------------------------------------------------------------
Limit (actual rows=10 loops=1)
-> Index Scan using feed_pkey on feed (actual rows=10 loops=1)
Index Cond: (post_id > 150000)
(3 rows)
To return page 15,001 with LIMIT 10 OFFSET 150000, the database reads 150,010 rows and throws away all but the last 10. Every later page is slower than the one before. Rows inserted or deleted between requests also shift the pages, so users see duplicates or miss rows.
Fix: keyset pagination (article 10): remember the last key shown and ask for WHERE post_id > last_seen ORDER BY post_id LIMIT 10. The index goes straight to the right place, and the query reads exactly 10 rows, whichever page it is.
The N+1 query problem
An application loads 50 orders with one query, then loops over them and runs one more query per order to load its customer: 51 queries instead of one or two. Each query is fast, but the round trips add up, and pages with hundreds of items make hundreds of queries. ORMs make this easy to do without noticing, through lazily loaded relationships.
Fix: fetch related data in the same query with a join, or in one second query with WHERE customer_id = ANY($1) or IN (...) for all the IDs at once. ORMs have "eager loading" options for this, such as JOIN FETCH, include or select_related. Query logs and pg_stat_statements (article 67), showing the same query called thousands of times, reveal N+1 patterns.
Other slow patterns
- Functions or casts on indexed columns in
WHERE, such asWHERE EXTRACT(YEAR FROM placed_on) = 2025, which prevent index use (article 55). - Leading-wildcard
LIKE '%term%'on large tables without a trigram index or full-text search (article 55). SELECT *in application queries: it reads and sends columns nobody uses, defeats index-only scans, and breaks code when columns are added or reordered. List the columns.- Row-by-row processing in loops or cursors where one set-based statement would do (articles 62 and 63).
ORDER BY random() LIMIT 1on a large table, which sorts every row to pick one. UseTABLESAMPLEor pick a random key range.COUNT(*)to check existence, such asIF (SELECT COUNT(*) ...) > 0, which counts every match.EXISTSstops at the first (article 16).UNIONwhereUNION ALLis meant:UNIONremoves duplicates, which needs a sort or hash of the whole result (article 15).- Long transactions that hold locks and old row versions (articles 60 and 61).
Application patterns that are dangerous
- SQL built by string concatenation: SQL injection (article 59). Always use parameters.
- Read-modify-write in the application without locking or version checks: lost updates (article 61). Use atomic
UPDATEs,FOR UPDATEor optimistic locking. SELECT MAX(id) + 1to generate keys: two sessions get the same value. Use identity columns or sequences (article 54).- Connecting as a superuser or table owner: one bug compromises everything (article 58).
- Ignoring the affected row count: an
UPDATEthat matched nothing reports success (article 60). - Catching every database error and carrying on: failed transactions keep going, half finished. Roll back and report (articles 60 and 63).
A review checklist
When reviewing a query, ask:
- Can any column in a comparison,
NOT INor aggregate be NULL, and does the query handle it? - Can any join multiply rows? Are there two one-to-many joins from the same table?
- Is
DISTINCThiding a join problem? - Are ranges half-open? Are money and quantities exact types?
- Is the
ORDER BYdeterministic where it matters? - Can the database use an index for each selective condition and join?
- Will this still be fast with 100 times the data?
- Are all values from outside passed as parameters?
What's current
- PostgreSQL 15 added
UNIQUE NULLS NOT DISTINCTand PostgreSQL 16 addedANY_VALUE, explicit replacements for older workarounds such as partial unique indexes and selecting non-grouped columns. - MySQL 5.7+ enables
ONLY_FULL_GROUP_BYby default, rejecting queries that select non-grouped columns. - Linters such as SQLFluff, and many ORMs' query analysis tools, now catch several of these anti-patterns automatically.
Common questions
Why does NOT IN sometimes return no rows?
The subquery returns a NULL. Use NOT EXISTS.
Is SELECT * always wrong? It's fine for exploring data by hand. In application code and views, list the columns.
When is OFFSET pagination acceptable? For small result sets, or when users rarely go beyond the first few pages. For deep or infinite scrolling, use keyset pagination.
Is EAV ever the right choice? Rarely, for truly unknown attributes with little querying. A JSON column is usually better.
How do I spot N+1 queries?
Look for the same query, with different parameter values, run many times per request in your logs or pg_stat_statements.
Summary
- Wrong-result anti-patterns:
NOT INwith NULLs, join fan-out hidden byDISTINCT, floating-point money,BETWEENon timestamps,= NULL, and non-deterministic ordering. - Schema anti-patterns: lists in columns, EAV tables, missing keys and constraints, polymorphic references, and values stored as text.
- Performance anti-patterns: deep
OFFSET, N+1 queries, functions on indexed columns, leading wildcards,SELECT *, and row-by-row loops. - Application anti-patterns: string-built SQL, unprotected read-modify-write,
MAX(id) + 1, over-privileged connections and ignored errors. - When duplicates appear, find their cause rather than adding
DISTINCT.
Practice questions
Rewrite SELECT name FROM products WHERE product_id NOT IN (SELECT product_id FROM order_items) so it's safe even if order_items.product_id could be NULL.
Answer
SELECT p.name
FROM products p
WHERE NOT EXISTS (SELECT 1 FROM order_items oi WHERE oi.product_id = p.product_id);
A query joins customers to both orders and support_tickets, and reports each customer's order count and ticket count with COUNT(*). Why are the numbers too high, and how do you fix it?
Answer
Each order pairs with each ticket for the same customer, so both counts become orders × tickets. Count each table separately, in derived tables or CTEs grouped by customer, then join those results to customers, with LEFT JOIN and COALESCE(..., 0) for customers with none.
An app shows 20 products per page, and users can jump to page 5,000. What problem will appear, and what's the alternative?
Answer
OFFSET 99980 makes the database read and discard almost 100,000 rows for every request, getting slower with each page, and concurrent inserts shift the pages. Keyset pagination, WHERE (sort_key, id) > (last values) ORDER BY sort_key, id LIMIT 20, reads only 20 rows. If jumping to arbitrary page numbers is required, limit how deep users can go, or precompute page boundaries.
Why is WHERE created_at BETWEEN '2026-01-01' AND '2026-01-31' wrong for a timestamp column, and what's the correct condition?
Answer
The upper bound means midnight at the start of 31 January, so almost all of 31 January is excluded. Use created_at >= '2026-01-01' AND created_at < '2026-02-01'.
Previous: Query Plans and Tuning: Reading EXPLAIN

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.