SQL count occurrences of a substring
Outside Oracle's REGEXP_COUNT and PostgreSQL 15's regexp_count, there is no substring counter; the standard trick measures the length lost when the needle is removed.
- Categoría
- Strings
- Returns
integer- In this category
- 76 of 172
Sintaxis
LEN(s) - LEN(REPLACE(s, needle, ''))
Soporte del motor
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Sí | Supported under this name. |
| PostgreSQL | Sí | Supported under this name. |
| MySQL | Sí | Supported under this name. |
| SQLite | Sí | Supported under this name. |
| Oracle | Sí | Supported under this name. |
Ejemplos
SQL Server
SELECT LEN(note) - LEN(REPLACE(note, ',', '')) AS commas FROM notes;
PostgreSQL
SELECT length(note) - length(replace(note, ',', '')) AS commas FROM notes;
Oracle
SELECT (LENGTH(note) - LENGTH(REPLACE(note, ',', ''))) AS commas FROM notes;
Conviene saberlo
- The trick: removing the needle shortens the string by count x needle-length. For single characters no division is needed; for longer needles divide by LENGTH(needle).
- Counts are non-overlapping by construction: REPLACE removes left to right, so 'aaa' counts one 'aa', not two.
- Case sensitivity follows REPLACE: SQL Server's default case-insensitive collations count 'A' and 'a' alike, while MySQL's REPLACE matches exact case even under a _ci collation, as do PostgreSQL, SQLite and Oracle.
- NULL poisons the math: a NULL column yields NULL, so wrap with COALESCE(s, '') when blanks should count as zero.
Questions about Counting substring occurrences
How do I count occurrences of a multi-character needle?
Divide the length difference by the needle's length: (LEN(s) - LEN(REPLACE(s, 'ab', ''))) / 2 counts 'ab' pairs.
Does this count overlapping matches?
No. REPLACE consumes left to right, so 'aaaa' with needle 'aa' counts 2. Overlap counting needs a recursive or regex-based approach.
Is there a COUNT function for substrings?
Oracle has REGEXP_COUNT(s, pattern) and PostgreSQL 15+ has regexp_count(); both take a regex, so escape special characters in the needle. Elsewhere the length-minus-replace trick is the idiom.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.