These two statements are logically equivalent:
SELECT * FROM table WHERE someColumn BETWEEN 1 AND 100
SELECT * FROM table WHERE someColumn >= 1 AND someColumn <= 100
Is there a potential performance benefit to one versus the other?
1 Answer. Using '=' operator is faster than the LIKE operator in comparing strings because '=' operator compares the entire string but the LIKE keyword compares by each character of the string.
A where clause will generally increase the performance of the database. Generally, it is more expensive to return data and filter in the application. The database can optimize the query, using indexes and partitions. The database may be running in parallel, executing the query in parallel.
Both operators give the same output. The only difference is that '<>' is in line with the ISO standard while '!= ' does not follow ISO standard. You should use <> operator as it follows the ISO standard.
Between is technically greater than and equal to PLUS less than and equal to. If you are using date ranges like the examples above, your filter translates to: select * from dbo. BTW where DT between cast('1945-01-08' as datetime) and cast('1965-01-01' as datetime)
Hmm, here was a surprising result. I don't have SQL Server here, so I tried this in Postgres. Obviously disclaimers apply: this won't necessarily give the same results, your mileage may vary, consult a physician before using. But still ...
I just wrote a simple query in two different ways:
select *
from foo
where (select code from bar where bar.barid=foo.barid) between 'A' and 'B'
and
select *
from foo
where (select code from bar where bar.barid=foo.barid)>='A'
and (select code from bar where bar.barid=foo.barid)<='B'
Surprisingly to me, both had almost identical run times. When I did an EXPLAIN PLAN, they gave identical results. Specifically, the first query did the lookup against bar twice, once for the >= test and again for the <= test, just like the second query.
Conclusion: In Postgres, at least, BETWEEN is indeed just syntactic sugar.
Personally, I use it regularly because it is clearer to the reader, especially if the value being tested is an expression. Figuring out that two complex expressions are identical can be a non-trivial exercise. Figuring out that two complex expressions SHOULD BE identical even though they're not is even more difficult.
No benefit, just a syntax sugar.
By using the BETWEEN
version, you can avoid function reevaluation in some cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With