Counting Blank Spaces

The LEN() function will ignore trailing blanks, to count blank spaces, use the DATALENGTH() function instead.

Brian Moran

July 23, 2003

1 Min Read
ITPro Today logo in a gray background | ITPro Today

Why does the command SELECT LEN('123' + ' '), which counts the number of characters in a field, return three when it should return eight? Three characters plus five blank spaces is eight characters in total. How can I count the blank spaces?

When in doubt about unexpected behavior, read SQL Server Books Online (BOL). The BOL entry for the LEN() function says that it ignores trailing blanks. Many people make the mistake of assuming the LEN() function will count trailing blanks because similar functions in other programming languages do. To get the answer you're looking for, use the DATALENGTH() function instead:

SELECT DATALENGTH('123' + '    ')

Learn more from "Trimming Blanks" and "Practicing Data Porting."

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like