I have a list of UK postcodes, looking roughly like this. Entries may not be unique.

A1 1AA
A1 2BC
A1 3PN
B2 4XY
B2 5LH
C3 6NJ

They're in a range named Postcodes. I've set up the following arrangement to count how many instances of each postcode area (the part before the space) there are.

   A                 B (range "PostcodeAreas")        C                       D
1  =SORT(Postcodes)  =REGEXREPLACE($A1, "\s\w+", "")  =UNIQUE(PostcodeAreas)  =COUNTIF(PostcodeAreas, $C1)

I've extended the formulas in B1 and D1 downwards to cover the data output of the formulas in A1 and C1.

This works, and the output would be this for my example data:

   A       B    C   D
1  A1 1AA  A1   A1  3
2  A1 2BC  B2   B2  2
3  A1 3PN  C3   C3  1
4  B2 4XY
5  B2 5LH
6  C3 6NJ

Columns A and B, being workings, aren't relevant to the target audience of the sheet, so I've hidden them. The end result is a nice set of counts in columns C and D.

All well and good. However, I can't help feeling that this can be optimized a bit. Particularly, I don't like the manually-extended formula in B1. Is it possible to write a single formula that applies the regular expression to all of the SORT() output? Which I could then perhaps even wrap in the UNIQUE(), and eliminate the need for working columns entirely? I've searched around a bit but couldn't quite find an answer.

  • For the postal code, wouldnt (LEFT(A1, 2) suffice?
    – Jacob Jan
    May 1, 2015 at 21:14
  • 1
    No, my example data is a simplification. The first part of a UK postcode can contain several different patterns of letters or numbers.
    – Scott
    May 2, 2015 at 20:18

1 Answer 1


Assuming your data is in A1:A, try in B1

=query(ArrayFormula(iferror(regexextract(A1:A, {"^(.+)\s", "\s(.+)$"}))), "select Col1, count(Col2) where Col1 <>'' group by Col1")
  • Beautiful - ARRAYFORMULA was the key. Thanks very much.
    – Scott
    May 1, 2015 at 18:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.