[Solved] I want to Query w3school database

How to optimize this SQL query?

In case you have your own slow SQL query, you can optimize it automatically here.

For the query above, the following recommendations will be helpful as part of the 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. Avoid OR Conditions By Using UNION (modified query below): In mosts cases, filtering using the OR operator cannot be applied using indexes. A more optimized alternative will be to split the query to two parts combined with a UNION clause, while each query holds one part of the original OR condition.
  2. 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.
  3. Prefer Inner Join Over Left Join (modified query below): We identified that one or more left joined entities (e.g. `Shippers`) are used in the 'where' clause, in a way that allows to replace it with an optimized inner join. Inner joins can be fully optimized by the database, while Left joins apply limitations on the database's optimizer.
  4. Prefer Inner Join Over Left Join (modified query below): We identified that one or more left joined entities (e.g. `Employees`) are used in the 'where' clause, in a way that allows to replace it with an optimized inner join. Inner joins can be fully optimized by the database, while Left joins apply limitations on the database's optimizer.
  5. Use UNION ALL instead of UNION (query line: 72): Always use UNION ALL unless you need to eliminate duplicate records. By using UNION ALL, you'll avoid the expensive distinct operation the database applies when using a UNION clause.
Optimal indexes for this query:
ALTER TABLE `Categories` ADD INDEX `categories_idx_categoryid` (`CategoryID`);
ALTER TABLE `Customers` ADD INDEX `customers_idx_customerid` (`CustomerID`);
ALTER TABLE `Employees` ADD INDEX `employees_idx_lastname_firstname` (`LastName`,`FirstName`);
ALTER TABLE `OrderDetails` ADD INDEX `orderdetails_idx_orderid` (`OrderID`);
ALTER TABLE `Orders` ADD INDEX `orders_idx_employeeid` (`EmployeeID`);
ALTER TABLE `Products` ADD INDEX `products_idx_productid` (`ProductID`);
ALTER TABLE `Shippers` ADD INDEX `shippers_idx_shippername_shipperid` (`ShipperName`,`ShipperID`);
The optimized query:
SELECT
        c_customername,
        c_contactname,
        c_address,
        c_city,
        c_postalcode,
        c_country,
        o_orderdetailid,
        s_phone,
        r_productname,
        r_price,
        o_quantity,
        g_categoryname 
    FROM
        ((SELECT
            c.CustomerName AS c_customername,
            c.ContactName AS c_contactname,
            c.Address AS c_address,
            c.City AS c_city,
            c.PostalCode AS c_postalcode,
            c.Country AS c_country,
            o.OrderDetailID AS o_orderdetailid,
            s.Phone AS s_phone,
            r.ProductName AS r_productname,
            r.Price AS r_price,
            o.Quantity AS o_quantity,
            g.CategoryName AS g_categoryname 
        FROM
            Customers c 
        JOIN
            Orders d 
                ON (
                    c.CustomerID = d.CustomerID
                ) 
        LEFT JOIN
            OrderDetails o 
                ON (
                    o.OrderID = d.OrderID
                ) 
        INNER JOIN
            Shippers s 
                ON (
                    s.ShipperID = d.ShipperID
                ) 
        LEFT JOIN
            Products r 
                ON (
                    r.ProductID = o.ProductID
                ) 
        LEFT JOIN
            Categories g 
                ON (
                    g.CategoryID = r.CategoryID
                ) 
        INNER JOIN
            Employees e 
                ON (
                    e.EmployeeID = d.EmployeeID
                ) 
        WHERE
            s.ShipperName = 'Speedy Express' 
            AND (
                (
                    e.lastName = 'Peacock' 
                    AND e.firstName = 'Margaret'
                )
            ) 
            AND EXTRACT(YEAR_MONTH 
        FROM
            d.OrderDate) = 199607) 
    UNION
    DISTINCT (SELECT
        c.CustomerName AS c_customername,
        c.ContactName AS c_contactname,
        c.Address AS c_address,
        c.City AS c_city,
        c.PostalCode AS c_postalcode,
        c.Country AS c_country,
        o.OrderDetailID AS o_orderdetailid,
        s.Phone AS s_phone,
        r.ProductName AS r_productname,
        r.Price AS r_price,
        o.Quantity AS o_quantity,
        g.CategoryName AS g_categoryname 
    FROM
        Customers c 
    JOIN
        Orders d 
            ON (c.CustomerID = d.CustomerID) 
    LEFT JOIN
        OrderDetails o 
            ON (o.OrderID = d.OrderID) 
    INNER JOIN
        Shippers s 
            ON (s.ShipperID = d.ShipperID) 
    LEFT JOIN
        Products r 
            ON (r.ProductID = o.ProductID) 
    LEFT JOIN
        Categories g 
            ON (g.CategoryID = r.CategoryID) 
    INNER JOIN
        Employees e 
            ON (e.EmployeeID = d.EmployeeID) 
    WHERE
        s.ShipperName = 'Speedy Express' 
        AND ((e.LastName = 'Davolio' 
        AND e.FirstName = 'Nancy')) 
        AND EXTRACT(YEAR_MONTH 
    FROM
        d.OrderDate) = 199607)
) AS union1

Related Articles



* original question posted on StackOverflow here.