The following code does not give me any output.

    $collection = Mage::getModel('sales/order_status_history')->getCollection()->getLastItem();

I have SQL Query for this but I have to use magento collection for this.

   SELECT MAX(entity_id) AS entity_id FROM sales_flat_order_status_history

Any idea ?

4 Answers 4


Try using an expression. You will have more control over what you're attempting to query.

$collection = Mage::getModel('sales/order_status_history')->getCollection()
    ->addFieldToSelect(new Zend_Db_Expr('MAX(entity_id) AS entity_id'))

$maxEntityId = $collection->getData('entity_id');
  • MAX(entity_id) is much more efficient than setOrder , as it is much less ressource intensive for the database engine. So, even if it seems less beautiful to have some pure SQL bits wrapped by a Zend DB Expr, it will be much better to use daXXon's solution.
    – Cedric
    Nov 14, 2018 at 9:49

You can use setOrder('Index','Order') function for getting max data

                  ->setOrder('created_at', 'desc')->getFirstItem()

print_r( $maxData->getData());
    $collection = Mage::getModel('sales/order_status_history')->getCollection();
    $collection->getSelect()->order('entity_id DESC');
    $maxId = $collection->getFirstItem()->getId();
  • Who marked my post for deletion - please leave your feedback
    – zhartaunik
    Aug 3, 2015 at 13:54
  • 1
    This will load the ENTIRE sales/order_status_history table and then get the first item of the underlying Varien_Collection. Add ->setPageSize(1) to the collection to LIMIT the query.
    – Elias
    May 3, 2017 at 12:01
  • Good stuff!....
    – zhartaunik
    May 4, 2017 at 7:19
  • While this works, ordering is much more resource consuming for a database than the SQL MAX function itself
    – Cedric
    Nov 14, 2018 at 9:36
$collection->addExpressionFieldToSelect("max_id", "MAX(entity_id)", [])

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.