Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the value of max length in sql server

i would like to ask you if there is a way to get the value of maxlength of column in ms sql server.
For example in the table A we have:

id  | value
----+--------
 1  | 0123
 2  | 00034567
 3  | 547

The desired result for this data set is 00034567.

Wherever i have searched for this problem i get the answer select max(len(value)) which is not what i need, because it gives the max number of characters of the value and not the value itself.

Any ideas?

like image 227
paa Avatar asked Sep 01 '14 07:09

paa


People also ask

How do you find max length in SQL?

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.

How do you find max and min length 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.

What is the max string length in SQL?

The maximum length of an SQL statement string is 65,000 characters.

How do I find the length of a field in SQL Server?

You can use the LEN function () to find the length of a string value in SQL Server, for example, LEN (emp_name) will give you the length stored in the emp_name string.


2 Answers

SELECT TOP 1 t.value
FROM table AS t
ORDER BY LEN(t.value) DESC
like image 196
Vland Avatar answered Sep 16 '22 13:09

Vland


Sort by length and take the first row:

select top 1 value
from mytable
order by len(value) desc

If you want ties:

select value
from mytable
where len(value) = (select max(len(value)) from mytable)

Or more efficient but SQL Server specific:

select value from (
  select value,
  rank() over (order by len(value) desc) rank
  from mytable) x
where rank = 1

See SQLFiddle for last one.

like image 30
Bohemian Avatar answered Sep 20 '22 13:09

Bohemian