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, LENGTH(email) - LENGTH(REPLACE(email, '.', '')) AS dots
FROM contacts ORDER BY id;| id | dots | |
|---|---|---|
| 1 | asha.rao@example.com | 2 |
| 2 | Ben@Mail.example.org | 2 |
| 3 | chen_li@example.com | 1 |
| 4 | NULL | NULL |
Removing every dot shortens the string by exactly the number of dots. The same trick counts words roughly (spaces plus one) or path depth (slashes).
For a substring longer than one character, divide:
text
(LENGTH(s) - LENGTH(REPLACE(s, 'ab', ''))) / LENGTH('ab')PostgreSQL 15+ also offers REGEXP_COUNT(s, '\.') (not run here).
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, LENGTH(email) - LENGTH(REPLACE(email, '.', '')) AS dots
FROM contacts ORDER BY id;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- LENGTH minus LENGTH after REPLACE counts occurrences
- Divide by the substring length for longer patterns
- NULL input gives NULL
- Works on every engine with basic functions
Common mistakes
- Forgetting to divide for multi-character patterns
- Using LIKE, which only says whether a match exists
Follow-ups
- How would you count words in a sentence?
- How would you find emails with more than one '@'?
Tips
- Explain why the subtraction works