Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql: Perform of NOT EXISTS. Is it possible to improve perfomance?

I have two tables posts and comments. Table comments have post_id attribute. I need to get all posts with type "open", for which there are no comments with type "good" and created date MAY 1.

Is it optimal to use such SQL-query:

SELECT  posts.* FROM  posts  
WHERE NOT EXISTS (
SELECT comments.id FROM comments WHERE comments.post_id = posts.id 
AND  comments.comment_type = 'good' AND 
comments.created_at BETWEEN '2010-05-01 00:00:00' AND '2010-05-01 23:59:59')

I'm not sure that NOT EXISTS is perfect construction in this situation.

like image 404
petRUShka Avatar asked Jun 07 '10 21:06

petRUShka


People also ask

Which is faster exists or not exists in SQL?

There is no difference.

Which is better join or exists?

In cases like above the Exists statement works faster than that of Joins. Exists will give you a single record and will save the time also. In case of joins the number of records will be more and all the records must be used.


1 Answers

You are right - you can do better. See this article by Quassnoi for the details but the conclusion is:

That’s why the best way to search for missing values in MySQL is using a LEFT JOIN / IS NULL or NOT IN rather than NOT EXISTS.

Your query rewritten using NOT IN could look like this:

SELECT *
FROM posts  
WHERE posts.id NOT IN (SELECT post_id
                       FROM comments
                       WHERE comments.comment_type = 'good'
                       AND comments.created_at BETWEEN '2010-05-01 00:00:00'
                                                   AND '2010-05-01 23:59:59')
like image 114
Mark Byers Avatar answered Sep 26 '22 07:09

Mark Byers