Strpos Left Right Substring Split

Locate a delimiter with strpos, slice from either end with left and right, and guard the not-found case because left(x, -1) silently trims the tail.

SqlData Integrity

Code

snippet
CREATE TABLE contacts (
    id    int PRIMARY KEY,
    email text NOT NULL
);

INSERT INTO contacts VALUES
    (1, '[email protected]'),
    (2, '[email protected]'),
    (3, 'no-at-sign.example.com');

SELECT
    id,
    -- strpos:1 起始位置;找不到返回 0
    strpos(email, '@') AS at_pos,
    -- left/right:从两端各取固定长度
    left(email, 3)  AS head,
    right(email, 4) AS tail,
    -- 与 strpos 组合 split;没有 @ 时用 CASE 兜底,避免 left(x, -1) 的负数语义
    CASE WHEN strpos(email, '@') > 0
         THEN left(email, strpos(email, '@') - 1)
         ELSE email END AS local_part,
    CASE WHEN strpos(email, '@') > 0
         THEN substring(email FROM strpos(email, '@') + 1)
         ELSE NULL END AS domain
FROM contacts
ORDER BY id;

What the code does

SELECT / INSERT / CREATE statements share the script, touching contacts and strpos.

Breaking the statements into their working parts: an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Applying it

Run the statement against the contacts table.

Statements that matter

INSERT INTO contacts VALUES
    (1, '[email protected]'),
    (2, '[email protected]'),
    (3, 'no-at-sign.example.com');
CREATE TABLE contacts (
    id    int PRIMARY KEY,
    email text NOT NULL
);

Interactive Tools for This Topic

FAQ

What relations does the SQL touch?
`contacts`, `strpos`.