title: Select Longest String - SQL Server
body: <p>I have a need to select the longest string in a SQL Server Query.</p>
  
  <p>I need, the longest description from LongDescription_c when there is something in it or the longest from PartDescription.</p>
  
  <p>At the moment, we have the following query created by a colleague a long time ago:</p>
  
  <pre><code>SELECT        PartNum, 
                MAX(CASE WHEN LongDescription_c = '' THEN PartDescription ELSE LongDescription_c END) AS PartDesc
  FROM            
                Part
  GROUP BY 
                PartNum
  </code></pre>
  
  <p>This works in a lot of circumstances but not all and I believe the reason for this is the <code>MAX()</code>. As i believe this returns in alphabetical order rather then <code>MAX(LEN())</code> which is what I believe he wanted. However, I cannot work out how to use <code>MAX(LEN())</code> as this will purely return the maximum length as an integer.</p>
  
  <p>Thanks for any help in advance as Im a bit stuck at this point.</p>
  
  <p>Thanks :)</p>