AI Reports

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

  1. 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

Related

Gaurav Harsh

Gaurav Harsh is a Magento developer who works on large Adobe Commerce stores and builds AI Reports, a Magento extension for asking your store's data questions in plain English. LinkedIn