Find records with Minimum length data

135 Views Asked by At

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
2

There are 2 best solutions below

1
Shariful_Islam On BEST ANSWER
SELECT TOP 1 WITH TIES (name) Smallest  FROM #tempTest
GROUP BY name
ORDER BY LEN(name) 
0
David M On
SELECT id, name FROM #tempTest
WHERE LEN(name) = (SELECT MIN(LEN(name)) FROM #tempTest)