Edited: Sorry I forgot to add an important condition value1 - value 2 <> 0;
. Without it result have ~111k records. And as I rewrite query using CTE go get set of code(s) in max date to join with main table it seems index can't help my case, i think.
--==================================
We have a query (a CTE) that get records with latest date.
For one of worst cases, this take 8.6 secs to get 11k rows.
Table table_name
has 3.1 mil rows.
For now this query use full table scan. I try but cannot find an index to add to use in this query. Could anyone have a way to tune it?
--sample - one of worse cases
p_filter_code_1 VARCHAR2(200) := ' ';
p_filter_code2 VARCHAR2(10) := ' ';
p_filter_code3 VARCHAR2(10) := ' ';
p_filter_code4 VARCHAR2(10) := ' ';
p_filter_code5 VARCHAR2(10) := ' ';
p_filter_start_date NUMBER := 20170101;
p_filter_end_date NUMBER := 20171231;
--===============
SELECT code_2, code_3, code_4, code5
value1, value2
FROM (
SELECT t.*,
ROW_NUMBER() OVER (PARTITION BY code_1, code_2, code_3, code_4, code_5 ORDER BY date_col DESC) AS rn
FROM table_name t
WHERE
(
code_1 IN (SELECT code_1 FROM temp_code)
)
AND date_col < p_filter_start_date
AND (code_2 LIKE p_filter_code2 OR p_filter_code2 = ' ')
AND (code_3 LIKE p_filter_code3 OR p_filter_code3 = ' ')
AND (code_4 = p_filter_code4 OR p_filter_code4 = ' ')
AND (code_5 = p_filter_code5 OR p_filter_code5 = ' ')
)
WHERE rn = 1 AND value1 - value 2 <> 0;
This is sample value for code_1_table and temp_code with filter from user: '1002,1020-1025,1030,1040-1050' (like print pages in word)
code_1_table (sample)
code_1 code_1_name
1001 test
1002 x..
1023 .sona
1025 .sojj
1026 .oifhal
temp_code sample records with p_filter_code_1 := '1002,1020-1025,1030,1040-1050'
code_1
1002
1023
1025
CREATE TABLE table_name
(code_1 VARCHAR2(10 BYTE) ,
code_2 VARCHAR2(20 BYTE) ,
code_3 VARCHAR2(20 BYTE) ,
code_4 VARCHAR2(25 BYTE) ,
code_5 VARCHAR2(25 BYTE) ,
value1 NUMBER,
value2 NUMBER,
value3 NUMBER,
value4 NUMBER,
date_col NUMBER )
ALTER TABLE table_name
ADD CONSTRAINT table_name_p
PRIMARY KEY (code_1, code_2, code_3, code_4, code_5, date_col)
/