Learn SQL/Advanced/Query Performance/SQL Index Selectivity

SQL Index Selectivity

How much does this column actually narrow things down? Low selectivity means an index may not help at all.

What & Why

Selectivity describes the fraction of table rows matched by a predicate; smaller matched fractions are generally more selective. Highly selective lookups are stronger index candidates than predicates that return most of a table.

See How It Works

BUSINESS QUESTION

Growth compares the selectivity of each event name in the events table.

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
  event_name,
  COUNT(*) AS matching_rows,
  ROUND(COUNT(*)::numeric / NULLIF(SUM(COUNT(*)) OVER (), 0), 4) AS table_fraction
FROM growth.events
GROUP BY event_name
ORDER BY table_fraction, event_name;
RESULT — event-name selectivity
event_namematching_rowstable_fraction
activated10.2500
report_viewed10.2500
signup20.5000

The ordered fractions come from all four representative growth.events rows.

This lesson's practice is part of Pro.

Advanced business practice

Sign up free to try it on a real business scenario