0

I have a review table which has, app_id(string), reviews_updated_at(timestamp), description(text) and other stuff. The table has around 90 million entries, I have around 2000 read IOPS limit on my database instance and the below mentioned query takes 30-40 sec to complete, Is there any way i can make this query execute faster?.

I have two indexes app_id(btree), reviews_updated_at(btree)

Query:

select * from reviews
where app_id = '2332223'
order by review_updated_at
offset 200 limit 100

Query Plan:

Limit  (cost=243270.84..364905.97 rows=100 width=258) (actual time=23212.698..32806.020 rows=100 loops=1)
  ->  Index Scan using index_reviews_on_review_updated_at on reviews  (cost=0.57..327489222.63 rows=269239 width=258) (actual time=237.720..32805.359 rows=300 loops=1)
        Filter: ((app_id)::text = '2332223'::text)
        Rows Removed by Filter: 36376
Planning time: 0.160 ms
Execution time: 32806.216 ms
9
  • To make it run faster, add a where clause so there are fewer records to sort.
    – Dan Bracuk
    Nov 5, 2015 at 18:43
  • ap_is seems to be an integer. remove the quotes -> WHERE ap_id = 2332223 (and maybe your statistics are off) Nov 5, 2015 at 18:46
  • @DanBracuk what where clause? These are the records that I want.
    – rajat
    Nov 5, 2015 at 19:48
  • @wildplasser In some cases it's integer, In others it is not. The column type is string.
    – rajat
    Nov 5, 2015 at 19:49
  • 1
    And what is the cost (in EXPLAIN) for the new index? Nov 6, 2015 at 20:50

1 Answer 1

2

For this query:

select *
from reviews
where app_id = '2332223'
order by review_updated_at
offset 200
limit 100;

The best index in reviews(app_id, review_updated_at). Actually with this index, the query should be quite fast.

Note that when comparing values, you should ensure that they are of the same type. If app_id is a string, then there should be quotes.

4
  • which values should be of the same type?
    – rajat
    Nov 5, 2015 at 20:02
  • The app_id and the value it is being compared to. Nov 5, 2015 at 22:50
  • The datatype for app_id is string, most of the app_ids in the table are strings, only some of them are numbers.
    – rajat
    Nov 6, 2015 at 7:23
  • Thanks, it's very fast now using composite index.
    – rajat
    Nov 6, 2015 at 8:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.