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:
- Description of the steps you can take to speed up the query.
- The optimal indexes for this query, which you can copy and create in your database.
- An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
- 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.
- 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.
- Prefer Direct Join Over Joined Subquery (query line: 7): We advise against using subqueries as they are not optimized well by the optimizer. Therefore, we recommend to replace subqueries with JOIN clauses.
- Prefer Direct Join Over Joined Subquery (query line: 20): We advise against using subqueries as they are not optimized well by the optimizer. Therefore, we recommend to replace subqueries with JOIN clauses.
- Prefer Inner Join Over Left Join (modified query below): We identified that one or more left joined entities (e.g. `o1`) are used in the 'where' clause, in a way that allows to replace it with an optimized inner join. Inner joins can be fully optimized by the database, while Left joins apply limitations on the database's optimizer.
- Prefer Inner Join Over Left Join (modified query below): We identified that one or more left joined entities (e.g. `o2`) are used in the 'where' clause, in a way that allows to replace it with an optimized inner join. Inner joins can be fully optimized by the database, while Left joins apply limitations on the database's optimizer.
- Prefer Sorting/Grouping By The First Table In Join Order (modified query below): The database can use indexes more efficiently when sorting and grouping using columns from the first table in the join order. The first table is determined based on the prediction of the the optimal first table, and is not necessarily the first table shown in the FROM clause.
Optimal indexes for this query:
CREATE INDEX cust_orders_idx_order_id ON cust_orders (order_id);
CREATE INDEX order_info_idx_status_order_id ON order_info (status,order_id);
The optimized query:
SELECT
*
FROM
cust_orders AS co
INNER JOIN
order_info AS o1
ON o1.order_id = co.order_id
INNER JOIN
order_info AS o2
ON o2.order_id = co.order_id
WHERE
(
(
o1.order_id IS NOT NULL
AND o2.order_id IS NOT NULL
)
AND (
o1.pay_type IN (
'prepay', '10n30'
)
AND o1.status = 'open'
)
)
AND (
o2.pay_type NOT IN (
'prepay', '10n30'
)
AND o2.status = 'open'
)
ORDER BY
o1.order_id DESC