| 
	
 | 
 Posted by Erland Sommarskog on 02/25/07 23:20 
C10B (tswalton@gmail.com) writes: 
> I have a table with several million rows. 
> Each row is simply the date and time a certain page was viewed. 
>  
> eg 
> page1   1-1-00 
> page2   2-1-00 
> page1   16-1-00 
> page1   17-1-00 
> page2   19-1-00 
>  
> I now need to find the most popular pages so I do this... 
>  
> SELECT TOP 10 COUNT(*) AS mycount FROM tblPageViews 
> GROUP BY place ORDER BY COUNT(place) DESC 
>  
> ...which gives me the top 10 most viewed pages 
>  
> big problem - this is getting slower and slower as the table grows and 
> grows. 
>  
> what should I do? 
  
A non-clustered index on place would help, as SQL Server then only  
would have to scan that index, and not the entire difference. But it  
seems that the table has two columns. In such case, the index would not 
reduce execution time that much. 
 
A better alternative may be to define an indexed view that maintains 
the count: 
 
   CREATE TABLE pagehits (pageid varchar(20) NOT NULL, 
                          viewtime datetime NOT NULL, 
                          PRIMARY KEY (pageid, viewtime) 
   ) 
   go 
   CREATE VIEW pagecount WITH SCHEMABINDING AS 
      SELECT pageid, cnt = COUNT_BIG(*) 
      FROM   dbo.pagehits 
      GROUP  BY pageid 
   go 
   CREATE UNIQUE CLUSTERED INDEX pagecount_ix ON pagecount(pageid) 
   go 
   SELECT TOP 10 pageid, cnt 
   FROM   pagecount WITH (NOEXPAND) 
   ORDER  BY cnt 
   go 
   DROP VIEW pagecount 
   DROP TABLE pagehits 
 
I added the NOEXPAND hint to the query, since it's only on Enterprise 
Edition, the optimizer considers indexed views.  
 
Note that this could have effect on performance when writing to the table. 
 
--  
Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se 
 
Books Online for SQL Server 2005 at 
http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx 
Books Online for SQL Server 2000 at 
http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx
 
  
Navigation:
[Reply to this message] 
 |