Direct SQL Queries in Magento

Magento includes a database abstraction layer and object relationship manager that is really great at ensuring data integrity and consistent data access. In general, you should avoid writing to the database and instead use a well-written Magento extension that performs the task for you. However, sometimes a direct query needs to be made whether for performance or convenience and in this case you need to know how to do direct queries the right way.

Step 1: Get the database connection

To get the database connection, so you can execute the direct query you should use one of the following depending on whether you need to read or write:

Step 2: Get the table names

Almost every SQL query will require the use of a table name. Magento tables can be prefixed, so it is important to not hardcode the table name. There are two methods to get a table name that will include the prefix:

Get the table name from an entity

Get the table name from a string

Step 3: Reading from a table

Now that we have the read connection and table name we are ready to read from a table. It is oftentimes much faster to perform a direct read of a Magento database, than to the load the object property. In this example we will read the product table in get all products with their ID and SKU:

Step 4: Writing to a table

Just as direct reading can be faster, so can direct writing. Sometimes much faster. Here is a simple example of how to update the SKU of a product with the ID of 1:

Conclusion

Direct reading / writing can be faster or more convenient than using Magento models. However, it is important to do it with cautsion especially when doing direct writing. Magento models ensure data integrity and allow triggers that do things like the Magento full page cache or Magento indexing. Directly writing can create unforeseen issues.