Video in progress

Why is writing `SELECT *` in prod code a bad habit?

Unneeded columns still travel over the network and take memory, a covering index (Index Only Scan) stops working, and code can break unexpectedly when a column is added to the table or the column order changes. Listing the columns you need explicitly is safer.

📖 Answer

In one project, description (about 20 KB of text on average) and image_meta jsonb were later added to the products table. The list page showed only the name and price, but because of SELECT *, megabytes of data started arriving on every page. Response time tripled while nothing in the code had changed.

Other reasons:

  • Index Only Scan. If there is an index (user_id) INCLUDE (status, total), then SELECT status, total ... WHERE user_id = ? may never touch the table at all. SELECT * loses that option.
  • Brittle code. INSERT INTO archive SELECT * FROM orders fails if the two table structures differ a little, or worse, writes the columns to the wrong places.
  • VIEW. When a VIEW is created, PostgreSQL expands * into the list of columns at that moment, so a column added later doesn't show up in the VIEW.

A quick check in the console, or use inside EXISTS (SELECT * ...) or in a CTE, is fine. When you load a JPA entity, Hibernate lists the columns anyway; for list pages, though, it's better to fetch only the columns you need with a DTO projection (select new ... or an interface projection).