Click here to Skip to main content
15,891,905 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
SQL
select COUNT(id) as tablecount from tbl_Panelist where tbl_Panelist.IsTrash='0' and  tbl_Panelist.Subscribe='1' and tbl_Panelist.Pending='0' and tbl_Panelist.UserName not in (select distinct UserName from tbl_PanelistActivity where tbl_PanelistActivity.ActivityDate>(GETDATE()-180))
Posted
Updated 3-Jan-14 0:09am
v2

1 - don't store things like IsTrash as a string. Use a bit if that's what you're storing ( 1 or 0 )

2 - try adding an index to every column you're checking to see if it speeds things up

3 - don't use DISTINCT if you can avoid it. It's not needed here, the DB does not need to filter the list to be distinct before checking on it.

4 - EXISTS is indeed faster, but getting rid of subqueries is better:

SQL
select COUNT(id) as tablecount from tbl_Panelist pl
left join tbl_PanelistActivity pa on pa.UserName = pl.UserName and pa.ActivityDate > (GETDATE()-180)
where pl.IsTrash='0' and  pl.Subscribe='1' and pl.Pending='0' and pa.Username is null


this uses a left join, if the pa values are null, then the values did not exist in the pa table.

5 - give your users a numeric id so the DB can filter on that, instead of reusing the username everywhere. What if someone changes their username, do you change it through the DB ? A numeric id will keep the records with the old username, associated with the new one.
 
Share this answer
 
Comments
Maciej Los 3-Jan-14 17:23pm    
Good advice!
It's better to use a not exists in this sort of scenario as you will not be iterating through every row in PanelistActivity:
SQL
select COUNT(id) as tablecount
from tbl_Panelist where tbl_Panelist.IsTrash='0'
and  tbl_Panelist.Subscribe='1'
and tbl_Panelist.Pending='0'
and not exists
(select UserName
from tbl_PanelistActivity
where tbl_PanelistActivity.ActivityDate>(GETDATE()-180)
and tbl_PanelistActivity.UserName = tbl_Panelist.UserName)
 
Share this answer
 
v2
You should optimize your database too using Index, stored procedure, etc.,.
Check this for more
How To: Optimize SQL Queries[^]

0) From your query, the fields(IsTrash, Subscribe, Pending) are numeric or text datatype? If the values only 0,1 or only numbers then use numeric datatype.
1) You should use UserID column instead of UserName in subquery condition.
2) Agree with GuyThiebaut. You should use EXISTS instead of IN.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900