Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you Select TOP x but still get a COUNT of the whole query?

Tags:

sql

sql-server

I'm writing a webpage to interactively filter results based on filter criteria as it is specified by the user. I only want to return from SQL the TOP 20 rows but I want to know how many rows met the criteria (Count). I want to be able to tell the user: "here are the top 20 rows matching your criteria, and BTW, there were 2,000 additional rows I'm not showing here".

I know I could simply run the query twice but EWWWW that's expensive and wasteful. How can I achieve what I want without over taxing the database?

like image 451
kingdango Avatar asked Oct 05 '11 14:10

kingdango


People also ask

How do I count a query in a selection?

The COUNT (*) function returns the number of rows that satisfy the WHERE clause of a SELECT statement. The following example finds how many rows in the stock table have the value HRO in the manu_code column: SELECT COUNT(*) FROM stock WHERE manu_code = 'HRO';

How does SELECT top work in SQL?

Limits the rows returned in a query result set to a specified number of rows or percentage of rows in SQL Server. When you use TOP with the ORDER BY clause, the result set is limited to the first N number of ordered rows. Otherwise, TOP returns the first N number of rows in an undefined order.


1 Answers

You can use COUNT(*) OVER()

SELECT TOP 20 *, 
       COUNT(*) OVER() AS TotalMatchingRows
FROM master..spt_values
WHERE type='P'
ORDER BY number

Doing two queries may work out more efficient however especially if you have narrower indexes that can be used in determining the matching row count but don't cover the entire SELECT list.

like image 102
Martin Smith Avatar answered Oct 12 '22 19:10

Martin Smith