Magento 2 SQL queries › Customers
Which cities do our repeat customers come from?
Short answer: Find customers with more than one order, take the billing address of their latest order, and count by city.
In the Magento admin
- Export orders with billing addresses and count repeat emails per city in a spreadsheet.
With one query
These queries only read data. Run them on a copy of your database if you can, or ask your developer to. If your tables have a prefix (set in app/etc/env.php), add it to each table name.
Works on Magento Open Source and Adobe Commerce:
SELECT a.city, a.country_id, COUNT(*) AS repeat_customers
FROM (
SELECT o.customer_email, MAX(o.entity_id) AS last_order_id
FROM sales_order o
WHERE o.state <> 'canceled'
GROUP BY o.customer_email
HAVING COUNT(*) > 1
) r
JOIN sales_order_address a ON a.parent_id = r.last_order_id AND a.address_type = 'billing'
GROUP BY a.city, a.country_id
ORDER BY repeat_customers DESC
LIMIT 25;
Good to know
- City is free text, so “London”, “london” and “LONDON ” are separate rows unless your database collation ignores case. Trim and compare by postcode if you need exact numbers.