简体   繁体   中英

Check if row exists, The most efficient way?

SQL Queries /P1/

  1. SELECT EXISTS(SELECT /p2/ FROM table WHERE id = 1)
  2. SELECT /p2/ FROM table WHERE id = 1 LIMIT 1

SQL SELECT /P2/

  1. COUNT(id)
  2. id

PHP PDO Function /P3/

  1. fetchColumn()
  2. rowCount()

From the following 3 Parts, What is the best method to check if a row exists or not with and without the ability to retrieve data like.

Retrievable:

/Query/ SELECT id FROM table WHERE id = 1 LIMIT 1

/Function/ rowCount()


Irretrievable

/Query/ SELECT EXISTS(SELECT COUNT(id) FROM table WHERE id = 1)

/Function/ fetchColumn()

In your opinion, What is the best way to do that?

By best I guess you mean consuming the least resources on both MySQL server and client.

That is this:

      SELECT COUNT(*) count FROM table WHERE id=1

You get a one-row, one-column result set. If that column is zero, the row was not found. If the column is one, a row was found. If the column is greater that one, multiple rows were found.

This is a good solution for a few reasons.

  1. COUNT(*) is decently efficient, especially if id is indexed.
  2. It has a simple code path in your client software, because it always returns just one row. You don't have to sweat edge cases like no rows or multiple rows.
  3. The SQL is as clear as it can be about what you're trying to do. That's helpful to the next person to work on your code.

Adding LIMIT 1 will do nothing if added to this query. It is already a one-row result set, inherently. You can add it, but then you'll make the next person looking at your code wonder what you were trying to do, and wonder whether you made some kind of mistake.

COUNT(*) counts all rows that match the WHERE statement. COUNT(id) is slightly slower because it counts all rows unless their id values are null. It has to make that check. For that reason, people usually use COUNT(*) unless there's some chance they want to ignore null values. If you put COUNT(id) in your code, the next person to work on it will have to spend some time figuring out whether you meant anything special by counting id rather than * .

You can use either; they give the same result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM