Count how many times a substring appears in SQL
How many times does 'error' appear in each log line? The length difference after deleting it tells you.
The task
Count occurrences of a word or token by measuring how much shorter the string gets when the token is deleted.
The snippet
Written for PostgreSQL. Versions for SQL Server are under Variations.
SELECT (length(message) - length(replace(lower(message), 'error', ''))) / length('error') AS error_count
FROM log_lines;
仕組み
replace deletes every occurrence, and the character count lost divided by the length of the search term is exactly the number of hits. Dividing by length('error') instead of writing 5 keeps the intent obvious. The count includes occurrences inside words like 'errors'; the FAQ covers that.
Variations
SQL Server
SQL ServerSELECT (LEN(message) - LEN(REPLACE(LOWER(message), 'error', ''))) / LEN('error') AS error_count
FROM log_lines;
Questions that come up
Does this count words or substrings?
Substrings: 'errors' contains 'error', so it counts. For whole words, pad the search with spaces (replace ' error ') after normalizing whitespace, or use regexp_count with a word-boundary pattern on PostgreSQL 15+ ('\yerror\y') or Oracle REGEXP_COUNT ('(^|\W)error(\W|$)'). On SQL Server, LEN ignores trailing spaces, so use DATALENGTH when the term can end in a space.
Keep reading
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.