Is there MS SQL Server function that counts the number of times a particular character appears in a string?
-
This might help http://social.msdn.microsoft.com/Forums/en/transactsql/thread/6bd2da08-af9e-4216-bec3-1e859415d800 – Chetter Hummin Mar 20 '12 at 14:59
-
1Try the following similar SO question [link](http://stackoverflow.com/questions/1144172/how-to-count-the-number-of-times-a-character-appears-in-a-sql-column) – Barry Kaye Mar 20 '12 at 15:00
-
Duplicate of SO [How do you count the number of occurrences of a certain substring in a SQL varchar?](http://stackoverflow.com/questions/738282/how-do-you-count-the-number-of-occurrences-of-a-certain-substring-in-a-sql-varch) which is older and has more answers. – Peter Mar 28 '17 at 11:12
-
Does this answer your question? [How to count instances of character in SQL Column](https://stackoverflow.com/questions/1860457/how-to-count-instances-of-character-in-sql-column) – starball Jul 26 '23 at 04:00
9 Answers
There's no direct function for this, but you can do it with a replace:
declare @myvar varchar(20)
set @myvar = 'Hello World'
select len(@myvar) - len(replace(@myvar,'o',''))
Basically this tells you how many chars were removed, and therefore how many instances of it there were.
Extra:
The above can be extended to count the occurences of a multi-char string by dividing by the length of the string being searched for. For example:
declare @myvar varchar(max), @tocount varchar(20)
set @myvar = 'Hello World, Hello World'
set @tocount = 'lo'
select (len(@myvar) - len(replace(@myvar,@tocount,''))) / LEN(@tocount)

- 40,401
- 11
- 97
- 129
-
2Maybe using DATALENGTH instead LEN would be better, because LEN returns the size of the the string trimmed. – rodrigocl Nov 03 '15 at 17:25
-
4Using DATALENGTH needs care, as it returns the size of data used to store the variable. For a varchar this is ok as the number of bytes to store the data is equal to the length of the string. However nvarchar uses 2 bytes for each character, so DATALENGTH would double the length reported. There are other factors that may also affect DATALENGTH. See [msdn](https://learn.microsoft.com/en-us/sql/t-sql/functions/datalength-transact-sql?view=sql-server-2017) – Jon Egerton Apr 26 '18 at 08:21
-
Be advised the code solution for multi-char strings returns +1 when the sought after characters are at the end of the string. For example: set @myvar = 'lo Hello World, Hello World, lo lo' returns 6 instead of 5. – Langston Aug 03 '20 at 20:48
-
1
-
To clarify on the comment left by @Langston - this solution fails if replacing the final copy of the search pattern text results in trailing spaces. LEN ignores trailing spaces, so it may calculate the difference in characters incorrectly. The answer is fine otherwise, but needs this caveat to be added (as do most of the duplicated answers below). – mathewb Aug 26 '21 at 02:24
Look at the length of the string after replacing the sequence
declare @s varchar(10) = 'aabaacaa'
select len(@s) - len(replace(@s, 'a', ''))
>>6

- 171,639
- 30
- 264
- 288
You can do that using replace
and len
.
Count number of x
characters in str
:
len(str) - len(replace(str, 'x', ''))

- 687,336
- 108
- 737
- 1,005
Use this function begining from SQL SERVER 2016
Select Count(value) From STRING_SPLIT('AAA AAA AAA',' ');
-- Output : 3
When This function used with count function it gives you how many character exists in string

- 559
- 6
- 10
-
That is not answering the question. What the string_split() function is doing is counting the number of words separated by a space ' '. It does not count the number of characters in the string. `Select Count(value) From STRING_SPLIT('A AA AAA',' ');` also gives an answer of 3. – Zorkolot Mar 03 '23 at 17:01
-
If SQL server compatibility allows that, then this is the best answer. E.g. Select Count(value)-1 From STRING_SPLIT('Hello World','l') counts the number of letter "l" in the Text. – Carsten Sep 01 '23 at 12:49
try that :
declare @t nvarchar(max)
set @t='aaaa'
select len(@t)-len(replace(@t,'a',''))

- 144,742
- 138
- 468
- 792
You can do it inline, but you have to be careful with spaces in the column data. Better to use datalength()
SELECT
ColName,
DATALENGTH(ColName) -
DATALENGTH(REPLACE(Col, 'A', '')) AS NumberOfLetterA
FROM ColName;
-OR- Do the replace with 2 characters
SELECT
ColName,
-LEN(ColName)
+LEN(REPLACE(Col, 'A', '><')) AS NumberOfLetterA
FROM ColName;

- 31
- 1
It will count occurrences of a specific character
DECLARE @char NVARCHAR(50);
DECLARE @counter INT = 0;
DECLARE @i INT = 1;
DECLARE @search NVARCHAR(10) = 'o'
SET @char = N'Hello World';
WHILE @i <= LEN(@char)
BEGIN
IF SUBSTRING(@char, @i, 1) = @search
SET @counter += 1;
SET @i += 1;
END;
SELECT @counter;

- 81
- 6
function for sql server:
CREATE function NTSGetCinC(@Cadena nvarchar(4000), @UnChar nvarchar(100))
Returns int
as
begin
declare @t1 int
declare @t2 int
declare @t3 int
set @t1 = len(@Cadena)
set @t2 = len(replace(@Cadena,@UnChar,''))
set @t3 = len(@UnChar)
return (@t1 - @t2) / @t3
end
Code for visual basic and others:
Public Function NTSCuentaChars(Texto As String, CharAContar As String) As Long
NTSCuentaChars = (Len(Texto) - Len(Replace(Texto, CharAContar, ""))) / Len(CharAContar)
End Function

- 989
- 1
- 8
- 9
Use this code, it is working perfectly. I have create a sql function that accept two parameters, the first param is the long string that we want to search into it,and it can accept string length up to 1500 character(of course you can extend it or even change it to text datatype). And the second parameter is the substring that we want to calculate the number of its occurance(its length is up to 200 character, of course you can change it to what your need). and the output is an integer, represent the number of frequency.....enjoy it.
CREATE FUNCTION [dbo].[GetSubstringCount]
(
@InputString nvarchar(1500),
@SubString NVARCHAR(200)
)
RETURNS int
AS
BEGIN
declare @K int , @StrLen int , @Count int , @SubStrLen int
set @SubStrLen = (select len(@SubString))
set @Count = 0
Set @k = 1
set @StrLen =(select len(@InputString))
While @K <= @StrLen
Begin
if ((select substring(@InputString, @K, @SubStrLen)) = @SubString)
begin
if ((select CHARINDEX(@SubString ,@InputString)) > 0)
begin
set @Count = @Count +1
end
end
Set @K=@k+1
end
return @Count
end

- 31
- 3