0

I have following query:

SELECT 
`status`, `is_client_coordinator`, id, first_name, last_name 
FROM `users` `t` 
WHERE t.status!="CLOSED" 
and t.is_client_coordinator 
or t.id in (select client_coordinator_id from projects where status not in ("DELETED", "ARCHIVED")) 
ORDER BY concat(first_name, last_name)

The explain gives this:

enter image description here

Individually queries take less than 0.1 seconds (first one 0.04 seconds and the subquery 0.07 seconds). Put together it takes more than a second to perform the query. Both status columns are the type of ENUM. What am I doing wrong here? Any advice about how to optimize the query?

asked May 1, 2020 at 15:30
2
  • 1
    could you please add create table statemets (including indexes)? Commented May 1, 2020 at 17:11
  • How many rows are you expecting in the result? Commented May 7, 2020 at 21:46

1 Answer 1

0

In order for the in clause to be evaluated, the subquery is likely being evaluated for every row. My first performance suggestion would be to use a left join and then filter:

select t.status, t.is_client_coordinator, t.id, first_name, t.last_name
from users t
left join projects p on t.client_coordinator_id = pl.id
where t.status != "CLOSED"
and t.is_client_coordinator
or (
exists(p.client_coordinator_id)
and p.status != "DELETED"
and p.status != "ARCHIVED"
)
ORDER BY concat(t.first_name, t.last_name)
answered May 1, 2020 at 16:26

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.