Retrieve the maximum length of a VARCHAR column in SQL Server

Milo LaMar picture Milo LaMar · Mar 6, 2012 · Viewed 276.1k times · Source

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

aweis picture aweis · Mar 6, 2012

Use the built-in functions for length and max on the description column:

SELECT MAX(LEN(DESC)) FROM table_name;

Note that if your table is very large, there can be performance issues.