Direct SQL Query in Magento 2

There are many situations where executing direct raw SQL queries would be simple and much quicker leading to a more optimized Magento get collection query as a performance basis.

On a large data set of an entity, Saving each individual entity can take a long time with resource-hungry and therefore make the system unusable.

Overcome this issue it is possible to issue a direct SQL query that could update a large set of data of an entity in fewer seconds.

When you use Direct SQL Query you don’t need to worry about Model/Factory Pattern.

By default, Magento will automatically connect to its database using class Magento\Framework\App\ResourceConnection with getConnection() function.

Using the below code snippet to run the direct SQL query to fetch Table name with a prefix,

Calling from a template or other PHP files,

You need to use the $this->resourceConnection object to run any Direct SQL Query.

Reading From The Database All the records, 

fetchAll() => This method Fetches all SQL result rows as a sequential array.
This method takes a query as it’s the first parameter, executes it, and then returns all of the results as an array.
Using this we can get all the records of
a database table.

The result will be all the records of a customer entity as an array.

fetchCol() => This method Fetches the first column of all SQL result rows as an array.

The result looks like,

fetchOne() => This method Fetches the first column of the first row of the SQL result.

Using fetchOne you can get only a single result value. In the above query, you can get an email id as a result.

Update Query: Update Records in a Database table that already exists.

Delete Query: Delete a specific row from a database table.

Insert Query: Insert a single record in the database table using the row query. The first Parameter is a table name
In the given example, We will add a record into the review table.

New records will be inserted in a review table.

insertArray Query: Insert array into a table based on columns definition.
Pass only those columns which value you want to insert in the second parameter column and the third parameter is data of the specific column.

In the below example, We will add the record into a review table.

The above query inserts the new record in the table column-wise.

There are many other row query functions related to the database. You can get all the SQL functions from the file Magento/framework/DB/Adapter/AdapterInterface.php

You can explore many direct SQL queries which will be available in other articles from this site.