[Solved] Querying large data in Yii?

EverSQL Database Performance Knowledge Base

Querying large data in Yii?

Database type:

I am using MySQL database for an application in Yii. The database contains both small (like storing user details) and large tables (storing large invoice data). I have join queries to fetch data from the large tables and that makes site very slow. So I enabled MySQL query cache to improve the performance. But that is not a permanent solution. After everyday, the data become very huge. Is there any suggestions to improve the performance? Is there any other db which can integrate with Yii to handle large data queries?

Here is the query,

SELECT u.accountnumber, u.chargedescription, ROUND(SUM(u.netamount), 2) as cost, p.value, p.price FROM `reports` `u` JOIN `reportsdata` `p` ON u.trackingnumber=p.value WHERE chargedescriptioncode='003' GROUP BY `u`.`trackingnumber` 

"reports" and "reportsdata" both are large data tables. Both are joined with trackingnumber which is a huge list. So, whenever the trackingnumber become huge, the query lags and kills the cpu execution time.

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. Explicitly ORDER BY After GROUP BY (modified query below): By default, the database sorts all 'GROUP BY col1, col2, ...' queries as if you specified 'ORDER BY col1, col2, ...' in the query as well. If a query includes a GROUP BY clause but you want to avoid the overhead of sorting the result, you can suppress sorting by specifying 'ORDER BY NULL'.
  2. Use Numeric Column Types For Numeric Values (query line: 14): Referencing a numeric value (e.g. 003) as a string in a WHERE clause might result in poor performance. Possible impacts of storing numbers as varchars: more space will be used, you won't be able to perform arithmetic operations, the data won't be self-validated, aggregation functions like SUM won't work, the output may sort incorrectly and more. If the column is numeric, remove the quotes from the constant value, to make sure a numeric comparison is done.
The optimized query:
SELECT
        u.accountnumber,
        u.chargedescription,
        ROUND(SUM(u.netamount),
        2) AS cost,
        p.value,
        p.price 
    FROM
        `reports` `u` 
    JOIN
        `reportsdata` `p` 
            ON u.trackingnumber = p.value 
    WHERE
        chargedescriptioncode = '003' 
    GROUP BY
        `u`.`trackingnumber` 
    ORDER BY
        NULL

Related Articles



* original question posted on StackOverflow here.