Mysql Query Optimization: LIMIT 1 Avoid full table scanning to improve query efficiency _mysql

Source: Internet
Author: User
In some cases, using limit 1 in SQL statements can improve query efficiency if you know that only one query results.
For example, the following user table (primary key ID, mailbox, password):
Copy Code code as follows:

CREATE TABLE T_user (
ID int primary KEY auto_increment,
Email varchar (255),
Password varchar (255)
);

Each user's email is unique, if users use email as a user name landing, you need to check out the corresponding email a record.
SELECT * from T_user WHERE email=?;
The above statement implements a query email corresponding to a user information, but because the email this column is not indexed, will result in a full table scan, inefficient.
SELECT * from T_user WHERE email=? LIMIT 1;
Plus limit 1, as long as you find a corresponding record, it will not continue to scan downward, the efficiency will be greatly improved.
LIMIT 1 applies to SQL statements where the query result is 1 (or 0) that results in a full table scan.
If the email is indexed, you do not need to add limit 1, if it is based on the primary key query a record does not need limit 1, the primary key is also index.
For example:
SELECT * from T_user WHERE id=?;
There is no need to write:
SELECT * from T_user WHERE id=? LIMIT 1;
There is no difference in efficiency.
Attached to the experiment I did:
Stored procedure generates 1 million data:
Copy Code code as follows:

BEGIN
DECLARE i INT;
START TRANSACTION;
SET i=0;
While i<1000000 do
INSERT into T_user VALUES (Null,concat (i+1, ' @xxg. com '), i+1);
SET i=i+1;
End while;
COMMIT;
End

Query statement
Copy Code code as follows:

SELECT * from T_user WHERE email= ' 222@xxg.com '; Time-consuming 0.56 S
SELECT * from T_user WHERE email= ' 222@xxg.com ' LIMIT 1; Time-consuming 0.00 S

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.