When LIMIT Doesn't Make Queries Fast in PostgreSQL

I thought LIMIT makes queries fast… until it didn’t I used to think: If I add LIMIT 10, the query should be fast. But in one case, even with LIMIT, the query was still slow. So I checked EXPLAIN ANALYZE. What I saw was something like: Limit → Sort → Join → Seq Scan Which basically means the database was: * scanning a large dataset * doing joins * sorting everything * and only then applying LIMIT So LIMIT was just reducing the output, not the actual work. That’s when it clicked for me: LIMIT helps only when it’s applied early. Something like: Index Scan → Limit Here: * database reads already sorted/indexed data * stops early * avoids unnecessary processing In my case, the fix was pretty straightforward: * added index on ORDER BY column * adjusted the query so sorting could use the index * reduced the amount of data before sorting After that, the plan changed and performance improved. One small learning from this: LIMIT doesn’t make a query fast by default it depends on how the query is executed Curious if you’ve seen similar cases where LIMIT didn’t help at all. #PostgreSQL #BackendEngineering #DatabasePerformance #SystemDesign #PerformanceOptimization #QueryOptimization

To view or add a comment, sign in

Explore content categories