Software Technology Tips

While working on a query to count some rows based upon a condition I found an interesting thing.If you were to use the COUNT function in a query for a condition then we have to use the HAVING clause instead of  WHERE clause.

So the following query would return error:

$wrong_query = "SELECT count( `fk_mp` ) FROM wrong_tab GROUP BY `pg_name`  WHERE  count( `fk_mp` ) > 1";

 

Now, compose the same query using HAVING instead of WHERE :

$right_query = "SELECT count( `fk_mp` ) FROM wrong_tab GROUP BY `pg_name`  HAVING count( `fk_mp` ) > 1";


This query can also be used to find duplicate records in a table.


Related Tags:

Database, SQL Server

Author: Mohanish Das

Database

Let us Connect!

iso 9001 QA25 Red Herring STPI D&B Fastest Growing SME 2013 Award zinnov Nasscom

This site uses cookies. We respect your privacy.copyright (c) Mindfire Solutions 2007-2015. Login