Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use the BETWEEN operator when we can do without it?

Tags:

sql

between

As seen below the two queries, we find that they both work well. Then I am confused why should we ever use BETWEEN because I have found that BETWEEN behaves differently in different databases as found in w3school

SELECT *
FROM employees
WHERE salary BETWEEN 5000 AND 15000;

SELECT *
FROM employees
WHERE salary >= 5000
AND salary <= 15000;
like image 998
Thunder Avatar asked Dec 25 '09 08:12

Thunder


People also ask

Why between operator is used?

The BETWEEN operator is used in the WHERE conditions to filter records within the specified range. The range of values can be strings, numbers, or dates. The range of values must be specified with the AND operator, as shown below.

What is the use of between and not between operator?

MySQL NOT BETWEEN AND operator checks whether a value is not present between a starting and a closing expression. If expr is not greater than or equal to min and expr is not less than or equal to max, BETWEEN returns 1, otherwise, it returns 0.

What is the purpose of between in and like clauses?

LIKE and BETWEEN in SQL LIKE and BETWEEN operators in SQL are used to compare values in a database.

Can we use between operator for character data?

In SQL, if we use BETWEEN operator with character values, it will return all the records where the column name begins with any letter between character string values.


1 Answers

BETWEEN can help to avoid unnecessary reevaluation of the expression:

SELECT  AVG(RAND(20091225) BETWEEN 0.2 AND 0.4)
FROM    t_source;

---
0.1998

SELECT  AVG(RAND(20091225) >= 0.2 AND RAND(20091225) <= 0.4)
FROM    t_source;

---
0.3199

t_source is just a dummy table with 1,000,000 records.

Of course this can be worked around using a subquery, but in MySQL it's less efficient.

And of course, BETWEEN is more readable. It takes 3 times to use it in a query to remember the syntax forever.

In SQL Server and MySQL, LIKE against a constant with non-leading '%' is also a shorthand for a pair of >= and <:

SET SHOWPLAN_TEXT ON
GO
SELECT  *
FROM    master
WHERE   name LIKE 'string%'
GO
SET SHOWPLAN_TEXT OFF
GO


|--Index Seek(OBJECT:([test].[dbo].[master].[ix_name_desc]), SEEK:([test].[dbo].[master].[name] < 'strinH' AND [test].[dbo].[master].[name] >= 'string'),  WHERE:([test].[dbo].[master].[name] like 'string%') ORDERED FORWARD)

However, LIKE syntax is more legible.

like image 70
Quassnoi Avatar answered Dec 16 '22 19:12

Quassnoi