How to determine if a record exists in MySQL compare "Go"

Source: Internet
Author: User

When writing data to a database, it is often necessary to detect the existence of the record to be inserted before deciding whether to write.

Here I summarize the common methods for judging whether records exist:

SQL statement: SELECT COUNT (*) from TableName;

The value of Count (*) is then read to determine if the record exists. For this method of performance is a bit wasteful, we just want to determine whether records exist, there is no need to find out all.

The following method is recommended by me.

SQL statement: Select 1 from tablename where col = col Limit 1;

The number of rows affected by the execution of the statement is then read.

Of course, the limit 1 here is important. This will not be looking down after MySQL finds a record. The number of rows affected by this execution is either 0 or 1, and performance has improved a lot.

If you are using PDO, you can use ROWCOUNT () and it is easy to execute the number of rows affected.

There are also people who might read the records queried by the SQL statement, and then determine if the record exists, and then determine if the record exists. This method is feasible, but for our requirements, there is some waste, we do not need to query the records, all the performance will be lost. Not recommended here.

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.