// SQL snippet

Extract the domain from an email address in SQL

Grouping signups by email domain (gmail.com vs corporate) is a common segmentation need.

Main statement
PostgreSQL
还支持
SQL Server MySQL

The task

The domain is whatever follows the @. split_part returns that piece directly and handles missing @ gracefully.

The snippet

Written for PostgreSQL. Versions for SQL Server and MySQL are under Variations.

PostgreSQL
SELECT lower(split_part(email, '@', 2)) AS email_domain,
       count(*) AS signups
FROM users
GROUP BY 1
ORDER BY signups DESC;

工作原理

split_part(text, '@', 2) returns the text after the first @, or an empty string when there is none, so malformed rows group under '' rather than erroring. Lowercasing first keeps Gmail.com and gmail.com in one bucket.

Variations

SQL Server

SQL Server
SELECT RIGHT(email, CHARINDEX('@', REVERSE(email) + '@') - 1) AS email_domain,
       COUNT(*) AS signups
FROM users
GROUP BY RIGHT(email, CHARINDEX('@', REVERSE(email) + '@') - 1);

MySQL

MySQL
SELECT LOWER(SUBSTRING_INDEX(email, '@', -1)) AS email_domain,
       COUNT(*) AS signups
FROM users
GROUP BY email_domain;

Questions that come up

What about addresses with quotes or multiple @?

Quoted local parts technically may contain @ (rare and legal in RFC 5321). split_part and SUBSTRING_INDEX split on the first or last @ depending on the index argument; the SQL Server variant uses the last @ and returns the whole value when there is no @ at all. For a real system, validate addresses on input instead of parsing defensively in every query.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.