Solved

Count the TOP n Records

Posted on 2011-03-03
4
298 Views
Last Modified: 2012-05-11

Is there any way of doing a count using count(*) over that only counts the first x number of records?

Reason I ask is that a search may return 300,000 results but in reality I want to say if more than 500 returned just tell the user that. SQL is so slow at counting that I don't want it ot count the full 300,000.
0
Comment
Question by:vliwill
  • 2
4 Comments
 
LVL 6

Expert Comment

by:Mistralol
ID: 35025828

What like

SELECT TOP 501 COUNT(*) FROM Table WHERE .....

If you have > 501 you say > 500 results?
0
 
LVL 23

Accepted Solution

by:
Rajkumar Gs earned 500 total points
ID: 35025857
Evenif total COUNT is greater than or equal to 500, result of this query would be 500
If count is lesser than 500, it would return real count
SELECT COUNT(*)
FROM (SELECT TOP 500 * FROM YourTable) A

Open in new window

0
 

Author Closing Comment

by:vliwill
ID: 35025964
Perfect thanks
0
 
LVL 23

Expert Comment

by:Rajkumar Gs
ID: 35025986
Glad to help and for the points
Raj
0

Featured Post

Visualize your virtual and backup environments

Create well-organized and polished visualizations of your virtual and backup environments when planning VMware vSphere, Microsoft Hyper-V or Veeam deployments. It helps you to gain better visibility and valuable business insights.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Why I am having this error in my query? 2 32
TSQL Challenge... 7 43
Need to find substring in SQL 5 40
Can I skip a node in XML? 9 29
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

713 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question