▲ | dotancohen 14 hours ago | ||||||||||||||||||||||||||||||||||||||||
I've been told similar nasty things for adding LIMIT 1 to queries that I expect to return at most a single result, such as querying for an ID. But on large tables (at least in sqlite, mysql, and maybe postgress too) the database will continue to search the entire table after the given record was found. | |||||||||||||||||||||||||||||||||||||||||
▲ | Guillaume86 12 hours ago | parent | next [-] | ||||||||||||||||||||||||||||||||||||||||
Only if your table is missing an unique index on that column, which it should have to enforce your assumption, so yeah LIMIT 1 is a code (or schema in the case) smell. | |||||||||||||||||||||||||||||||||||||||||
| |||||||||||||||||||||||||||||||||||||||||
▲ | sgarland 6 hours ago | parent | prev | next [-] | ||||||||||||||||||||||||||||||||||||||||
If you include an ORDER BY, the DB _may_ continue searching. MySQL (and, I assume, MS SQL Server, since it also can cluster the PK) can stop early in some circumstances. But if you just have a LIMIT, then no - any RDBMS should stop as soon as it’s reached your requested limit. | |||||||||||||||||||||||||||||||||||||||||
| |||||||||||||||||||||||||||||||||||||||||
▲ | fipar 2 hours ago | parent | prev | next [-] | ||||||||||||||||||||||||||||||||||||||||
In mysql, the db will continue reading even if the limit condition has been met, and then anything beyond the limit will be discarded before returning the result. | |||||||||||||||||||||||||||||||||||||||||
▲ | giovannibonetti 9 hours ago | parent | prev [-] | ||||||||||||||||||||||||||||||||||||||||
I've noticed that LIMIT 1 makes a huge difference when working with LATERAL JOINs in Postgres, even when the WHERE condition has a unique constraint. |