Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Check if there Exist Row(s) Matching a Condition

Tags:

mysql

I have been doing this for quite some time:

SELECT COUNT(*) FROM Table WHERE Condition = *Condition*;

Since I am not interested in the total number of rows returned, I wonder if there is a more efficient way to check if there exist any row(s) that match the condition without letting MySQL scan through the entire table.

like image 800
Question Overflow Avatar asked Oct 10 '11 11:10

Question Overflow


People also ask

How do you check if a row exists in SQL?

The EXISTS operator is used to test for the existence of any record in a subquery. The EXISTS operator returns TRUE if the subquery returns one or more records.

How do I check if two rows have the same value in MySQL?

First, use the GROUP BY clause to group all rows by the target column, which is the column that you want to check duplicate. Then, use the COUNT() function in the HAVING clause to check if any group have more than 1 element. These groups are duplicate.

How do you check if a value from one table exists in another table?

Example using VLOOKUP You can check if the values in column A exist in column B using VLOOKUP. Select cell C2 by clicking on it. Insert the formula in “=IF(ISERROR(VLOOKUP(A2,$B$2:$B$1001,1,FALSE)),FALSE,TRUE)” the formula bar.

How do you check if a record exists in another table SQL?

How do you check if a table contains any data in SQL? Using EXISTS clause in the IF statement to check the existence of a record. Using EXISTS clause in the CASE statement to check the existence of a record. Using EXISTS clause in the WHERE clause to check the existence of a record.


2 Answers

SELECT CASE
         WHEN EXISTS(SELECT *
                     FROM   YourTable
                     WHERE  Condition = '*Condition*') THEN 1
         ELSE 0
       END  
like image 108
Martin Smith Avatar answered Nov 15 '22 11:11

Martin Smith


Try

SELECT COUNT(*) FROM SmallTable
WHERE EXISTS(SELECT * FROM Table WHERE Condition = *Condition*)
like image 37
SLaks Avatar answered Nov 15 '22 10:11

SLaks