Unicode NORMALIZE And IS NORMALIZED Checks

Compare canonically equivalent NFC and NFD Unicode strings with normalize() and enforce IS NFC NORMALIZED inside PostgreSQL CHECK constraints.

SqlData Integrity

Code

snippet
CREATE TEMP TABLE user_handles (
    id     integer PRIMARY KEY,
    handle text NOT NULL CHECK (handle IS NFC NORMALIZED)
);

-- Precomposed NFC (4 code points) vs decomposed NFD (e + U+0301, 5 code points)
SELECT
    E'caf\u00e9' = E'cafe\u0301' AS raw_bytes_equal,
    E'caf\u00e9' IS NFC NORMALIZED AS nfc_is_nfc,
    E'cafe\u0301' IS NFC NORMALIZED AS nfd_is_nfc,
    E'cafe\u0301' IS NFD NORMALIZED AS nfd_is_nfd,
    normalize(E'cafe\u0301', NFC) = E'caf\u00e9' AS normalized_equal,
    normalize(E'\ufb01le', NFKC) AS compat_folded;

INSERT INTO user_handles VALUES (1, normalize(E'cafe\u0301', NFC));

DO $$
BEGIN
    INSERT INTO user_handles VALUES (2, E'cafe\u0301');
EXCEPTION
    WHEN check_violation THEN
        RAISE NOTICE 'unnormalized NFD handle rejected by CHECK';
END $$;

SELECT id, handle FROM user_handles;

Execution path — Unicode NORMALIZE And IS NORMALIZED Checks

SELECT / INSERT / CREATE statements share the script, touching user_handles.

user_handles creates throwaway temporary storage bound to the active session right here so nothing has to exist ahead of time and state drops on disconnect.

In terms of clauses, the statements use: a CHECK constraint that rejects out-of-domain values at write time; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Applying it

The file brings its own tables (user_handles) — session-local, created on the fly — so execute it whole against a database you can throw away.

Statements that matter

DO $$
BEGIN
    INSERT INTO user_handles VALUES (2, E'cafe\u0301');
EXCEPTION
    WHEN check_violation THEN
        RAISE NOTICE 'unnormalized NFD handle rejected by CHECK';
END $$;
CREATE TEMP TABLE user_handles (
    id     integer PRIMARY KEY,
    handle text NOT NULL CHECK (handle IS NFC NORMALIZED)
);
INSERT INTO user_handles VALUES (1, normalize(E'cafe\u0301', NFC));

Interactive Tools for This Topic

FAQ

What are the relations in play here?
`user_handles` — referenced directly, no join needed.