I just got a question from Dirk Bonenkamp. He has a query which returns a number of contacts, but he wants to get no more than 5 contacts of per customer. After thinking really hard, I came up with a solution using variables and a subquery.

To test this idea, I used the ‘world’ database available at MySQL dev zone. This query selects no more than 5 countries per continent.

SET @a=0; SET @b="";
SELECT Name, Continent FROM (SELECT @a:=IF(@b=Continent, @a+1, 0) AS a, Name, @b:=Continent AS Continent FROM Country ORDER BY Continent) AS t WHERE a < 5;

This isn’t one of the nicest looking solutions, but it works. Do you have a better solution? Please let me know :) .