Common Query Pitfalls & Anti-patterns

RoadmapsSQL

Overview

Query pitfalls are common mistakes that return incorrect row-sets or cause severe performance issues. Examples include accidental cross-joins, using SELECT * unnecessarily (which wastes network/memory and breaks applications if columns are added/removed), or applying functions on indexed columns which forces full table scans.

Writing SQL that 'works' on small datasets often masks underlying anti-patterns. Knowing these pitfalls prevents a production outage when data scales.

Where used: database optimization, peer code review

Why learn this

Query walkthrough

SELECT name FROM customers WHERE id IN (SELECT customer_id FROM orders) ORDER BY id;

Focus: Using IN with a subquery is valid, but can sometimes perform poorly compared to EXISTS or a JOIN on larger datasets. Here it filters to the 6 customers who have orders.

Common mistakes

Glossary

outage
A period when a system or service becomes unavailable, often caused by severe performance issues or crashes.
anti-patterns
Commonly used solutions or coding practices that actually create more problems than they solve.
Cartesian
A mathematical term describing a result where every single item in one list is paired with every single item in another list.

Recall questions

Understanding checks

What rows does this return?

8

Counts all 8 customers. A common pitfall is counting a column that has NULLs when you mean to count all rows (like COUNT(*)).

What rows does this return?

7

Customer 5 (Emma) has a NULL country. COUNT(column) ignores NULL values, which is a frequent source of accidental bugs.

Practice tasks

Fixing the COUNT pitfall

Given this query that accidentally ignores NULL countries, change it to safely count all customer rows regardless of NULLs.

Challenge

Avoid SELECT *

Write a query that joins products and order_items for order_id 1, but instead of using SELECT *, explicitly select the product name and the quantity ordered.

Continue learning

Previous: Reading EXPLAIN ANALYZE

Return to SQL Roadmap