Sql-server – How to tune the below query

performancesql serversql-server-2008-r2

I am currently working on below table structure to pull the data/ generate any one time report.

Table ABC:

ID  Field       Value
1   Name        Nagarjuna
1   Gender      Male
1   Industry    Actor
2   Name        Sachin RT
2   Gender      Male
2   Industry    Sports
3   Name        Theresa
3   Gender      Female
3   Industry    Social Worker
4   Name        Saha
4   Gender      Female
4   Industry    Software Engineer
5   Name        Swe
5   Gender      Female
5   Industry    Doctor

In order to get the report in the format Name,gender,industry values, I am writing the below query

Select  
  vname.Value, vgender.value, vindustry.value 
from ABC [vname] with (nolock)   
join ABC [vgender] with (nolock)
  on vname.id = vgender.id  
join ABC [vindustry] with (nolock)
  on vgender.id = vindustry.id

where vname.field = 'Name' 
  and vgender.field = 'Gender'
  and vindustry.field = 'Industry'

I am currently working on the table which has around 500k of records and for each id type there would be around 10 – 30 entries, so if more records are there for one id type then more joins would be added up.

Because of this executing it is taking a lot of time.

Is there any way that we can reduce this time taken for execution and also this table is used by an website where there would be around 1000 to 50000 users.

Best Answer

This is your query:

Select vname.Value, vgender.value, vindustry.value
from ABC [vname] with (nolock) join
     ABC [vgender] with (nolock)
     on vname.id = vgender.id join
     ABC [vindustry] with (nolock)
     on vgender.id = vindustry.id
where vname.field = 'Name' and
      vgender.field = 'Gender' and
      vindustry.field = 'Industry';

You can try indexes on this query. I would try ABC(id, field, value) and ABC(field, id, value).

However, you might also try the following:

select max(case when field = 'Name' then value end) as Name,
       max(case when field = 'Gender' then value end) as Gender,
       max(case when field = 'Industry' then value end) as Industry      
where field in ('Name', 'Gender', 'Industry')  
from ABC
group by id;