Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

COUNT(*) with and without GROUP BY, no matching rows

Tags:

sql

mysql

Consider a relation table (Balance,Customer) with the following records:

screenshot of database table

Now I tried these two queries here:

-- Query 1:
select A.Customer, count(B.Customer)
from account A, account B
where A.balance < B.balance
group by A.Customer;

-- Query 2:
select A.Customer, count(B.Customer)
from account A, account B
where A.balance < B.balance;

The first query gives me no output. With the second query, I am getting an output with count = 0.

In both cases there are no rows satisfying the criteria in the where clause, and hence no rows are returned. Then why is the count function giving an output only in the second case?

like image 294
Zephyr Avatar asked Dec 03 '25 23:12

Zephyr


1 Answers

An aggregation query that has no group by always returns one row (if it is syntactically correct). The count in such a row would be 0.

An aggregation query with a group by returns one row per group. If there are no groups then there are no rows.

like image 87
Gordon Linoff Avatar answered Dec 05 '25 13:12

Gordon Linoff



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!