Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 896
Milo LaMar Avatar asked Mar 06 '12 21:03

Milo LaMar


People also ask

How do I find the length of a VARCHAR Max in SQL?

varchar [ ( n | max ) ] Variable-size string data. Use n to define the string size in bytes and can be a value from 1 through 8,000 or use max to indicate a column constraint size up to a maximum storage of 2^31-1 bytes (2 GB).

What is the maximum length of VARCHAR column?

The size of the maximum size (m) parameter of a VARCHAR column can range from 1 to 255 bytes. If you are placing an index on a VARCHAR column, the maximum size is 254 bytes. You can store character strings that are shorter, but not longer, than the m value that you specify.

How do I find the length of a VARCHAR?

The length of a varchar column can be determined using the len() function, however this generates an error when used with the text datatype. Fortunately we can use the datalength() function to work out the length of a text field.

How do I find the maximum and minimum length of a column in SQL?

SQL Server databases use LEN or DATALENGTH to find field width. It also has its own function to find the maximum length of a column – COL_LENGTH. SELECT MIN(LENGTH(<column_name>)) AS MinColumnLength FROM Table; If we include any non-aggregate functions into our query then we need a GROUP BY clause.


2 Answers

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.

like image 176
aweis Avatar answered Sep 28 '22 07:09

aweis


For MySQL, it's LENGTH, not LEN:

SELECT MAX(LENGTH(Desc)) FROM table_name 
like image 26
Abhishek Goel Avatar answered Sep 28 '22 08:09

Abhishek Goel