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:
- 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 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 performance_points_idx_date ON "performance_points" ("date");
CREATE INDEX performance_points_idx_id_user_id ON "performance_points" ("id","user_id");
CREATE INDEX team_memberships_idx_team_id_user_id ON "team_memberships" ("team_id","user_id");
CREATE INDEX users_idx_id ON "users" ("id");
The optimized query:
SUM(pp.points) AS total
ON pp.user_id = u.id
ON tm.team_id = pp.team_id
AND tm.user_id = pp.user_id
pp.date > '2015-08-02 13:57:14.042221'
total DESC LIMIT 50