Take the 2-minute tour ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.

i've just wondered if there's a difference in cost(memory,cpu) of an EXISTS or NOT EXISTS in following queries. Does it make a difference if i select NULL, 1 or columns?

1)

SELECT id 
FROM Parent p
WHERE NOT EXISTS
(
   SELECT NULL FROM Child c
   WHERE c.parent_Id = p.id
   AND c.x <> c.y
)

2)

SELECT id 
FROM Parent p
WHERE NOT EXISTS
(
   SELECT 1 FROM Child c
   WHERE c.parent_Id = p.id
   AND c.x <> c.y
)

3)

SELECT id 
FROM Parent p
WHERE NOT EXISTS
(
   SELECT * FROM Child c
   WHERE c.parent_Id = p.id
   AND c.x <> c.y
)

Option 1 is what i use normally, is there are difference at all or is it optimised to the same?

share|improve this question
add comment

1 Answer 1

up vote 3 down vote accepted

You should find that each example results in a LEFT SEMI ANTI JOIN with equal costs.

The Left Anti Semi Join operator returns each row from the first (top) input when there is no matching row in the second (bottom) input. If no join predicate exists in the Argument column, each row is a matching row.

Out of habit I tend to use the syntax in your second example, which you could argue signals intent better than the others.

share|improve this answer
    
Doesn't using the * in the third syntax trigger the reading into memory of the entire result-set of the subquery? Thus making it much less efficient because it involves disk read + memory allocation. –  Mihai Stancu Aug 23 '12 at 8:33
    
@MihaiStancu No, the optimiser will eliminate that and check for existence of a row only. Given an index on c.parent_id which includes c.x and c.y, you would avoid a lookup to the heap/clustered index. –  Mark Storey-Smith Aug 23 '12 at 8:42
    
As a curiosity does this apply to other db engines such as MYSQL/PGSQL/SQLite? –  Mihai Stancu Aug 25 '12 at 12:34
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.