Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two ways to use Count, are they equivalent?

Tags:

sql

count

Is

SELECT COUNT(a.attr)
FROM TABLE a

equivalent to

SELECT B
FROM (SELECT COUNT(a.attr) as B
      FROM TABLE a)

I would guess no, but I'm not sure.

I'm also assuming the answer would be the same for functions like min, max, avg, correct?

EDIT:

This is all out of curiosity, I'm still new at this. Is there a difference between the value returned for the count of the following and the above?

SELECT B, C
FROM (SELECT COUNT(a.attr) as B, a.C
      FROM TABLE a
      GROUP BY c)

EDIT AGAIN: I looked into it, lesson learned: I should be awake when I try to learn about these things.

like image 904
null Avatar asked Jan 21 '26 19:01

null


1 Answers

Technically, they are not the same, the first one is a simple select, the second one is a select with a sub select.
But every sane optimizer will generate the same execution plan for both of them.

like image 177
Daniel Hilgarth Avatar answered Jan 23 '26 13:01

Daniel Hilgarth



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!