How to Optimize SQL query with DISTINCT and fetch first?

Viewed 29

I am trying to fetch first 5 distinct rows using the query SELECT DISTINCT col_A from table_name fetch first 5 rows only;

But the table has millions of rows so using distinct is expensive as it scans the whole table for only 5 rows taking a lot of time, around 200 seconds for me.

Is there a workaround or subquery for this?

1 Answers

The problem here is you don't know if a row is unique unless you check all the other rows. I believe your only solution would be to index the rows such that non-distinct rows are indexed together. That might buy you some efficiency when searching, however it will cost you when inserting data.

Related