0

I have two different approaches to check for an existing entry.

Approach 1

SQL: SELECT COUNT(*) FROM ...

PHP:

$result = fetch_row();
if($result[0] > 0) // entry found

Approach 2

SQL: SELECT 1 FROM ... LIMIT 1

PHP:

$result = num_rows();
if($result > 0) // entry found

What is the right way to do it in terms of performance?

Anas
  • 5,622
  • 5
  • 39
  • 71
Aley
  • 8,540
  • 7
  • 43
  • 56

2 Answers2

1

Both are correct and good. But I will suggest second as you are limiting to 1 record and as you got record it will stop while in first you are counting all records.

first "count *" is important when you need to find how many records presents.

mukund
  • 2,253
  • 1
  • 18
  • 31
1

The latter is more efficient when there are many rows matching your query, because in first case MySQL will have to find all of them to return correct count value, while in second case it will stop searching after finding the first one.

Mikhail Vladimirov
  • 13,572
  • 1
  • 38
  • 40