Different methods have different pros and cons:
SELECT EXISTS(SELECT 1 FROM table1 WHERE some_condition);
may be the fastest in MySQL but
SELECT COUNT(1) FROM table 1 WHERE some_condition
as in @Luis's answer, gives you the score.
In addition, I recommend that you take a look at your business logic. Very rarely you just need to see if a line exists, most often you want
- either use these lines, so just select and handle the case with 0 lines
- or you want to change these lines, in which case just do your update and check mysql_affected_rows ()
- If you want to
INSERT .. ON DUPLICATE KEY row if it does not already exist, take a look at INSERT .. ON DUPLICATE KEY or REPLACE INTO
source share