citext Case Insensitive Equality
The citext extension compares through lower(), so duplicates collapse case-free and PRIMARY KEY uniqueness ignores case without a functional index.
Code
CREATE EXTENSION IF NOT EXISTS citext;
CREATE TABLE subscribers (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email citext UNIQUE NOT NULL
);
INSERT INTO subscribers (email) VALUES ('[email protected]');
-- citext 比较前先 lower:'[email protected]' 与已存行判等,被 UNIQUE 拒绝
-- INSERT INTO subscribers (email) VALUES ('[email protected]');
SELECT email = '[email protected]' AS matches
FROM subscribers WHERE id = 1;
-- DISTINCT / GROUP BY 同理:仅大小写不同的值合并成一组
WITH samples(c) AS (
VALUES ('Foo'::citext), ('foo'), ('FOO'), ('bar')
)
SELECT c, count(*) FROM samples GROUP BY c ORDER BY c;
-- 需要区分大小写的匹配时显式转回 text(或用 COLLATE "C")
SELECT email::text = '[email protected]' AS text_compare
FROM subscribers WHERE id = 1;How the snippet works
What runs here is SELECT / INSERT / CREATE — subscribers and samples are the objects involved.
Mechanically, the statements are built from: a CTE (WITH … AS) that names an intermediate result before the main query; a WHERE clause that keeps only the rows a statement is meant to touch; COUNT aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; UNIQUE constraints that keep duplicate values out; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.
Applying it
The subscribers table is the working surface here.
Statements that matter
WITH samples(c) AS (
VALUES ('Foo'::citext), ('foo'), ('FOO'), ('bar')
)
SELECT c, count(*) FROM samples GROUP BY c ORDER BY c;
SELECT email::text = '[email protected]' AS text_compare
FROM subscribers WHERE id = 1;
SELECT email = '[email protected]' AS matches
FROM subscribers WHERE id = 1;
Interactive Tools for This Topic
FAQ
- Which tables or CTEs does it reference?
- `subscribers`, `samples` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.