← Back to SQL, page 8

sql-0150 · Medium mid

How do you count how many times a character appears in a string, such as dots in an email address?

Subtract the length after removing the character from the original length: LENGTH(email) - LENGTH(REPLACE(email, '.', '')). For a multi-character substring, divide the difference by the substring's length.

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;
idemaildots
1asha.rao@example.com2
2Ben@Mail.example.org2
3chen_li@example.com1
4NULLNULL

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