I need to run a query that selects data from three tables. The “first” of the three is a timescaledb hypertable.
I have “organized” my query into three parts. If I run any of the three parts separately, the results are fetched immidately. However, if I run the three parts toghether, it takes “forever” (I let it run for 5 minutes before I cancelled it).
So, these queries run super-fast:
with "sensor" as (
select 11958 as "id"
) (
-- part 1
select "sensorId",
"timestamp",
"value"
from "SensorDataPoint",
"sensor"
where "aggregationMethodId" = 0
and "sensorId" = "sensor"."id"
and "timestamp" < '2024-03-01Z'
order by "timestamp" desc
limit 1
);
-- or
with "sensor" as (
select 11958 as "id"
)
(
-- part 2
select "sensorId",
"timestamp",
"sa"."value"::float8
from "SensorEvent"
join "StateAlias" "sa" on "sa"."id" = "stateAliasId",
"sensor"
where "sensorId" = "sensor"."id"
and "timestamp" < '2024-03-01Z'
order by "timestamp" desc
limit 1
)
union all
(
-- part 3
select "sensorId",
"timestamp",
"value"
from "ComputedSample",
"sensor"
where "sensorId" = "sensor"."id"
and "timestamp" < '2024-03-01Z'
order by "timestamp" desc
limit 1
);
but, this query (i.e. a combination of the two queries above), takes forever:
with "sensor" as (
select 11958 as "id"
) (
-- part 1
select "sensorId",
"timestamp",
"value"
from "SensorDataPoint",
"sensor"
where "aggregationMethodId" = 0
and "sensorId" = "sensor"."id"
and "timestamp" < '2024-03-01Z'
order by "timestamp" desc
limit 1
)
union all
(
-- part 2
select "sensorId",
"timestamp",
"sa"."value"::float8
from "SensorEvent"
join "StateAlias" "sa" on "sa"."id" = "stateAliasId",
"sensor"
where "sensorId" = "sensor"."id"
and "timestamp" < '2024-03-01Z'
order by "timestamp" desc
limit 1
)
union all
(
-- part 3
select "sensorId",
"timestamp",
"value"
from "ComputedSample",
"sensor"
where "sensorId" = "sensor"."id"
and "timestamp" < '2024-03-01Z'
order by "timestamp" desc
limit 1
)
Why?
How can I run a query that combines the results of these three queries, and still have the performance as if they were run separately?