Take the 2-minute tour ×

Currently I have an sql query which finds the amount of records in the database for a specific person (Ms White), how can I repeat the function for every surname within the table and print them out in a sensible format?

  $query = "SELECT COUNT(Surname) FROM Customers WHERE Surname='White'";
share|improve this question

3 Answers 3

up vote 3 down vote accepted

Wouldn't it be better to run just one query with the count per each surname?

select Surname, count(*) as Total from Customers
group by Surname

This will return results like this:

Person  Total
White       4
Mustard     2
Plum        1
share|improve this answer
Just what I was looking for, thanks! –  William Mar 14 '12 at 13:45

GROUP BY I think is what you are looking for

SELECT COUNT(*),Surname FROM Customers GROUP BY Surname
share|improve this answer
Thanks that works perfectly, however how do I print these in a logical way? Currently all I get is a series of numbers(depending on how many orders each person has made)? –  William Mar 14 '12 at 13:34
Well are you printing the second column (the Surname one)? YOu can also sort the results (using ORDER BY) by Surname or the COUNT –  cotton.m Mar 14 '12 at 13:36


SELECT count(1) as "Counter", surname FROM Customers GROUP BY surname

This will give you output like below.

Counter  +  Surname
  10     +  SN1
  15     +  SN2
  11     +  SN3
share|improve this answer

Your Answer


