Sample data from my table test_table
:
date symbol value created_time
2010-01-09 symbol1 101 3847474847
2010-01-10 symbol1 102 3847474847
2010-01-10 symbol1 102.5 3847475500
2010-01-10 symbol2 204 3847474847
2010-01-11 symbol1 109 3847474847
2010-01-12 symbol1 105 3847474847
2010-01-12 symbol2 206 3847474847
Given the table above, I am trying to find the optimal index to put on the table (date, symbol, value and created_time should combined be unique) and the query to go along with it to return the following:
date symbol value created_time
2010-01-09 symbol1 101 3847474847
2010-01-10 symbol1 102.5 3847475500
2010-01-10 symbol2 204 3847474847
2010-01-11 symbol1 109 3847474847
2010-01-12 symbol1 105 3847474847
2010-01-12 symbol2 206 3847474847
I am looking for date, symbol, value columns of data for each group of those three with the maximum created_time column (essentially row 1, 3, 4, 5, 6, 7 in the example above returned).
Currently I have tried this index...
CREATE UNIQUE INDEX "test_table_date_symbol_value_created_time"
ON "test_table" USING btree (date, symbol, value, created_time)
And am using this query. Not sure if it is the most effective way, it still seems pretty slow.
select *
from(
select date,
symbol,
value,
created_time,
max(created_time) over (partition by date, symbol) as max_created_time
from "test_table"
) t
where symbol in ('symbol1', 'symbol2') and created_time = max_created_time