且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将查询限制为一条记录可提高性能

更新时间:2023-01-29 08:50:56

如果列有



唯一索引:否,不会更快



非唯一索引:




  • 如果1行或更多行符合查询,因为全表扫描将在第一行匹配后暂停

  • 如果没有符合查询的行 ,因为它需要完成全表扫描


Will limiting a query to one result record, improve performance in a large(ish) MySQL table if the table only has one matching result?

for example

 select * from people where name = "Re0sless" limit 1

if there is only one record with that name? and what about if name was the primary key/ set to unique? and is it worth updating the query or will the gain be minimal?

If the column has

a unique index: no, it's no faster

a non-unique index: maybe, because it will prevent sending any additional rows beyond the first matched, if any exist

no index: sometimes

  • if 1 or more rows match the query, yes, because the full table scan will be halted after the first row is matched.
  • if no rows match the query, no, because it will need to complete a full table scan