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.

SqlData Fetching

Code

snippet
-- 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

FAQ

Which tables does the SQL touch?
`users` — referenced directly, no join needed.