Difficulty: Beginner
Why is 'SELECT *' usually considered bad practice in production queries?
SELECT * returns every column whether or not the code needs it, which wastes I/O, memory and network bandwidth, blocks covering-index optimizations, and makes the application fragile when the table's columns change. In production code you should list the columns explicitly. It is still perfectly fine for ad-hoc exploration in a SQL console.
users table may hold a profile bio, a JSONB preferences blob and a resume text. Listing 20 users for a dropdown only needs id and name, yet SELECT * pulls everything across the network and into application memory.(user_id, created_at, amount_paise), a query selecting just those columns never touches the table. SELECT * always needs the full row, so the covering index cannot help.work_mem.INSERT INTO archive SELECT * FROM orders when the two tables drift, or views. In PostgreSQL a view defined with SELECT * expands to the column list at creation time, so new columns silently do not appear.SELECT * FROM orders JOIN users ... returns two id columns, and many drivers keep only the last one, quietly giving you the wrong id.password_hash or pan_number column suddenly flows into API responses if the code serializes the whole row.| Context | OK? |
|---|---|
| Ad-hoc queries in psql, DBeaver, a notebook | Yes |
EXISTS (SELECT * FROM ...) | Yes, the select list is ignored |
COUNT(*) | Yes, unrelated to column selection |
| Small CTE or subquery that the outer query narrows | Usually fine; the planner prunes unused columns |
| Application code, APIs, views, reports | Avoid |
ORMs default to fetching all columns (User.findAll(), Model.objects.all()). Use projections such as Prisma select, Django only() or values(), or SQLAlchemy load_only() on hot paths.
CREATE INDEX orders_user_idx ON orders (user_id) INCLUDE (amount_paise, status);
-- Bad: needs every column, so the table must be read
SELECT * FROM orders WHERE user_id = 42;
-- Good: answered from the index alone
SELECT amount_paise, status FROM orders WHERE user_id = 42;
-- Bad in joins: two "id" columns, driver may keep only one
-- SELECT * FROM orders o JOIN users u ON u.id = o.user_id;
SELECT o.id AS order_id, u.id AS user_id, u.name
FROM orders o JOIN users u ON u.id = o.user_id;
Listing columns lets the optimizer use the covering index and avoids ambiguous duplicate column names.
// Fetches only what the dropdown needs, not bio or resume blobs
const users = await prisma.user.findMany({
where: { collegeId: 12 },
select: { id: true, name: true },
take: 20,
});
ORM projections give the same benefit as explicit SQL columns and keep sensitive fields out of responses.
SELECT *, Column Projection, Covering Index, Network I/O, Schema Evolution