Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

COUNT(*) returning multiple rows instead of just one

Tags:

mysql

count

Why does COUNT() return multiple rows when I just need the total count of how many rows my query generates?

Should return 1078.

enter image description here

like image 437
silkfire Avatar asked Aug 19 '13 08:08

silkfire


People also ask

How do I COUNT a single row in SQL?

The SQL COUNT() function returns the number of rows in a table satisfying the criteria specified in the WHERE clause. It sets the number of rows or non NULL column values. COUNT() returns 0 if there were no matching rows.

Is COUNT (*) and COUNT 1 Same?

The simple answer is no – there is no difference at all. The COUNT(*) function counts the total rows in the table, including the NULL values. The semantics for COUNT(1) differ slightly; we'll discuss them later. However, the results for COUNT(*) and COUNT(1) are identical.

How does COUNT (*) work in SQL?

COUNT(*) returns the number of rows in a specified table, and it preserves duplicate rows. It counts each row separately. This includes rows that contain null values.

What is the difference between COUNT (*) and COUNT expression?

The difference is simple: COUNT(*) counts the number of rows produced by the query, whereas COUNT(1) counts the number of 1 values. Note that when you include a literal such as a number or a string in a query, this literal is "appended" or attached to every row that is produced by the FROM clause.


1 Answers

The COUNT() is working as expected. When you put a group by clause, the count() gives you the result for GROUP BY. If you wish to get the count of rows in a query that includes group by, use it as a subquery instead.

Something like:

SELECT COUNT(*) FROM (SELECT * FROM `table`
                      GROUP BY `column1`) AS `a`
like image 119
Kangkan Avatar answered Oct 06 '22 09:10

Kangkan