Skip to content

Instantly share code, notes, and snippets.

@0x49D1
Created September 11, 2019 06:29
Show Gist options
  • Save 0x49D1/61cac505dc8b47a67bafa993efd232d7 to your computer and use it in GitHub Desktop.
Save 0x49D1/61cac505dc8b47a67bafa993efd232d7 to your computer and use it in GitHub Desktop.
MySQL number of times string contains another string (count char appearance)
CREATE FUNCTION COUNT_STR(haystack TEXT, needle VARCHAR(32))
RETURNS INTEGER DETERMINISTIC
BEGIN
RETURN ROUND((CHAR_LENGTH(haystack) - CHAR_LENGTH(REPLACE(haystack, needle, ""))) / CHAR_LENGTH(needle));
END;
# Example: SELECT COUNT_STR('{"a":"test","fdfs":"test","more":"tests","b":"a"}',',"'); returns 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment