views:

127

answers:

6

Hi, Does anybody know if there is a way to find what the length of the longest row in a column in Oracle?

Basically I need to get the length of the longest row and then use that length plus 1 with SUBSTR to make the output of the column one character longer than the longest string.

Thanks

EDIT:

Thanks for the advice.

However, the MAX(LENGTH(column_name)) AS MAXLENGTH approach gives me the number I want but when I try to use it with SUBSTR(column_name,1, MAXLENGTH) I get an invalid identifier error.

SO I made a function to return the numberI wanted then used: SUBSTR(column_name,1,maxlengthfunc)

This gave me the following output:

SUBSTR(NAME,1,MAXLENGTHFUNC)

Rather than:

SUBSTR(NAME, 1, 19)

And it didn't shrink the output column size like I needed.

Also RTRIM(name)||' ' didn't do anything for me in SQL developer.

Thanks.

A: 
select max(length(MyColumn)) as MaxLength
from MyTable
RedFilter
+1  A: 

This should do what you want:

select max(length(MyColumn)) from MyTable;

Depending on what you are trying to achieve, you may also be insterested to know that you can output the data in the column plus exactly one space like this:

select rtrim(MyColumn)||' ' from MyTable;
Colin Pickard
+1  A: 

This will work with VARCHAR2 columns.

select max(length(your_col))
from your_table
/

CHAR columns are obviously all the same length. If the column is a CLOB you will need to use DBMS_LOB.GETLENGTH(). If it's a LONG it's really tricky.

APC
A: 

select max(LENGTH(column_name)) from table_name.

Visage
A: 

To make the maxlength useable you may want to get it from a imbedded select

select <do something with maxlength here> 
from
(select x.*, 
( select max(length(yourcolumn)) from yourtable) as maxlength 
from yourtable x)
Jürgen Hollfelder
+1  A: 

w/o function:

select 
  rpad(tbl.column_name, length_info.max_length+1, ' ') as target_string
from 
  table_name tbl,
  (
    select max(length(column_name)) max_length 
    from my_table
  ) 
    length_info

with your function:

select 
  rpad(tbl.column_name, MaxLengthFunc + 1, ' ') as target_string
from 
  my_table tbl

declare your function as determinictic for better performance:

create or replace function MaxLengthFunc 
return number  
deterministic
as
  vMaxLen number;
begin

  select max(length(column_name)) 
  into vMaxLen
  from table_name;

  return vMaxLen;

end;
ThinkJet