0

I have a query that is taking over 30 seconds to run and is causing delays in our application. I've tried indexing the tables and adjusting the query structure, but it's still slow. Are there any other optimization techniques I can use to speed up the query?

Thank you.

SELECT
    orders.order_id,
    orders.order_date,
    customers.customer_name,
    products.product_name,
    order_details.quantity,
    order_details.unit_price
FROM
    orders
JOIN
    customers ON orders.customer_id = customers.customer_id
JOIN
    order_details ON orders.order_id = order_details.order_id
JOIN
    products ON order_details.product_id = products.product_id
WHERE
    orders.order_date >= '2022-01-01'
    AND products.category = 'Electronics'
ORDER BY
    orders.order_date DESC;

ERROR: Query timeout expired. The query took more than 30 seconds to execute.

10
  • 2
    Please update your question with the EXPLAIN PLAN for your query Commented Nov 29, 2023 at 17:49
  • 1) Please copy the result of the explain into the question. 2) Please describe what indexes you have defined on your impacted tables. Commented Nov 29, 2023 at 17:49
  • 3
    please edit your question to add (as text, not images) ouptut of explain select...rest of your query and of show create table yourtablename for all the tables used in the query; this is the minimum information needed to get good answers to optimization questions Commented Nov 29, 2023 at 18:27
  • 2
    @p3consulting, That's not a problem. Date literals are strings. See dev.mysql.com/doc/refman/8.0/en/date-and-time-literals.html Commented Nov 29, 2023 at 18:46
  • 1
    @p3consulting, That syntax is not needed in MySQL. A quoted string that contains a date is automatically cast to a date value when it is compared to a date. Try it! Commented Nov 29, 2023 at 19:11

1 Answer 1

0

These composite indexes may help:

orders:  INDEX(order_date, customer_id,  order_id)
customers:  INDEX(customer_id,  customer_name)
products:  INDEX(category, product_id,  product_name)

If not, please provide `SHOW CREATE TABLE for each table so we can di deeper.

(And, I agree that orders.order_date >= '2022-01-01' is fine.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.