I have a column from which I would like to retreive only those values which are only consecutive identical characters like ‘ppp’ ‘mmmm’, ‘ddddd’. The length of the string will be greater than or equals to 3
I tried different queries but somehow it’s not giving me the output
2
Answers
One alternative uses a recursive query to split each string to individual characters, then aggregates and filters on the count of distinct characters.
Assuming that your table has a structure like
mytable(id, str)
:Note that recursive queries are supported in version 8.0 only.
You can apply some tricks. Begin by using the
LEFT
string function to extract the first character. Then, replace occurrences of that character with an empty value using either theTRIM
,REPLACE
, orTRANSLATE
functions. Verify that the resulting string is empty. Finally, validate the length of the string using theLENGTH
(orLEN
) function. Consider the following SQL query, which incorporates these techniques:I have tested the idea with MySQL, and it worked as expected:
Additionally, if your SQL engine supports regex and capturing groups, you can implement it using patterns such as
(.)1{2,}
. Even if capturing groups is not supported, you can still combine theLEFT
function with regex patterns to achieve the desired result.