MySql query execution flow

To optimize the query its import to understand the execution flow of query, here is an example:

SELECT product, SUM(quantity) AS "Total quantity"
FROM order_details
JOIN orders on orders.id = order_details.id
WHERE order_details.type = 'automobile'
GROUP BY product
HAVING SUM(quantity) > 10
ORDER BY order_details.id DESC;


In the above query we will have flow like

1. FROM clause
SELECT product, SUM(quantity) AS "Total quantity"
FROM order_details
JOIN orders on orders.id = order_details.id
WHERE order_details.type = 'automobile'
GROUP BY product
HAVING SUM(quantity) > 10
ORDER BY order_details.id DESC;

2. WHERE clause
SELECT product, SUM(quantity) AS "Total quantity"
FROM order_details
JOIN orders on orders.id = order_details.id
WHERE order_details.type = 'automobile'
GROUP BY product
HAVING SUM(quantity) > 10
ORDER BY order_details.id DESC;

3. GROUP BY clause
SELECT product, SUM(quantity) AS "Total quantity"
FROM order_details
JOIN orders on orders.id = order_details.id
WHERE order_details.type = 'automobile'
GROUP BY product
HAVING SUM(quantity) > 10
ORDER BY order_details.id DESC;

4. HAVING clause
SELECT product, SUM(quantity) AS "Total quantity"
FROM order_details
JOIN orders on orders.id = order_details.id
WHERE order_details.type = 'automobile'
GROUP BY product
HAVING SUM(quantity) > 10
ORDER BY order_details.id DESC;

5. SELECT clause
SELECT product, SUM(quantity) AS "Total quantity"
FROM order_details
JOIN orders on orders.id = order_details.id
WHERE order_details.type = 'automobile'
GROUP BY product
HAVING SUM(quantity) > 10
ORDER BY order_details.id DESC;

6. ORDER BY clause
SELECT product, SUM(quantity) AS "Total quantity"
FROM order_details
JOIN orders on orders.id = order_details.id
WHERE order_details.type = 'automobile'
GROUP BY product
HAVING SUM(quantity) > 10
ORDER BY order_details.id DESC;

Leave a comment