Given the table:
Column | Type | Modifiers | Storage |
---|---|---|---|
id | bigint | not null default nextval('items_id_seq'::regclass) | plain |
data | text | not null | extended |
object_id | bigint | not null | plain |
and indexes:
- "items_pkey" PRIMARY KEY, btree (id)
- "items_object_id_idx" btree (object_id)
When I execute:
SELECT *
FROM items
WHERE object_id = 123
LIMIT 1;
It returns 0 rows very quickly. However, when I execute this query with ORDER BY
, it hangs for a very long time:
SELECT *
FROM items
WHERE object_id = 123
ORDER BY id DESC -- I added the ORDER BY
LIMIT 1;
What explains this discrepancy?
Query Plans
Fast Query (without ORDER BY
)
QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------------------------------------------
Limit (cost=0.56..3.34 rows=1 width=63) (actual time=0.014..0.014 rows=0 loops=1)
-> Index Scan using items_object_id_operation_idx on items (cost=0.56..2579.16 rows=929 width=63) (actual time=0.013..0.013 rows=0 loops=1)
Index Cond: (object_id = 123::bigint)
Total runtime: 0.029 ms
Slow query (with the ORDER BY
)
QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------------------------------------------
Limit (cost=0.44..1269.14 rows=1 width=63) (actual time=873796.061..873796.061 rows=0 loops=1)
-> Index Scan Backward using items_pkey on items (cost=0.44..1164670.11 rows=918 width=63) (actual time=873796.059..873796.059 rows=0 loops=1)
Filter: (object_id = 123::bigint)
Rows Removed by Filter: 27942522
Total runtime: 873796.113 ms