i have got lot of queries which are written like:
select thread_id as topic_id,title as topic
,
isnull((select count(*) from tblmessages b where thread_id=a.thread_id and is_approved='Y' and sort_level>1
group by b.thread_id
),0) as replies,
isnull((select count(*) from tblmessages b where thread_id=a.thread_id and isnull(new_post,'Y')='Y' and sort_level>1
group by b.thread_id
),0) as NewPost,
isnull((select count(*) from tblmessages b where thread_id=a.thread_id and isnull(is_approved,'N')='N' and sort_level>1
group by b.thread_id
),0) as NotClear,
sort_level,sort_index, from tblMessages a
where sort_level=1 and category=@category
order by topic_id desc
Please tell me how to optimize and better way to write such queries. because i have got tables with records 5,00,000. so it takes lots of time and some times gets time out.
Thanks