Example 1
Find the position of @ in each email address
The @ in [email protected] is at position 6 (a=1, l=2, i=3, c=4, e=5, @=6). In [email protected] it is at position 4. In [email protected] it is at position 8. The key difference between engines is argument order: INSTR and STRPOS take (string, pattern) while SQL Server's CHARINDEX takes (pattern, string). A return value of 0 means the substring was not found.
CREATE TABLE contacts (id INT, email VARCHAR(100));
INSERT INTO
contacts (id, email)
VALUES
(1, '[email protected]'),
(2, '[email protected]'),
(3, '[email protected]');SELECT
email,
INSTR (email, '@') AS at_position
FROM
contacts
ORDER BY
id;| at_position | |
|---|---|
| [email protected] | 6 |
| [email protected] | 4 |
| [email protected] | 8 |
CREATE TABLE contacts (id INT, email VARCHAR(100));
INSERT INTO
contacts (id, email)
VALUES
(1, '[email protected]'),
(2, '[email protected]'),
(3, '[email protected]');SELECT
email,
CHARINDEX ('@', email) AS at_position
FROM
contacts
ORDER BY
id;| at_position | |
|---|---|
| [email protected] | 6 |
| [email protected] | 4 |
| [email protected] | 8 |
CREATE TABLE contacts (id INT, email VARCHAR(100));
INSERT INTO
contacts (id, email)
VALUES
(1, '[email protected]'),
(2, '[email protected]'),
(3, '[email protected]');SELECT
email,
STRPOS (email, '@') AS at_position
FROM
contacts
ORDER BY
id;| at_position | |
|---|---|
| [email protected] | 6 |
| [email protected] | 4 |
| [email protected] | 8 |
MySQL/MariaDB/SQLite use INSTR(string, substr). PostgreSQL uses STRPOS(string, substr). SQL Server uses CHARINDEX(substr, string) — argument order is reversed. All return the same 1-based positions.