MySQL: Count number of occurrences of a substring
31 August 2025 (Updated 31 August 2025)
Suppose you have a tweets
table like this:
+----------+-----------------------------------------------------------------------------------+
| tweet_id | content |
+----------+-----------------------------------------------------------------------------------+
| 1 | Traveling, exploring, and living my best life @JaneSmith @SaraJohnson @LisaTaylor |
| | @MikeBrown #Foodie #Fitness #Learning |
| 2 | Just had the best dinner with friends! #Foodie #Friends #Fun |
| 4 | Working hard on my new project #Work #Goals #Productivity #Fun |
+----------+-----------------------------------------------------------------------------------+
And you want to find the number of hashtags (#
) and mentions (@
) in the content
column. You can do so like this:
SELECT
*,
LENGTH(REGEXP_REPLACE(content, '[^@]', '')) AS num_mentions,
LENGTH(REGEXP_REPLACE(content, '[^#]', '')) AS num_hashtags
FROM tweets
ORDER BY tweet_id
Tagged:
SQL recipes