[Solved] SQL query - issue with WHERE statement

EverSQL Database Performance Knowledge Base

SQL query - issue with WHERE statement

I have this query, which is made from snippets/ideas around here - I am not an expert in the more advanced SQL yet. The part I want you to focus on is: WHERE ... l.status='active'

SELECT l.*, COUNT(c.id) AS callsNum 
FROM leads AS l 
LEFT JOIN calls AS c ON c.lead = l.id
WHERE l.pool IN ($pools) AND l.status='active' AND l.center='$center'
GROUP BY l.id
ORDER BY callsNum ASC, l.id ASC
LIMIT 0,1

I can't get the error myself, but some people has experienced errors where leads with a status that is not "active" has come up.

Can anyone spot the error? I suppose the code can be better too, any suggestions are welcome - if it ain't clear what the code is supposed to do, feel free to ask.

UPDATE:

Thanks for all your responses. I'm glad you think the query should work. I suppose I need to add some more info.

The system is for a small callcenter. The query is getting the next lead from the selected pools, that the caller should call to. In the same AJAX call to the PHP file the "next lead" gets marked as "processing" to avoid multiple callers getting the samme lead.

As pointed out the problem could technically happen if two callers pressed the "get next lead" button on the exact same time. But they have reported to me, that even if they are just 2 callers calling on the same pools at the same time, they get the same lead quite often. If they are 4 callers, even more often.

I therefore put in some lines of code just after this query, that checks one more time that the lead has status='active' - and if not, it comes up with an error (to prevent multiple callers calling at the same time). This error comes quite often, and I therefore suspect that something is wrong with this query.

It is very important that a lead won't come up multiple times. Any suggestions?

RELEVANT CODE (FULL)

Here is a longer code example as requested. The error in the end comes up quite often with just 2-4 persons using it (on a quite fast server).

// Get next lead
$stmt = $db->prepare("
    SELECT l.*, COUNT(c.id) AS callsNum 
    FROM leads AS l 
    LEFT JOIN calls AS c ON c.lead = l.id
    WHERE l.pool IN ($pools) AND l.status='active' AND l.center='$center'
    GROUP BY l.id
    ORDER BY callsNum ASC, l.id ASC
    LIMIT 0,1");
$stmt->execute();
$res = $stmt->get_result(); 

if($res->num_rows > 0) {

    while($row = $res->fetch_assoc()) {

        // Set as "processing" to avoid simultaneous call from multiple bookers 
        $stmt = $db->prepare("UPDATE leads SET status='processing' WHERE status='active' AND id=? AND center='$center'");
        $stmt->bind_param("i", $row["id"]);
        $stmt->execute();
        $affectedRows = $stmt->affected_rows;
        if($affectedRows != 1) {
            echo 'ERROR. Please reload.';
            die;
        }

    }
}

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Avoid OFFSET In LIMIT Clause (query line: 19): OFFSET clauses can be very slow when used with high offsets (e.g. with high page numbers when implementing paging). Instead, use the following \u003ca target\u003d"_blank" href\u003d"http://www.eversql.com/faster-pagination-in-mysql-why-order-by-with-limit-and-offset-is-slow/"\u003eseek method\u003c/a\u003e, which provides better and more stable response rates.
  2. Avoid Selecting Unnecessary Columns (query line: 2): Avoid selecting all columns with the '*' wildcard, unless you intend to use them all. Selecting redundant columns may result in unnecessary performance degradation.
  3. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
Optimal indexes for this query:
ALTER TABLE `calls` ADD INDEX `calls_idx_lead` (`lead`);
ALTER TABLE `leads` ADD INDEX `leads_idx_status_center_pool_id` (`status`,`center`,`pool`,`id`);
The optimized query:
SELECT
        l.*,
        COUNT(c.id) AS callsNum 
    FROM
        leads AS l 
    LEFT JOIN
        calls AS c 
            ON c.lead = l.id 
    WHERE
        l.pool IN (
            $pools
        ) 
        AND l.status = 'active' 
        AND l.center = '$center' 
    GROUP BY
        l.id 
    ORDER BY
        callsNum ASC,
        l.id ASC LIMIT 0,
        1

Related Articles



* original question posted on StackOverflow here.