My Task is to optimize a query, which should check for data inconsistency: Return all leads ids with more than one entries and multiple is_first flag.
| id | lead_id | is_first| (other data) |
|----|---------|---------|-------- ...
| 1| 20| 1|...
| 2| 20| 0|
| 3| 21| 1|
| 4| 21| 0|
| 5| 21| 1|
| 6| 22| 1|
So this dataset should return 21. (20 ok, because is_first is only true/1 once)
Old Query:
SELECT DISTINCT s1.lead_id as lead_id
FROM history as s1
INNER JOIN history as s2 ON
s1.is_first = 1 AND
s2.is_first = 1 AND
s1.id != s2.id AND
s1.lead_id = s2.lead_id;
New Query: I already increased performance somewhat with this query
SELECT history.lead_id AS lead_id
FROM history
WHERE is_first = 1 GROUP BY lead_id
HAVING count(lead_id) != 1;
But I feel it's not end of the line. Any recommendations?
HAVING count(lead_id) > 1
as count cannot have a value <=0. Can you post the actual schema including indexes and the query plan so we can work out if there is anything else that is possible on the dataset.