Skip to main content
1 of 3
joedotnot
  • 123
  • 1
  • 4

Why is a COUNT query faster than a RESULTSET query?

Suppose I have two similar queries, with complex joins; query1 returns rows and columns, and query2 returns just the Count of rows as per query 1;

var mySearchSql = @"SELECT col1, col2, col3, ...etc 
    FROM MyBigTable
       LEFT JOIN AnotherTable1 On ... etc 
       LEFT JOIN AnotherTable2 On ... etc
    WHERE someCol1= val1
    AND someCol2= val2
    AND etc...
";

var myCountSql = @"SELECT count(MyBigTable.PKcol)
    FROM MyBigTable
       LEFT JOIN AnotherTable1 On ... etc 
       LEFT JOIN AnotherTable2 On ... etc
    WHERE someCol1= val1
    AND someCol2= val2
    AND etc...
";

Self-evident logic tells me the Sql engine (of most databases, say SqlServer, MySql, IBM DB2, whatevs...) will RETURN from the count query FASTER than the resultset query; AT LEAST WHEN WE ARE TALKING BIG RESULT-SETS.

Obviously transferring lots of rows and columns across a network... will take longer. than just a single scalar value of count !

My questions are (a) does the DB-Engine have to do similar amount of work / effort for both queries, and (b) therefore, the bottleneck (or delay in receiving the results) is simply due to transferring bigger data across a network ?

joedotnot
  • 123
  • 1
  • 4