Skip to content
Advertisement

SQL: difference between where in main body vs join clause

I’m wondering why does the following queries give me a slightly different dataset:

So I just moved BETWEEN clause to the main body, logically, it does not matter where to apply it, but the result says it matters. Any suggestions? Thanks!

UPD: tried on MySQL 5.6

Advertisement

Answer

Maybe it’s hard to answer this question without some images! but I try.

Let’s assume this is the event_type table

Id Name
1 First
2 Second

Events table:

Id TypeId Start
5 1 2022-10-01
6 1 2022-10-10

So for this query:

The result will be:

Name Count(e.id)
First 1
Second 0

But why? becuase sql engine when try to get result on left join, it will check both of id and start, actually the result of prevois query is like this:

Id Name Id TypeId Start
1 First 5 1 2022-10-01
2 Second null null null

That’s it! When you try to use Between in where clause, in fact you are filtering the null values so sql would ingore them and the final result would be different.

I hope it’s clear enough!

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement