Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimizing select count(*) from table

Tags:

sql

sql-server

I have table Eli with 1 million records. When I query the following:

Select count(*) from Eli where userId ='my_user'

It is taking more than 10 mins to give results. I searched web and found better way to optimize the query from http://dbatipster.blogspot.com/2009/08/get-row-counts-fast.html.

How do I utilize the the following query into my above query-

SELECT OBJECT_NAME(i.id) [Table_Name], i.rowcnt [Row_Count] 
FROM sys.sysindexes i WITH (NOLOCK) 
WHERE i.indid in (0,1) 
ORDER BY i.rowcnt desc
like image 618
user2961127 Avatar asked Nov 28 '25 15:11

user2961127


1 Answers

Without touching on properly building a table, I would use something like this:

SELECT COUNT(userID) FROM Eli (NOLOCK)
WHERE userId ='my_user'

The (NOLOCK) hint allows you to select from the table without other transactions against the Eli table being committed, meaning you're not waiting for other updates and inserts to complete before returning your results.

like image 139
Jake Avatar answered Nov 30 '25 06:11

Jake



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!