Magento 2 Direct SQL Queries in Zend Format

Magento 2 Direct SQL Queries in Zend Format

Sometimes due to some project requirements, we need to directly communicate with Magento2 Database and we have to write SQL queries for that. This post will help you to write direct SQL Queries in Zend Format.

 

public function __construct(
   \Magento\Framework\App\ResourceConnection $resourceConnection
) {
    $this->resourceConnection = $resourceConnection;
}

$connection = $this->resourceConnection->getConnection();
$tableName = $this->resourceConnection->getTableName('customer_history');
$tableName2 = $this->resourceConnection->getTableName('order_history');

OR

Using Object Manager Directly:

$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();
$resource =  $objectManager->get('Magento\Framework\App\ResourceConnection');

$connection = $resource->getConnection();

$tableName =$resource->getTableName('customer_history');

$tableName2 =$resource->getTableName('order_history');

 

Select Queries:

Syntax: 

$select = $connection->select()
 ->from(
 ['p' => $tableName])
  ->where('p.column_name=?', $value)
  ->where('p.column_name2 >=?', $value)
  ->order('p.column_name3 DESC')
  ->limit($pagesize, $offset);

$data = $connection->fetchAll($select);

Example:

$select = $connection->select()
         ->from(
        ['p' => $tableName])
        ->where('p.customer_id=?', 5)
        ->where('p.status =?', 1)
        ->order('p.createdat DESC')
        ->limit(10, 0);

To get only selected columns from Table:

$select = $connection->select()
 ->from( ['p' => $tableName],['p.order_id', 'p.status']) 
->where('p.customer_id=?', 5) 
->where('p.status =?', 1)
 ->order('p.createdat DESC') 
->limit(10, 0);

 $data = $connection->fetchAll($select);

Perform Select Query with JOIN

 

$select  = $connection->select()
           ->from(
                  ['p' => $tableName], ['p.customer_id', 'p.status', 'p.order_id','o.ordertotal']
                 )
                 ->join(
                        ['o' => $tableName2], 'main_table.order_id = order.id', ['']
                )
                ->where('p.order_id = (?)', '455');

$data = $connection->fetchAll($query);

 

Insert Query:

Syntax: 

$data = ["column_name"=>$value,"column_name2"=>$value2,'column_name3'=>$value3];

$connection->insert($tableName, $data);

Example : 

$data = ["customer_id"=>'22',"status"=>1,'order_id'=>'455'];

$lastInsertedID= $connection->insert($tableName, $data);

 

Update Query:

Syntax:

$data = ["column_name3"=>$value3];

$where = ['column_name = ?' => $value, 'column_name2 = ?' => $value2];

$updatedRows=$connection->update($tableName, $data, $where);

Example:

$data = ["status"=>1];

$where = ['customer_id = ?' => '22', 'order_id = ?' => '455'];

$updatedRows=$connection->update($tableName, $data, $where);

 

Delete Queries

Syntax: 

$connection->delete(
            $tableName,
            ['column_name = ?' => $value, 'column_name2 = ?' => '0']
        );

Example :

$connection->delete(
            $tableName,
            ['customer_id = ?' => '22', 'status = ?' => '0']
        );

 

1   0
Eecrets Magento
profile Meerak 25th May 2026

Explore stylish printed lawn dress designs with vibrant patterns, premium lawn fabric, and trendy silhouettes. Ideal for everyday wear, summer fashion, and effortless elegance all season long.

profile Miss 25th May 2026

Create precise and bold eye looks with a premium eyeliner pencil. Easy to apply, highly pigmented, and long-lasting eyeliner pencils are perfect for everyday and party makeup.

profile Adoro 25th May 2026

Discover the ultimate collection of stylish ladies handbags at Adoro. Find the perfect accessory to elevate your outfit and express your unique style.

profile Servis 23rd May 2026

Get the best formal shoes for men online in Pakistan at low Prices. Explore a wide range of formal shoes collections at Servis and order your favorite shoes today.

profile Shop 22nd May 2026

Take a look at a fantastic selection of Ladies Trousers Designs at ECS. Whether you're looking for black or white trousers, our collection has something for everyone. Shop now today.

profile OzGames 7th February 2026

If you enjoy social deduction games, Among Us is definitely worth trying.

profile nyt 31st January 2026

The way you presented complex information so simply is remarkable. pips game

profile Amora 28th January 2026

Pure momentum is one of the game's motifs; as the player rolls along Slope under increasing pressure, speed steadily increases, requiring quick thinking, quick reactions, and constant flexibility to survive longer runs.

profile Pallas 8th December 2025

Always keep in mind that you are one of a kind. The same as everyone else bitlife

profile oralied 6th October 2025

The design of Pips NYT is beautiful — clean, minimal, and satisfying to interact with. The small animations and sound effects make it feel premium, just like Wordle and Connections from NYT Games.

profile jack 30th July 2025

a extremely superb webpage. a realy educational in addition to a an extremely superior position. i’m a sucker for the. thongs for halloween

profile mixapo4728 20th July 2025

heavy window curtains would be much needed this december to conserve more heat**부달

profile mixapo4728 20th July 2025

i do paid online surverys and also monetize my blogs, both are good sources of passive income’부달

profile Nimra 22nd June 2025

Nice post! This is a very nice blog that I will definitively come back to more times this year! Thanks for informative post. skor live

profile Nimra 22nd June 2025

Nice post! This is a very nice blog that I will definitively come back to more times this year! Thanks for informative post. casino online

Related Post

11th June 2020

Upgrade Magento to ver 2.3.5-p1 without composer

Magento released 2.3.5-p1 that includes 180 functional fixes, 25 security enhancements, support for Elasticsearch 7.x and migration of the Zend to Laminas....

read more reply

Please rotate your device

We don't support landscape mode on your device. Please rotate to portrait mode for the best view of our site