[Solved] SQL add rows count from a second table to the main query

EverSQL Database Performance Knowledge Base

SQL add rows count from a second table to the main query

I'm trying to improve a (not so much) simple query:

Something like:

SELECT a.*,
       (SELECT Count(*)
        FROM   table_c c
        WHERE  c.a_id = a.id) AS counter,
       b.*
FROM   table_a a
       LEFT JOIN table_b b
              ON b.a_id = a.id  

This works, ok, but in reality, I'm just making 2 queries and I need to improve this so it only do one (if, its even possible).

Anyone knows how can I achive that?

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 Correlated Subqueries In Select Clause (modified query below): The aggregation function located in a subquery inside the SELECT clause, is executed once for every matched row. Extracting this subquery to a temporary table will improve performance significantly.
  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 `es_temp1` ADD INDEX `es_temp1_idx_a_id` (`a_id`);
ALTER TABLE `table_b` ADD INDEX `table_b_idx_a_id` (`a_id`);
The optimized query:
SELECT
        a.*,
        es_temp1.counter,
        b.* 
    FROM
        table_a a 
    LEFT JOIN
        table_b b 
            ON b.a_id = a.id 
    LEFT JOIN
        es_temp1 
            ON es_temp1.a_id = a.id

Related Articles



* original question posted on StackOverflow here.