Expression Index On lower(email)
Index the lower(email) expression and repeat that exact expression in the query; comparing the raw column falls back to a sequential scan.
Code
-- Expression index:索引建在表达式上,查询必须重复同一表达式才能命中
CREATE UNIQUE INDEX idx_users_email_lower ON users (lower(email));
-- 命中:谓词写法与索引表达式一致,可走索引扫描
SELECT id, email FROM users WHERE lower(email) = '[email protected]';
-- 不命中:比较的是原始列,规划器退回顺序扫描
SELECT id, email FROM users WHERE email = '[email protected]';
-- EXPLAIN 里看真实路径:上面两条的 Plan 分别是 Index Scan 与 Seq Scan
EXPLAIN SELECT id FROM users WHERE lower(email) = '[email protected]';
-- 大小写变体无法再注册:[email protected] 与 [email protected] 同键
INSERT INTO users (email) VALUES ('[email protected]');
-- INSERT INTO users (email) VALUES ('[email protected]'); -- 唯一冲突Inside the snippet
Several statements share this file — SELECT / INSERT / CREATE / EXPLAIN, with users among the objects involved.
Breaking the statements into their working parts: a WHERE clause narrowing which rows one statement affects; UNIQUE constraints that keep duplicate values out.
Putting it to use
Run the statement against the users table.
Core lines
EXPLAIN SELECT id FROM users WHERE lower(email) = '[email protected]';
SELECT id, email FROM users WHERE lower(email) = '[email protected]';
SELECT id, email FROM users WHERE email = '[email protected]';
Interactive Tools for This Topic
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Cron Expression ExplainerParse a five-field cron expression and get a field-by-field plain-English explanation plus a one-line human-readable schedule summary.Email Address ValidatorValidate email syntax, checking the local part, domain labels, and top-level domain against common rules.
FAQ
- Which tables does the SQL touch?
- `users` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.