I have the following query:
SELECT
id,
RANK() OVER (
PARTITION BY user_id
ORDER BY
effective_date <= '${date}' DESC,
effective_date DESC,
created_at DESC
) AS rank
FROM $table WHERE company_id = $companyId AND effective_date <= $date;
I want to add an index on the table to speed the performance of the query.
My guess is having a composite index on (company_id, effective_date) would help. However I wanted also to add the user_id column as part of an index.
So my question is: Should I use a single index on (company_id, effective_date, user_id)? Will having the userId as the last part of the composite index help the performance of PARTITION BY user_id
OR should I add a separate index on UserID only? Or it does not matter as it will not help at all?
Also worth mentioning: there are also a few queries that do not use ranks and partition and the where filter is applied only on company_id and user_id. For that case the best index option would be (company_id, user_id). However the most of the time the first query is used, so improving the performance of that query would be the most important thing to achieve.