I have the following query selecting everything from the notes table where the input(ex: bob) is not in the orders table.
SELECT * FROM `notes` WHERE notes.customer_email NOT IN
(SELECT customers_email_address FROM orders)
AND ((customer_phone LIKE '%bob%')
OR (customer_name LIKE '%bob%')
OR (customer_email LIKE '%bob%'))
AND customers_id IS NULL
GROUP BY `customer_email`
ORDER BY `customer_name`
DESC LIMIT 50
This fat boy of a query is taking ~80 seconds on my dev machine and ~7 seconds on the live server.
Two questions:
- What did I do wrong with this query? (I need to learn from my mistakes)
- How can I improve this query?
Try to use a join:
they are usually faster than the IN/NOT IN clause. And also, I am not sure why you put a group by clause here.