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.
Code
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
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.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What relations does the SQL touch?
- `contacts`, `strpos`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.