[Solved] PostgreSQL 9.3 on Ubuntu Server 12.04 v.s. MS SQL Server 2008 R2 on Windows 7 Ultima

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. Avoid Calling Functions With Indexed Columns (query line: 43): When a function is used directly on an indexed column, the database's optimizer won’t be able to use the index. For example, if the column `created_date` is indexed, the index won’t be used as it’s wrapped with the function `to_char`. If you can’t find an alternative condition that won’t use a function call, a possible solution is to store the required value in a new indexed column.
  2. Avoid Subqueries (query line: 4): We advise against using subqueries as they are not optimized well by the optimizer. Therefore, it's recommended to join a newly created temporary table that holds the data, which also includes the relevant search index.
  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.
  4. Index Function Calls Using Generated Columns (modified query below): When a function is used directly on an indexed column, the database's optimizer won’t be able to use the index to optimize the search. Creating and indexing a generated column (supported in MySQL 5.7) will allow MySQL to optimize the search.
  5. Use Numeric Column Types For Numeric Values (query line: 14): Referencing a numeric value (e.g. 1) 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.
  6. Use Numeric Column Types For Numeric Values (query line: 29): Referencing a numeric value (e.g. 1) 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.
Optimal indexes for this query:
CREATE INDEX counters_idx_counter_name_item_id ON counters (counter_name,item_id);
CREATE INDEX gourmet_idx_status ON gourmet (status);
CREATE INDEX photos_idx_main_photo_folder_id ON photos (main_photo,folder_id);
The optimized query:
SELECT
        count(*) 
    FROM
        (SELECT
            a.gourmet_id item_id,
            a.gourmet_name_c item_name,
            a.vendor_url external_url,
            'fnf-item.aspx?pid=' || a.gourmet_id fun_taiwan_url,
            b.photo_id,
            coalesce(SUM(c.total_hit),
            0) hit_count,
            to_char(a.created_date,
            'YYYY/MM/DD HH24:MI:SS') created_date,
            '1' is_gourmet,
            a.for_search_only,
            a.area_code || '-' || a.tel_no tel_no,
            a.tel_ext,
            a.county,
            a.town,
            a.address_c,
            'gourmet.png' icon_name,
            now() AS updated_date,
            'NonOrderScheduler' AS updated_by 
        FROM
            gourmet a 
        LEFT JOIN
            photos b 
                ON b.folder_id = a.gourmet_id 
                AND b.main_photo = '1' 
        LEFT JOIN
            counters c 
                ON c.item_id = a.gourmet_id 
                AND c.counter_name = 'FnfHit' 
        WHERE
            a.status = 'A' 
        GROUP BY
            a.gourmet_id,
            a.gourmet_name_c,
            a.length_vendor_url,
            a.vendor_url,
            'fnf-item.aspx?pid=' || a.gourmet_id,
            b.photo_id,
            to_char(a.created_date,
            'YYYY/MM/DD HH24:MI:SS'),
            a.for_search_only,
            a.area_code || '-' || a.tel_no,
            a.tel_ext,
            a.county,
            a.town,
            a.address_c) t

Related Articles



* original question posted on StackOverflow here.