How to use insertOnDuplicate query in Magento 2.

Use of insertOnDuplicate query using Magento 2,  You need to create a Connection object first to run the query using ResourceConnection class.

When you insert any new row into a table if the row causes a duplicate in Primary key or UNIQUE index, throw an error in MySQL.

Base Definition of function:

 * Inserts a table row with specified data.
 * @param mixed $table The table to insert data into.
 * @param array $data Column-value pairs or array of column-value pairs.
 * @param array $fields update fields pairs or values
 * @return int The number of affected rows.
public function insertOnDuplicate($table, array $data, array $fields = []);


class Magento2Sql
 public function __construct(
     \Magento\Framework\App\ResourceConnection $resource
 ) {
     $this->resource = $resource;

 public function executeInsertOnDuplicate()
     $tableName = "Your_Tablename";
     $data = ["column_name1"=>"value1","column_name2"=>"value2"]; // Key_Value Pair
     $connection = $this->resource->getConnection();
     $connection->insertOnDuplicate($tableName, $data);

The first argument is tableName
The second argument is the key-value pair of an array.
The third argument is optional for the table’s field of array. (update fields pairs)

Check for other Direct SQL Query in Magento 2