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.
COUNT(*)
is decently efficient, especially if id
is indexed.
- 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.
- 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.