MySQL Tip: HAVING is your friend

Often times you end up with the need to pull something from the database conditionally depending upon some other criteria. For example, given the following table, how would list the first names shared by one or more people?

table: users col: firstname col: lastname

Commonly people will either put in a counter somewhere or it will be done with some loops in the application itself (which is a tremendously bad idea.)

But MySQL gives you a handy dandy way of doing exactly this task using GROUP BY and HAVING

SELECT firstname FROM users GROUP BY firstname HAVING count(firstname) > 1;

Thats pretty easy 🙂 Now on a large table you will want to have the column(s) that you do this on indexed.

Leave a Reply