Milo LaMar Milo LaMar - 5 months ago 9
SQL Question

Retrieve the maximum length of a VARCHAR column in SQL Server

I want to find the longest

VARCHAR
in a specific column of a SQL Server table.

Here's an example:

ID = INT IDENTITY
DESC = VARCHAR(5000)

ID | Desc
---|-----
1 | a
2 | aaa
3 | aa


What's the SQL to return 3? Since the longest value is 3 characters?

Answer

use the build-in functions for length and max on the description column:

select max(len(Desc)) from table_name

Note that if youre table is very big, then there can be some performance issues :)