Full answer
Common causes
- Function or cast on the column: WHERE lower(email) = 'x' cannot use an index on email. Fix: an expression index on lower(email), or store the data normalised.
- Low selectivity: if 99 percent of rows match, a sequential scan is cheaper than an index with many random reads. This is a correct decision.
- Leading wildcard: LIKE '%abc' cannot use a B-tree. Use pg_trgm (GIN or GiST) for such searches.
- Wrong column order or a missing leading column in a composite index.
- Stale or missing statistics after bulk loads: run ANALYZE. Look at estimated rows against actual rows. A big difference (10x or more) is the sign.
- Data type or collation mismatches, or OR conditions across different columns (may need UNION or separate indexes).
- A tiny table: reading the whole table is faster than using an index.
Reading EXPLAIN (ANALYZE)
- Node type (Seq Scan, Index Scan, Bitmap Heap Scan, Index Only Scan), the join type, and sort steps.
- rows=... (estimate) and actual rows=... Large gaps point to statistics problems.
- loops: a node inside a nested loop runs many times, and the time is per loop.
- Rows Removed by Filter: lots of discarded rows suggest a better index.
- Do not force the planner with settings in production. Fix the cause instead. Use enable_seqscan = off only as a test to see what the index would cost.
const { Client } = require('pg');
(async () => {
const db = new Client(); await db.connect();
await db.query(`
DROP TABLE IF EXISTS bk28_users;
CREATE TABLE bk28_users (id serial PRIMARY KEY, email text NOT NULL, active boolean NOT NULL);
INSERT INTO bk28_users (email, active)
SELECT 'User' || g || '@Example.com', g % 100 <> 0 FROM generate_series(1, 100000) g;
CREATE INDEX bk28_email ON bk28_users (email);
CREATE INDEX bk28_active ON bk28_users (active);
ANALYZE bk28_users;`);
// Walks the JSON plan and returns the scan node on the table.
const scanType = async (sql) => {
const { rows } = await db.query('EXPLAIN (FORMAT JSON) ' + sql);
const find = (node) => (node['Relation Name'] ? node['Node Type'] : (node.Plans || []).map(find).find(Boolean));
return find(rows[0]['QUERY PLAN'][0].Plan);
};
const usesIndex = (t) => /Index|Bitmap/.test(t);
const report = async (label, sql) => { const t = await scanType(sql); console.log(label.padEnd(46), t.padEnd(18), 'index used:', usesIndex(t)); };
await report('1. email = value', "SELECT * FROM bk28_users WHERE email = 'User500@Example.com'");
await report('2. lower(email) = value (function on column)', "SELECT * FROM bk28_users WHERE lower(email) = 'user500@example.com'");
await db.query('CREATE INDEX bk28_email_lower ON bk28_users (lower(email)); ANALYZE bk28_users');
await report('3. same query after an expression index', "SELECT * FROM bk28_users WHERE lower(email) = 'user500@example.com'");
await report("4. email LIKE '%500@Example.com' (leading wildcard)", "SELECT * FROM bk28_users WHERE email LIKE '%500@Example.com'");
await report('5. active = true (99 percent of rows)', 'SELECT * FROM bk28_users WHERE active = true');
await report('6. active = false (1 percent of rows)', 'SELECT * FROM bk28_users WHERE active = false');
// Estimated rows against real rows for query 6.
const { rows } = await db.query('EXPLAIN (ANALYZE, FORMAT JSON) SELECT * FROM bk28_users WHERE active = false');
const node = JSON.parse(JSON.stringify(rows[0]['QUERY PLAN'][0].Plan));
console.log('query 6 estimated rows:', node['Plan Rows'], '| actual rows:', node['Actual Rows']);
await db.query('DROP TABLE bk28_users');
await db.end();
})();Runs on the local PostgreSQL with 100,000 rows. The script prints scan types read from EXPLAIN (FORMAT JSON) and the estimate against the actual row count for one query. Index and Bitmap scans are both counted as 'index used'. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): 1. email = value Index Scan index used: true 2. lower(email) = value (function on column) Seq Scan index used: false 3. same query after an expression index Index Scan index used: true 4. email LIKE '%500@Example.com' (leading wildcard) Seq Scan index used: false 5. active = true (99 percent of rows) Seq Scan index used: false 6. active = false (1 percent of rows) Index Scan index used: true query 6 estimated rows: 957 | actual rows: 1000
Key points
- The planner chooses by estimated cost, not by index existence.
- A function on the column needs an expression index.
- Unselective filters are correctly served by sequential scans.
- Compare estimated and actual rows to spot bad statistics.
- Fix the cause rather than forcing plans.
Common mistakes
- Rewriting queries with functions on indexed columns.
- Forcing the planner with settings in production.
- Skipping ANALYZE after a bulk load.
- Reading only the top plan node.
- Adding indexes for queries that return most of the table.
Follow-ups
- What does Rows Removed by Filter tell you?
- How does pg_trgm help with LIKE '%text%'?
- What is auto_explain?
Tips
- List causes by group: shape, selectivity, statistics.
- Say 'estimated against actual rows'.
- Avoid forcing plans.