[Solved] SQL query optimization
Looking to automatically optimize YOUR SQL query? Start for free.

EverSQL Database Performance Knowledge Base

SQL query optimization

I have a query that takes too long to execute. I need to know if there is any optimum way of executing that to reduce execution time.

my query is

SELECT     TOP (2) ID,
                   (
                    SELECT     SUM(CurrentStock) AS SimilarItemQuantity
                    FROM          Inventory AS T1
                    WHERE      (Inventory.ProductName = ProductName)
                   ) 
                   AS Expr1
FROM         Inventory

Consider that for 20 records and it takes 15 seconds. Is there a more faster way of doing it.

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
Optimal indexes for this query:
ALTER TABLE `Inventory` ADD INDEX `inventory_idx_productname` (`ProductName`);
The optimized query:
SELECT
        TOP (2) Inventory.ID,
        (SELECT
            SUM(T1.CurrentStock) AS SimilarItemQuantity 
        FROM
            Inventory AS T1 
        WHERE
            (
                Inventory.ProductName = Inventory.ProductName
            )) AS Expr1 
    FROM
        Inventory

Related Articles



* original question posted on StackOverflow here.