Write a Delete sql query in Magento 2 standard way without Model file.

Write a SQL delete query using Magento standard way for delete specific row from the database table using Magento 2.

You can write direct SQL query delete() without worrying about Model operation using a given code snippet in the blog.

Return Type: delete() return type is int. The number of affected rows for delete operation in a table.

/**
 * Deletes table rows based on a WHERE clause.
 *
 * @param  mixed $table The table to update.
 * @param  mixed $where DELETE WHERE clause(s).
 * @return int The number of affected rows.
 */
public function delete($table, $where = '');

Demo,

<?php
namespace Path\To\Class;

use Magento\Framework\App\ResourceConnection;

class DeleteQuery {

    const ORDER_TABLE = 'sales_order';

    /**
     * @var ResourceConnection
     */
    private $resourceConnection;

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

    /**
    * delete Sql Query
    *
    * @return int
    */
    public function deleteQuery()
    {
      $connection  = $this->resourceConnection->getConnection();
      $tableName = $connection->getTableName(self::ORDER_TABLE);
      $orderStatus = 'pending';

      $whereConditions = [
          $connection->quoteInto('status = ?', $orderStatus),
      ];

      $deleteRows = $connection->delete($tableName, $whereConditions);
      return $deleteRows;
    }
}

Remove all the rows with Status equals Pending in the sales_order table.

We have taken a simple sales_order database table example to remove all the records that have status equals pending. Using the above code snippet, All the Pending status of order records will be removed from the table.

Output: No. of affected deleted rows.

Check for other Direct Sql Query in Magento 2