Witam,
Musze na zalozyc index na takie zapytanie:
SELECT *
FROM orders
WHERE user_id = 1 AND record_type = 'ORDER'
ORDER BY order_date;
Czy taki index ma sens:
CREATE INDEX ix_orders_first_purchase_date
ON orders (user_id, record_type);
Witam,
Musze na zalozyc index na takie zapytanie:
SELECT *
FROM orders
WHERE user_id = 1 AND record_type = 'ORDER'
ORDER BY order_date;
Czy taki index ma sens:
CREATE INDEX ix_orders_first_purchase_date
ON orders (user_id, record_type);
Nie wiadomo czy ma sens, bo nie znamy rozkładu danych w kolumnach.
Dodatkowo jak sortujesz w tym zapytaniu, to indeks mógłby zawierać datę i silnik mógłby z tego skorzystać. Obejrzyj plan zapytanie bez indeksu, z indeksem, z indeksem zawierającym datę.
Załóż dwa index. Osobno na koażde z tych pól (user i record_type). Z tego co pamietam, to rekord type ma mało różnych wartości..
@Marcin.Miga: Tak, record_type
ma tylko 4 wartosci typu varchar(15)
.
@Marcin.Miga: Mam zalozony 3 indexy. Kazdy z osobna na te 3 kolumy. I takie 3 indexy beda szybciej dzialac jak jeden index z 3 kolumnami? Ciezko mi to samemu stwierdzic, bo po EXPLAIN ANALYSE
oba zapytania maja niemalze, taki sam czas wykonania.
11.5. Combining Multiple Indexes
A single index scan can only use query clauses that use the index's columns with operators of its operator class and are joined with AND. For >example, given an index on (a, b) a query condition like WHERE a = 5 AND b = 6 could use the index, but a query like WHERE a = 5 OR b = 6 could >not directly use the index.
Fortunately, PostgreSQL has the ability to combine multiple indexes (including multiple uses of the same index) to handle cases that cannot be >implemented by single index scans. The system can form AND and OR conditions across several index scans. For example, a query like WHERE x = >42 OR x = 47 OR x = 53 OR x = 99 could be broken down into four separate scans of an index on x, each scan using one of the query clauses. The >results of these scans are then ORed together to produce the result. Another example is that if we have separate indexes on x and y, one possible >implementation of a query like WHERE x = 5 AND y = 6 is to use each index with the appropriate query clause and then AND together the index >results to identify the result rows.
https://www.postgresql.org/docs/9.3/indexes-bitmap-scans.html
Jak 4 wartości, to partycjonowanie po RECORD_TYPE i już masz tylko 1 partycję do ogarnięcia + wtedy indeks na user_id i datę i masz od razu posortowane ;-)
Query plany powiedzą Ci prawdę.