Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PL/SQL "between x and y" does not work, if y < x. Why?

Tags:

oracle

plsql

I have a PL/SQL code like:

case when column between 201203 and 201201
then other_column
end

I know that there are values in column that are 201203. So code should return some values. But it didn't until I corrected it like:

case when column between 201201 and 201203
then other_column
end

Why between keyword works like that? How it is implemented on Oracle Databases?

like image 400
Canburak Tümer Avatar asked Dec 25 '12 16:12

Canburak Tümer


People also ask

Is between in Oracle inclusive?

The SQL BETWEEN Operator The 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.

What are between conditions?

A BETWEEN condition determines whether the value of one expression is in an interval defined by two other expressions. between_condition::= Description of the illustration ''between_condition.gif'' All three expressions must be numeric, character, or datetime expressions.

How does between work in Oracle?

The BETWEEN operator allows you to specify a range to test. When you use the BETWEEN operator to form a search condition for rows returned by a SELECT statement, only rows whose values are in the specified range are returned. The low and high specify the lower and upper values of the range to test.

Why Rownum 2 is not valid in Oracle?

But when you say ROWNUM = 2, The generation of the first row is failed as the ROWNUM for the first row is 1. And hence you dont get any rows.


3 Answers

This is ANSI SQL behavior.

 expr1 BETWEEN expr2 AND expr3

translates to

 expr2 <= expr1 AND expr1 <= expr3
like image 129
Michel Feldheim Avatar answered Nov 15 '22 05:11

Michel Feldheim


In Between Clause, always lower value comes first instead of higher value.

Ex:- BETWEEN 100 AND 200

instead of

BETWEEN 200 AND 100

When Query Parser Parse BETWEEN 100 AND 200 then it would be like this:-

X >= 100 AND X <= 200

like image 24
abhishek Avatar answered Nov 15 '22 07:11

abhishek


Consider

val1 between val2 and val3

as

(val1 >= val2) and (val1 <= val3)

Then what we have?

column between 201203 and 201201

is the equivalent to

( column >= 201203 ) and (column <= 201201)

If the column value is, let's say, 201202 then the first condition ( column >= 201203 ) will be false and the second one also will be false. That is why you are not getting any results. Find out more.

like image 32
Nick Krasnov Avatar answered Nov 15 '22 06:11

Nick Krasnov