How do I determine the length of a string with SQL?

It’s quite simple if you’re using MySQL or PostgreSQL – the function you need in both is simply – length()

There are a couple of points you’d better keep in mind if you’re using SQL Server, however.

1. The function in that environment is called len()

2. Unlike length in the other two database systems, len() excludes trailing blanks when counting the characters in a string. If you want them included, you need to use datalength()

---------------SQL Server---------------------------------------
select
'I love you' as phrase,
len('I love you') as phrase_length,
len(' I love you ') as phrase_length2,
datalength(' I love you ') as phrase_length3
phrase |phrase_length |phrase_length2 |phrase_length3 |
-----------|--------------|---------------|---------------|
I love you |10 |11 |12 |
--------------MySQL----------------------------------------------
select
'I love you' as phrase,
length('I love you') as phrase_length
phrase |phrase_length |
-----------|--------------|
I love you |10 |
--------------PostgreSQL-----------------------------------------
select
'I love you' as phrase,
length('I love you') as phrase_length
phrase |phrase_length
-----------|--------------
I love you |10
view raw SQL_length.sql hosted with ❤ by GitHub

Happy SQL-ing!