Magento 1.9 – Delete All Orders Older Than Specific Date by DB Query

deletemagento-1.9orders

I need to delete about 7500 orders and keep the orders from 26.08.2016 and onward. I would like to do it through db query. Is it possible or I have to stick with admin panel?

Best Answer

you can try this, but backup first in case I'm wrong.
I don't recommend using direct queries because you might end up with zombie data.
You can create a script:

First tell the script that you are on the admin area:

Mage::register('isSecureArea', true);

Then get the orders:

$orders = Mage::getModel('sales/order')->getCollection()
     ->addFieldToFilter('created_at', array('lt' => '2016-08-26'));  

Now for each order you have to delete the invoices, invoice items, shipments, shipment items, creditnotes, creditnote items, order items, payment references, quote, quote items and in the end the order itself.

foreach ($orders as $order) {
    //delete invoices
    $invoices = $order->getInvoiceCollection();
    foreach ($invoices as $invoice) {
        //invoice items will be deleted as well
        $invoice->delete();
    }
    //delete invoices
    $shipments = $order->getShipmentsCollection();
    foreach ($shipments as $shipment) {
        //shipment items will be deleted as well
        $shipment->delete();
    }
    //delete credit notes
    $creditMemos = $order->getCreditmemosCollection();
    foreach ($creditMemos as $creditMemo) {
        //credit note items will be deleted as well
        $creditMemo->delete();
    }
    //delete payment references
    $payments = $order->getPaymentsCollection();
    foreach ($payments as $payment) {
        $payment->delete();
    }
    //delete quote
    $quote = Mage::getModel('sales/quote')->load($order->getQuoteId());  
    if ($quote->getId()) {
        foreach ($quote->getAllItems() as $item) {
            $item->delete();
        }
        $quote->delete();
    }
    //delete the order. items will be deleted as well. So does addresses.
    $order->delete();
}
Related Topic