Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use COUNT(*) AS `COUNT` in MYSQL Where Clause

Tags:

mysql

count

I am trying to find, count and report all instances of duplicates entries in a column. Any idea how to do that similar to my attempt below.

SELECT `Id`, COUNT(*) AS `COUNT`
FROM `testproductdata`
WHERE `COUNT` > 1
GROUP BY `Id`
ORDER BY `COUNT` DESC;

I am getting a 1054 error: Unknown column COUNT in where clause.

like image 593
EricImprint Avatar asked Jan 22 '26 00:01

EricImprint


2 Answers

Use HAVING over WHERE with GROUP BY

SELECT `Id`, COUNT(*) AS `COUNT`
FROM `testproductdata`
GROUP BY `Id`
HAVING  `COUNT` > 1
ORDER BY `COUNT` DESC;

And I suggest to use relevant name for expression on count(*) as total_count than COUNT.

Change query as below:

SELECT `Id`, COUNT(*) AS `total_count`
FROM `testproductdata`
GROUP BY `Id`
HAVING  `total_count` > 1
ORDER BY `total_count` DESC;
like image 158
Ravinder Reddy Avatar answered Jan 24 '26 19:01

Ravinder Reddy


You should change the where for a having, this should work:

SELECT Id, COUNT(1) AS count
FROM testproductdata
GROUP BY Id
HAVING COUNT(1) > 1
ORDER BY COUNT(1) DESC;
like image 20
Leo Avatar answered Jan 24 '26 18:01

Leo



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!