← Back to SQL, page 8

sql-0142 · Easy fresher

Write a query that extracts the domain part of each email address.

Find the position of '@' and take everything after it: SUBSTR(email, INSTR(email, '@') + 1) in SQLite. PostgreSQL has SPLIT_PART(email, '@', 2) and POSITION('@' IN email). Lowercase the result, because domains are case-insensitive.

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;
idemaildomain
1asha.rao@example.comexample.com
2Ben@Mail.example.orgmail.example.org
3chen_li@example.comexample.com
4NULLNULL

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;
iddomain
1example.com
2mail.example.org
3example.com
4NULL

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