Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if multiple values exists in database?

I have a list of email addresses in the Java code and I would like to check if any of these already exists in the MySQL database.

For example:

  1. [email protected]
  2. [email protected]
  3. [email protected]

I want to know if any of the above email ids is already present in the table, and if they do, I would like to pull or separate them out.

I am not sure how to achieve this. Should I try this in Java or use SQL to achieve the desired result?

like image 716
shashank Avatar asked Oct 18 '14 16:10

shashank


1 Answers

Here are different solutions that will help you achieve what you want

  • This SQL expression will tell you if an email exists or not:

    SELECT IF (COUNT(*) > 0, 'Exist', 'Not exist')
    FROM email_table 
    WHERE email = '[email protected]';
    
  • If you just want the number of occurrences you can do this:

    SELECT COUNT(*)
    FROM email_table
    WHERE email = '[email protected]';
    
  • If you want to check for multiple values at a time you can do this:

    SELECT COUNT(*)
    FROM email_table
    WHERE email IN ('[email protected]', '[email protected]');
    
  • If you want to see which IDs are found:

    SELECT email
    FROM email_table
    WHERE email IN ('[email protected]', '[email protected]');
    
like image 154
Jean-François Savard Avatar answered Sep 23 '22 08:09

Jean-François Savard