Does using “LIMIT 1” speed up a query on a primary key?

后端 未结 2 1605
有刺的猬
有刺的猬 2021-02-19 04:23

If I have a primary key of say id and I do a simple query for the key such as,

SELECT id FROM myTable WHERE id = X

Will it find on

相关标签:
2条回答
  • 2021-02-19 04:53

    There is no need to worry about this sort of "optimization".

    Only one row will be fetched -- per unique index contract -- and the database is able to very quickly find all the (1) rows. It is able to do this because of the underlying structures that back the index (or primary key) support fast-seeking by value. There is no table-scan involved. (Generally a variant of a B-tree, but it might be hash-based, etc, is used. I suppose a smart query optimizer might also be able to pass down additional hints based on the unique constraint in effect, but I don't know enough about this.)

    0 讨论(0)
  • 2021-02-19 05:16

    Does using “LIMIT 1” speed up a query on a primary key?

    No. It's already as fast as can be without LIMIT 1. LIMIT 1 is effectively implied anyway.

    Will it find one row and then stop looking as it is a primary key

    Yes.

    No table scan should be necessary at all here: it's a key-based lookup. The matching row is found and that's the end of the procedure.

    0 讨论(0)
提交回复
热议问题