This is my victim query
SELECT *,
lag(quantity)
over (partition by product_id, size_id, warehouse_id order by size_id, warehouse_id, created_at ASC) -
quantity as orders
FROM stocks
WHERE check_id in (SELECT check_id
FROM stocks_check_ids
WHERE product_id IN (123451249)
ORDER BY created_at DESC)
It takes up to 32 seconds execution time [QUERY PLAN]
This subquery
SELECT check_id
FROM stocks_check_ids
WHERE product_id IN (123451249)
ORDER BY created_at DESC
Returns 6 rows with less than 0.4ms [QUERY PLAN]
948cbe16-148f-46bf-900b-6775fdafaf6a
61f60a06-3e25-437f-b09f-5183a9f60076
eec338f9-3548-4f37-93fa-1b5e454ad08e
7506bd20-b5a6-403c-a460-91a425a2a038
4dbad9a9-3036-4204-baad-e1f4927487cb
2db3cffd-255a-48ab-b2d9-5f29d2592973
If i switch my subquery to these rows, like this
SELECT *,
lag(quantity)
over (partition by product_id, size_id, warehouse_id order by size_id, warehouse_id, created_at ASC) -
quantity as orders
FROM stocks
WHERE check_id in ('948cbe16-148f-46bf-900b-6775fdafaf6a',
'61f60a06-3e25-437f-b09f-5183a9f60076',
'eec338f9-3548-4f37-93fa-1b5e454ad08e',
'7506bd20-b5a6-403c-a460-91a425a2a038',
'4dbad9a9-3036-4204-baad-e1f4927487cb',
'2db3cffd-255a-48ab-b2d9-5f29d2592973')
then it takes up to 68ms [QUERY PLAN]
What am i doing wrong?
32 seconds VS 68 milliseconds Why there is a such big difference in query plan?
order by
in the subquery? Care to post the table and index definitions?