The Real Fullstack

The Invisible Index

The email column has an index. Why does PostgreSQL read all 4.2 million rows?

مهندس7 دقيقةمختبر الأداءمختبر تصحيح الأخطاء
postgresqlsqlexplain

لم يُترجم هذا التحدي إلى العربية بعد. أنت تقرأ النسخة الإنجليزية.

المهمة:Read the plan, explain why the existing index is ignored, and give the planner an index it can actually use.السياق · أهداف التعلّم ▾

Release 2.14 of Wrenly made login case-insensitive by wrapping both sides of the comparison in lower(). Since then every login is a full table scan and the login page takes almost two seconds under load.

المهمة: Read the plan, explain why the existing index is ignored, and give the planner an index it can actually use.

أهداف التعلّم

  • Understand that a B-tree index on a column does not cover an expression on that column.
  • Create expression indexes or store normalised values.
  • Read Seq Scan vs Index Scan in EXPLAIN output.
المحاكاةمحاكاة
login pageauth servicePostgreSQL
تشغيل المحاكاة
-- Option 1: index the expression the query actually usesCREATE INDEX CONCURRENTLY users_email_lower_idx ON users (lower(email));-- query unchanged: WHERE lower(email) = lower($1)  → Index Scan-- Option 2: store the normalised value onceALTER TABLE users ADD COLUMN email_normalized text;UPDATE users SET email_normalized = lower(email);          -- in batchesCREATE UNIQUE INDEX CONCURRENTLY ON users (email_normalized);

تبسيط

Two symptoms with deterministic fixes. Collations and citext are other valid ways to compare case-insensitively. نموذج تعليمي — الأرقام توضّح سلوكًا وليست قياسات أداء.

المفاهيم

مفيد قبل هذا التحدي

تحديات ذات صلة

المراجع