// strings reference

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.

카테고리
Strings
Returns
integer
In this category
76 of 172

구문

LEN(s) - LEN(REPLACE(s, needle, ''))

엔진 지원

엔진Support메모
SQL Server 예 Supported under this name.
PostgreSQL 예 Supported under this name.
MySQL 예 Supported under this name.
SQLite 예 Supported under this name.
Oracle 예 Supported under this name.

예시

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;

알아 두면 좋은 정보

  • 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.

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// fewer lookups

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.