|
|
|
|
|
by buckbova
4504 days ago
|
|
I don't understand what you mean "trick". SELECT date_column, count(*)
FROM tbl
WHERE a = @a
AND b = @b
GROUP BY date_column;
The "AND b = @b" causes the sql engine to access data in the table instead of solely relying on the index. GROUP BY has 0 to do with it. If you changed the query to SELECT a, date_column
FROM tbl
WHERE a = @a
and SELECT a, date_column
FROM tbl
WHERE a = @a
AND b = @b
The answer would be the same. |
|
If we're told that:
SELECT a, date_column FROM tbl WHERE a = @a
Returns 100 rows.
Then:
SELECT a, date_column FROM tbl WHERE a = @a AND b = @b
Will only have to scan column b over 100 rows.
Even without an index that will always be neglible, not compared to using the index to grab 100 rows from 10million but just compared to running a query and returning results at all.
The reason that the original can be a lot slower is that the 100 and 10 rows of results are comprised of a lot more rows of actual information, because of the grouping.
You're right that:
SELECT a, date_column FROM tbl WHERE a = @a AND b = @b
would be a lot slower, given the same data, but that isn't the scenario, the group by has implications about what "returns 100 rows, returns 10 rows" actually means in terms of data read.