Learn SQL/Advanced/Query Performance/SQL SELECT Only Needed Columns

SQL SELECT Only Needed Columns

SELECT * costs more than it looks like — in I/O, and in whether an index-only scan is even possible.

What & Why

Requesting every column means the database has to fetch every column's data for every matching row, even the ones you'll never look at. Naming only the columns you need reduces I/O — and can sometimes unlock an index-only scan, where the answer comes entirely from the index without touching the table at all.

See How It Works

BUSINESS QUESTION

Growth wants a focused recent-event export without the large properties payload.

iduser_idevent_namecreated_atproperties
1001101signup2024-01-15 09:12:00+00{"source":"organic"}
1002101activated2024-01-16 14:25:00+00{"step":"workspace"}
1003102signup2024-02-10 11:08:00+00{"source":"paid"}
1004103report_viewed2024-03-12 16:40:00+00{"report":"retention"}
EXAMPLE QUERY
SELECT
  id AS event_id,
  user_id,
  event_name,
  created_at
FROM growth.events
ORDER BY created_at DESC, event_id
LIMIT 100;
RESULT — focused event projection
event_iduser_idevent_namecreated_at
1004103report_viewed2024-03-12 16:40:00+00
1003102signup2024-02-10 11:08:00+00
1002101activated2024-01-16 14:25:00+00
1001101signup2024-01-15 09:12:00+00

Only the four requested columns are returned, newest first.

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario