Comparison of Methods for determining whether a record exists in MySQL

Source: Internet
Author: User

I have summarized the common methods for determining whether a record exists:

SQL statement: Select count (*) from tablename;

Then read the value of Count (*) to determine whether the record exists. The performance of this method is a waste. We just want to determine whether the record exists, and it is not necessary to check all the records.

The following method is recommended.

SQL statement: select 1 from tablename where Col = Col limit 1;

Then read the number of rows affected by statement execution.

Of course, here limit 1 is very important. This requires MySQL to find a record and it will not be searched down. The number of rows affected by the execution is either 0 or 1, and the performance has improved a lot.

If you are using PDO, you can use rowcount () to easily reach the number of rows affected by the execution.

Some people may read the records queried by SQL statements, and then judge whether the records exist to determine whether the records exist. This method is feasible, but it is still a waste for our requirements. We do not need to query the records, and all performance loss will occur. This is not recommended.

Related Article

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.