I want to reassign existing orders to customers after deleting all customers and importing them into Magento 2 from a csv. The sales_order.customer_id values are not matching with the correct customer anymore in the table. They have a value of NULL. But the emails are still there in sales_order.customer_email.

I would like a SQL query (or Magento 2 way if easier) which compares the emails if they are matching in both tables sales_order.customer_email and customer_entity.email. If the emails are matching, the SQL query should update the sales_order.customer_id value with the value from customer_entity.entity_id

Afaik after that I can just reindex to update the sales_order_grid table, right?

1 Answer 1


After some trying around I solved it by using the following SQL qeuery:

UPDATE sales_order as SFO
INNER JOIN customer_entity as C
ON C.email = SFO.customer_email
SET SFO.customer_ID = C.entity_id
WHERE SFO.customer_is_guest = 0

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.