[Solved] SQL Optimization: multiplication of two calculated field generated by window functions

How to optimize this SQL query?

In case you have your own slow SQL query, you can optimize it automatically here.

For the query above, the following recommendations will be helpful as part of the 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. 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 `tbl2` ADD INDEX `tbl2_idx_time` (`time`);
The optimized query:
WITH cte AS (SELECT
        t1.time,
        t1.b_value,
        t2.u_value * t1.b_value AS bu_value,
        last_value(t2.u_value) OVER (PARTITION 
    BY
        DATE_TRUNC('DAY',
        t1.time) 
    ORDER BY
        DATE_TRUNC('DAY',
        t2.time)) AS daily_u_value 
    FROM
        stackoverflow.tbl1 t1 
    LEFT JOIN
        stackoverflow.tbl2 t2 
            ON t1.time = t2.time) SELECT
            DATE_TRUNC('DAY',
            c.time) AS time,
            AVG(c.daily_u_value) AS daily_u_value,
            SUM(SUM(c.b_value)) OVER (ORDER 
    BY
        DATE_TRUNC('DAY',
        c.time)) AS b_value_cum_sum,
        AVG(c.daily_u_value) * SUM(SUM(c.b_value)) OVER (ORDER 
    BY
        DATE_TRUNC('DAY',
        c.time)) AS daily_u_value_mul_b_value 
    FROM
        cte c 
    GROUP BY
        1 
    ORDER BY
        1 DESC

Related Articles



* original question posted on StackOverflow here.