[Solved] Why is adding sorted columns to an index not making it more efficient?

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:
CREATE INDEX cars_idx_sales_state_price ON "cars" ("sales_state","price");
The optimized query:
SELECT
        "cars"."id" 
    FROM
        de."cars" 
    WHERE
        "cars"."sales_state" = 'onsale' 
        AND (
            cars.is_disabled IS NOT TRUE
        ) 
        AND (
            cars.price >= 35920
        ) 
        AND (
            cars.price <= 659880
        ) 
        AND (
            "cars"."featuring_score" IS NOT NULL
        ) 
    ORDER BY
        CASE 
            WHEN cars.featuring_score < 'C' THEN 1 
            WHEN cars.featuring_score = 'C' THEN 2 
            WHEN cars.featuring_score > 'C' THEN 3 
            ELSE 4 END,
CASE 
    WHEN cars.au_rating >= 3 THEN 1 
    WHEN cars.au_rating = 0 THEN 2 
    WHEN cars.au_rating = 2 THEN 3 
    WHEN cars.au_rating = 1 THEN 4 
    ELSE 6 END,
CASE cars.brand 
    WHEN 'Audi' THEN 1 
    WHEN 'Alpina' THEN 2 
    WHEN 'Artega' THEN 3 
    WHEN 'BMW' THEN 4 
    WHEN 'Maybach' THEN 5 
    ELSE 6 END ASC,
CASE 
    WHEN ABS(cars.price - 347900) < cars.price * 0.2 THEN 1 
    WHEN ABS(cars.price - 347900) < cars.price * 0.4 THEN 2 
    WHEN ABS(cars.price - 347900) < cars.price * 0.6 THEN 3 
    ELSE 4 END,
CASE 
    WHEN de."cars".images_count = 0 
    OR de."cars".images_count IS NULL THEN 1 
    ELSE 0 END,
ABS(cars.price - 347900) LIMIT 61

Related Articles



* original question posted on StackOverflow here.