Write a fetchRow direct mysql query in Magento 2.

Write a Mysql fetchRow() query using Magento standard way for fetching the first row of the SQL result as an output.

You can get the first row as a result from the list of a resultant array using a query.

Direct SQL query fetchRow() without worrying about the Model operation.

Return Type: fetchRow() always returns as an array based on your query conditions.

Base Definition of function:

    /**
     * Fetches the first row of the SQL result.
     *
     * Uses the current fetchMode for the adapter.
     *
     * @param string|\Magento\Framework\DB\Select $sql An SQL SELECT statement.
     * @param mixed $bind Data to bind into SELECT placeholders.
     * @param mixed $fetchMode Override current fetch mode.
     * @return array
     */
    public function fetchRow($sql, $bind = [], $fetchMode = null);

Let’s we are fetching the first row from the sales_order table.

<?php
namespace Path\To\Class;

use Magento\Framework\App\ResourceConnection;

class FetchRow {

    const ORDER_TABLE = 'sales_order';

    private ResourceConnection $resourceConnection;

    public function __construct(
        ResourceConnection $resourceConnection
    ) {
        $this->resourceConnection = $resourceConnection;
    }

    /**
     * fetchRow SQL Query
     *
     * @return string[]
     */
    public function fetchRowQuery()
    {
        $connection  = $this->resourceConnection->getConnection();
        $tableName = $connection->getTableName(self::ORDER_TABLE);

        $query = $connection->select()
            ->from($tableName,['entity_id','status','grand_total'])
            ->where('status = ?', 'pending');

        return $connection->fetchRow($query);
    }
}

We are fetching the first row from the sales_order table with the Order status pending.

The output is the first row of the SQL result as an array.

Array
(
    [0] => Array
        (
            [entity_id] => 1
            [status] => pending
            [grand_total] => 1299.0000
        )
)

Check for other Direct SQL Query in Magento 2