sql-serversql-server-2008-r2datalength

Find records with Minimum length data


I have a table #tempTest with data like this:

ID  Name
1   A
2   AB
3   ABC
4   ABCD
5   ABCDE
6   ABCDEF
7   X
8   QRWXYZ

Now I need the shortest name from the table.

I've tried this way:

SELECT TOP 1(name) Smallest  FROM #tempTest
GROUP BY name
ORDER BY LEN(name) 

And that represents:

Smallest
A

But what I need is:

ID  Name
1   A
7   X

Solution

  • SELECT TOP 1 WITH TIES (name) Smallest  FROM #tempTest
    GROUP BY name
    ORDER BY LEN(name)