Full answer
sql
CREATE TABLE contacts (
id INTEGER PRIMARY KEY,
first TEXT,
last TEXT,
email TEXT,
phone TEXT
);
INSERT INTO contacts VALUES
(1,'Asha','Rao','asha.rao@example.com','+91 98450-12345'),
(2,'ben',NULL,'Ben@Mail.example.org','(020) 7946 0018'),
(3,' Chen ','Li','chen_li@example.com','020-7946-0019'),
(4,'Dara','Okafor',NULL,'12345');sql
SELECT id, email, LOWER(SUBSTR(email, INSTR(email, '@') + 1)) AS domain
FROM contacts ORDER BY id;| id | domain | |
|---|---|---|
| 1 | asha.rao@example.com | example.com |
| 2 | Ben@Mail.example.org | mail.example.org |
| 3 | chen_li@example.com | example.com |
| 4 | NULL | NULL |
INSTR returns the 1-based position of the first @, and SUBSTR with no length takes the rest of the string. Dara's NULL email gives NULL, which is correct.
PostgreSQL's SPLIT_PART reads more clearly:
sql
SELECT id, LOWER(SPLIT_PART(email, '@', 2)) AS domain FROM contacts ORDER BY id;| id | domain |
|---|---|
| 1 | example.com |
| 2 | mail.example.org |
| 3 | example.com |
| 4 | NULL |
Counting domains is then a GROUP BY on the expression. For heavy reporting, store the domain in its own column (or a generated column) rather than parsing on every query.
sql
CREATE TABLE contacts (
id INTEGER PRIMARY KEY,
first TEXT,
last TEXT,
email TEXT,
phone TEXT
);
INSERT INTO contacts VALUES
(1,'Asha','Rao','asha.rao@example.com','+91 98450-12345'),
(2,'ben',NULL,'Ben@Mail.example.org','(020) 7946 0018'),
(3,' Chen ','Li','chen_li@example.com','020-7946-0019'),
(4,'Dara','Okafor',NULL,'12345');
SELECT id, email, LOWER(SUBSTR(email, INSTR(email, '@') + 1)) AS domain
FROM contacts ORDER BY id;Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.
Key points
- INSTR finds the '@' position (1-based)
- SUBSTR(s, start) takes the rest of the string
- PostgreSQL has SPLIT_PART
- Lowercase domains before grouping
Common mistakes
- Off-by-one errors when skipping the '@'
- Grouping 'Mail.example.org' and 'mail.example.org' as different domains
Follow-ups
- How would you extract the part before the '@'?
- How would you count contacts per domain?
Tips
- Handle NULL and case in the answer