alternate solution for this union query

aslam 21 Reputation points
2021-03-18T18:19:14.277+00:00

Consider below case.
One table multiple columns like below .
Table name test .
Create table test ( sn int, name nvarchar(50), sname nvarchar(50), lname nvarchar(50) )
Insert into test Values(1,'aa','bb','cc') ,Values(1,'dd','ee','ff') ,Values(1,'gg','hh','ii') ,Values(2,'jj','kk','ll')

Expected result --all names
query --
Select name from test where sn = 1 union
select sname from test where sn = 1 union
select lname from test where sn = 1

Note:- I have tried UNION ALL as well . not much improvement .

Considering performance issue can we get an alternate solution to this situation in tsql?

Developer technologies | Transact-SQL
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2021-03-18T19:18:18.327+00:00

    Check the performance of this alternative:

    select names
    from 
    (
        select name, sname, lname from test where sn = 1 
    ) t
    unpivot
    (
        names for col in ( name, sname, lname )
    ) u
    

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.