2
Here you can find how to check row existance:
SELECT EXISTS(SELECT 1 FROM table1 WHERE some_condition);

How to efficiently existance of multiple rows from table like:

SELECT EXISTS(SELECT 1 FROM table1 WHERE key = 0);
SELECT EXISTS(SELECT 1 FROM table1 WHERE key = 2);

from table:

key,username
0,foo
1,bar
2,boo

to return positive only if both rows (with key 0 and 2) was found?

2 Answers 2

4
SELECT count(distinct key) = 2  FROM table1 WHERE key in (0, 2) 
Sign up to request clarification or add additional context in comments.

Comments

1
SELECT sum(`key` = 0) as key0_count,
       sum(`key` = 2) as key2_count 
FROM your_table

5 Comments

And how is that better from SELECT EXISTS and why key0_count?
It is one single query without any subqueries.
What is key0_count ?
key0_count is the number of times key = 0 in your table. If it is 0 then it is not in your table.
@Ulta . . . If you have an index on key, then multiple exists statements are probably faster. If you do not have an index, then this may be faster, because it only requires one full scan of the table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.