Search code examples
sqlpostgresql

When a SQL LIMIT clause executes? (Postgresql)


I'm using Postgres. Suppose I have only one record that satisfies the query parameters. My friend claims that I can speed up query completion if I use limit=1; This is true? GPT Chat also states that the database will stop searching once the limit is met. But I couldn't find any confirmation by googling.

I was also sure that the limit is applied only at the very end of the query execution, after the records have been formed.


Solution

  • I comcur with Tim that LIMIT without ORDER BY is pretty meaningless. Also, LIMIT is normally executed as the last step of the query (but it will keep subsequent results from being computed).

    Anyway, while adding LIMIT to a query that has only a single result row won't change the query result, it can influence the way in which PostgreSQL computes the result, so it can influence the performance of the query (the execution plan). With LIMIT, PostgreSQL will prefer execution plans that return the first rows quickly.

    If everything is as it should be, PostgreSQL will estimate the result row count correctly and choose the best execution plan, regardless if you use LIMIT or not. But the optimizer can get it wrong, and then the LIMIT can be a hint to get it on the right track.

    In case of doubt, examine the execution plans with EXPLAIN.