Query Antipatterns
Two queries return the exact same rows from orders. One finishes in a single trip to the database; the other quietly fires a hundred and one, and the row counts on screen give you no hint which one you wrote.
- ▸Two queries can return identical rows while one hits the database once and the other a hundred and one times.
- ▸A
%at the front ofLIKE, or a function wrapped around a column, breaks the index the same way. - ▸Dropping
SELECT *for named columns can revive an index-only scan that skips the table.
Four rows in users, and code that needs each user's order count. The straightforward way reads like a sentence: fetch the users, then loop over them, and for each one run SELECT count(*) FROM orders WHERE user_id = $1, where $1 is that user's id. Four users, so four more queries, five in total. Scale the users to a hundred and the loop fires a hundred and one queries to answer one question. Every one is a separate round trip to the database, and PostgreSQL runs each one as its own statement: the user list once, then the count four times for four users or a hundred times for a hundred, while a single JOIN runs once either way. The counts that come back are correct: a single SELECT ... LEFT JOIN ... GROUP BY that counts o.id would return the identical numbers in one trip. The pattern is invisible in the result and invisible in the row counts on screen. It shows up only when you count how many times the application had to talk to the database.