Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select BETWEEN column values

Tags:

sql

between

I'm trying to use the BETWEEN with column names instead of direct values, something like this:

SELECT * FROM table WHERE column1 BETWEEN column2 AND column3;

This is returning something like 17 rows, but if i write:

SELECT * FROM table WHERE (column1 <= column2 AND column1 >= column3) OR (column1 >= column2 AND column1 <= column3)

i get around 600 rows.. In both cases i only get rows where column1 value is actually the middle value, but 2nd method gives me much more results, so 1st method has something wrong with it.

I suspect the problem might be on using BETWEEN clause with column names, instead of pure values, and somehow SQL is converting the column names to actual values..its strange, but can someone enlighten me please? Thanks

like image 691
Gonçalo Queirós Avatar asked Sep 19 '10 18:09

Gonçalo Queirós


People also ask

How do you check between values in SQL?

The SQL BETWEEN OperatorThe BETWEEN operator selects values within a given range. The values can be numbers, text, or dates. The BETWEEN operator is inclusive: begin and end values are included.

How do you indicate ranges between numbers in a query?

The BETWEEN operator is inclusive. To specify an exclusive range, you use the less than (<) and greater than (>) operators instead. If you pass the NULL values to the BETWEEN operator e.g., expr , lower_value or upper_value , the BETWEEN operator returns NULL .

How do I SELECT data from multiple columns?

To select multiple columns from a table, simply separate the column names with commas! For example, this query selects two columns, name and birthdate , from the people table: SELECT name, birthdate FROM people; Sometimes, you may want to select all columns from a table.

Can we use SELECT * with group by?

Cannot use an aggregate or a subquery in an expression used for the group by list of a GROUP BY clause. The original idea was to create the table in beginning of the query, so the (SELECT * FROM #TBL) could be used on the query itself, instead of defining the names on each GROUP BY.


1 Answers

SELECT * FROM table WHERE column1 BETWEEN column2 AND column3; # gives 17 rows

is same as

SELECT * FROM table WHERE (column1 >= column2 AND column1 <= column3) # gives 17 rows

Because of your addition check of

(column1 <= column2 AND column1 >= column3)

which is ORed, you get additional rows.

like image 106
codaddict Avatar answered Oct 06 '22 21:10

codaddict