After finding the right SQL query for my purposes, I realized that my query is slow.
WITH temp_table (t_col_1, t_col_2, t_col_3) AS
(
SELECT col_1 AS t_col_1, col_2 AS t_col_2, col_3 AS t_col_3
FROM actual_table
WHERE ID = 100 AND PID = 1245
)
SELECT t_col_1, t_col_2, t_col_3
FROM temp_table AS t1
WHERE t1.t_col_2 BETWEEN 1 AND 12541
AND t1.t_col_1 = (SELECT max(t2.t_col_1)
FROM temp_table AS t2
WHERE t2.t_col_1 < 15147
AND t2.t_col_2 = t1.t_col_2)
ORDER BY t1.t_col_2
The reason, why I use the query in this form is as follows:
- The SQL query is generated and used within Matlab to fetch data.
- Depending on the ID, it can happen that columns col_1 and col_2 are interchanged which is why t_col_1 = col_2 and t_col_2 = col_1. In this case the Matlab script replaces col_1 AS t_col_2 and col_2 AS t_col_1.
Is there an elegant way to accelerate the query?
Thanks in advance.