Sharon Ben-Moshe is the founder of sqlfmt, a browser-based SQL formatter and validator with misspelled-keyword suggestions across PostgreSQL, MySQL, SQLite, SQL Server, and BigQuery.
Discover 7 dangerous SQL anti-patterns that degrade query performance and corrupt results. Learn how to refactor non-SARGable predicates and NULL pitfalls.
Quick answer
SQL anti-patterns are common query and schema design habits that degrade query performance, bypass indexes, or produce inaccurate results. Major anti-patterns include non-SARGable function calls in WHERE clauses, NOT IN with nullable subqueries, SELECT *, correlated subqueries in SELECT lists, and implicit data type conversions.
FAQs
What does SARGable mean in SQL?
SARGable stands for Search Argument Able. It describes a query predicate structured so that the query engine can use an index seek rather than scanning the entire table.
Why is NOT EXISTS better than NOT IN?
NOT IN fails completely if the subquery returns even a single NULL value, returning zero rows. NOT EXISTS handles NULL values cleanly and often compiles to more efficient anti-join execution plans.
Can a query use an index if I use a wildcard at the beginning of LIKE?
No. Leading wildcards (LIKE '%text') prevent B-tree index seeks. You must use full-text search or trigram indexes for substring matching.
Does SELECT * impact performance if the table only has a few columns?
Yes. It prevents the optimizer from using Index Only Scans, increases network payload size, and can break application code if schema migrations add new columns.
Implement distributed locks and cron leader election in PostgreSQL using advisory locks. Compare session vs transaction locks and non-blocking try locks.
Compare natural keys, auto-increment surrogate keys, and UUIDs for primary keys. Learn how UUIDv7 and sequential IDs impact B-tree index fragmentation.
Even experienced developers occasionally write SQL queries that look clean but perform poorly in production. These recurring habits are known as SQL anti-patterns. They cause database engines to ignore indexes, scan millions of unnecessary rows, and produce incorrect results when handling null values.
Refactoring these patterns requires minimal effort once you understand how database optimizers evaluate queries. Reviewing the seven most common anti-patterns will protect your database performance and improve query reliability across your engineering team.
1. Non-SARGable predicates: functions on indexed columns
SARGable stands for Search Argument Able. A query predicate is SARGable if the database engine can use an index seek to find matching rows. Wrapping an indexed column inside a function prevents the optimizer from using the index, forcing a full table scan.
Refactoring non-SARGable date filters
-- Anti-pattern: function on indexed created_at column forces full table scanSELECT order_id, total_amountFROM ordersWHERE YEAR(created_at) = 2026 AND MONTH(created_at) = 10;-- Refactored SARGable query: uses B-tree index range scan!SELECT order_id, total_amountFROM ordersWHERE created_at >= '2026-10-01' AND created_at < '2026-11-01';
The same problem occurs with string manipulation like WHERE UPPER(email) = 'ALEX@EXAMPLE.COM' or mathematical operations like WHERE price * 1.2 > 100. Always isolate the bare column on one side of the operator: WHERE price > 100 / 1.2.
2. NOT IN with nullable subqueries
In three-valued SQL logic, comparing any value against NULL evaluates to UNKNOWN. When you use NOT IN (subquery) and the subquery returns even a single NULL value, the entire query returns zero rows! Read our guide on SQL NULL comparison rules for logical foundations.
The dangerous NOT IN with NULL anti-pattern
-- If ANY inactive customer has NULL email, this query returns ZERO rows!SELECT customer_id, emailFROM customersWHERE email NOT IN (SELECT email FROM inactive_subscribers);-- Refactored query: use NOT EXISTS (safe and faster)SELECT c.customer_id, c.emailFROM customers cWHERE NOT EXISTS ( SELECT 1 FROM inactive_subscribers s WHERE s.email = c.email);
3. SELECT * in production application queries
Using SELECT * in production code wastes network bandwidth, inflates database memory buffers, and breaks covering indexes. When you specify exact column names, database optimizers can often satisfy the entire query directly from an index without reading table heap pages (Index Only Scan).
4. Leading wildcards in LIKE expressions
A B-tree index stores values sorted alphabetically. When you search with LIKE 'prefix%', the engine performs an efficient B-tree range scan. When you add a leading wildcard like LIKE '%suffix', the index ordering is useless, and the engine must scan every single row. If you need substring search, use Full-Text Search or trigram GIN indexes.
5. Correlated subqueries in the SELECT list
Placing a subquery in the SELECT column list forces the query engine to execute that subquery for every single row returned by the outer query:
Refactoring SELECT list subqueries into LEFT JOIN
-- Anti-pattern: executes subquery for every single customerSELECT c.id, c.name, (SELECT COUNT(*) FROM orders o WHERE o.customer_id = c.id) AS order_countFROM customers c;-- Refactored query: single pass aggregation via LEFT JOINSELECT c.id, c.name, COUNT(o.id) AS order_countFROM customers cLEFT JOIN orders o ON o.customer_id = c.idGROUP BY c.id, c.name;
6. Implicit data type conversion in WHERE clauses
When comparing two different data types, the database engine converts one side to match the other according to data type precedence rules. If the engine converts the column rather than the constant, index usage is disabled.
Implicit conversion index negation
-- If account_number is VARCHAR, passing an integer forces CONVERT on every row!-- Forces table scan:SELECT * FROM accounts WHERE account_number = 104291;-- SARGable: passing matching string literal uses index seek!SELECT * FROM accounts WHERE account_number = '104291';
7. Overusing DISTINCT to hide bad JOIN logic
When developers join tables and get duplicated rows due to one-to-many cardinality mistakes, they often slap DISTINCT onto the SELECT statement to hide the duplicates. DISTINCT forces a heavy in-memory sort or hash deduplication step. Instead of hiding Cartesian duplicates with DISTINCT, fix the underlying join conditions or group by the true entity identifier.
Actionable checklist for avoiding SQL anti-patterns
Audit WHERE clauses: verify all indexed columns appear bare without enclosing function wrappers.
Ban NOT IN on subqueries: mandate NOT EXISTS or LEFT JOIN ... WHERE id IS NULL in team code reviews.
Eliminate SELECT *: enforce explicit column lists across all application repositories and ORMs.
Check data type alignment: confirm query parameter types match underlying column definitions in database drivers.
Replace correlated SELECT subqueries: refactor row-by-row scalar subqueries into joins with GROUP BY.
Investigate DISTINCT usage: treat DISTINCT as a code smell in join queries and verify entity cardinality.
Wrapping up
Avoiding common SQL anti-patterns ensures that database query optimizers execute queries with maximum efficiency. By writing SARGable filters, guarding against null values, and selecting explicit columns, you maintain fast, predictable database performance. Keep your team SQL queries clean and standardized by formatting your codebase with sqlfmt or reviewing our Pro subscription.