5

I've been using the sp_MSforeachtable built-in stored procedure to determine the row count of each table in our database, using COUNT(*).

I've realized, though, that I just want a 0 or 1, depending on whether there are any rows at all in the table.

Is there something else I can use that's faster/cheaper than COUNT(*)?

Rich Armstrong
  • 1,432
  • 2
  • 16
  • 20
  • Have a look at http://stackoverflow.com/questions/1597442/subquery-using-exists-1-or-exists – StuartLC Aug 09 '10 at 16:28
  • 1
    Whatever answers you come up with should be benchmarked. COUNT(*) is probably well optimized depending on the DBMS, in addition it clearly expresses the intent of what you are trying to do. – Romain Hippeau Aug 09 '10 at 16:39

5 Answers5

8

Consider this query. EXISTS will stop execution when it finds the first match.

IF EXISTS (SELECT 1 FROM MyTable)
BEGIN
   print 'at least one!'
END
ELSE
BEGIN
   print 'no rows found in table'
END
p.campbell
  • 98,673
  • 67
  • 256
  • 322
3

This will print all the table names that have at least 1 row

exec sp_MSforeachtable 'if  exists (select 1 from ?) print ''?'''
SQLMenace
  • 132,095
  • 25
  • 206
  • 225
0

Maybe just grab the first row, and display a 1?

select top 1 1 from tablename

Dean J
  • 39,360
  • 16
  • 67
  • 93
  • @p.campbell: you could just ask for the correction, instead of spending your own rep on downvoting. :) Correction look right? – Dean J Aug 09 '10 at 17:00
  • @p.campbell; gave you an upvote anyways, hopefully that makes up for it. – Dean J Aug 09 '10 at 17:07
  • actually I didn't downvote your answer! I agree with not wasting rep! But other definitely are downvoting my own! – p.campbell Aug 09 '10 at 17:08
0
SELECT TOP 1 ID FROM TABLE

Then you can do an EOF check when the recordset is returned.

Tom Gullen
  • 61,249
  • 84
  • 283
  • 456
0

sp_spaceused will probably be more efficient than COUNT(*).

Keep in mind that it does not update in real time so it may not be 100% accurate in all cases.

Dan Herbert
  • 99,428
  • 48
  • 189
  • 219