Search code examples
mysqlsqlexistssql-in

Use mysql EXISTS with a const string


can u help me understand to difference between EXISTS and IN using mysql ?.
in my application i am using IN in my queries, since i am using memcached to store the IN values,
so i find IN more faster the EXISTS, for example :

String my_chached_string = Memecached.get('somekey')
"SELECT * FROM Table t WHERE t.fromId IN (" + my_chached_string + ")"

my question, is there a way to use EXISTS the same way, with constant values ?

thank you


Solution

  • Here are some common coding patterns:

    WHERE col = 'string'
    WHERE col IN ('string') -- same as above
    WHERE col IN ('string1', 'string2')
    WHERE EXISTS ( SELECT * FROM tbl WHERE ... )
    

    The EXISTS one is really solving a different situation; I don't understand why you threw it in. Even if there were an equivalent EXISTS pattern, it would necessarily be less efficient.

    This pattern in terribly inefficient:

    WHERE col IN ( SELECT ... )
    

    It can often be made more efficient by transforming into a JOIN.