Reputation: 2455
Output of the following SQL statement is '279A'
SELECT
SUBSTR('H0279A',3)
I am confused why this query returns 1:
SELECT
CASE
WHEN SUBSTR('H0279A',3) BETWEEN '0000' AND '9999'
THEN 1
ELSE 0
END
How can '279A' be between '0000' AND '9999' ? I am using Teradata.
Upvotes: 0
Views: 1681
Reputation: 10525
Your H0279A is of type varchar. And so is 0000 and 9999. So essentially you are comparing strings and not numbers. 2 comes after 0 and before 9. So its no wonder that 279A is between 0000 and 9999.
Do you want to check whether the given string is between 0 and 9999. Then you should do this.
SELECT
CASE
WHEN SUBSTR('H0279A',3) BETWEEN 0 AND 9999 --here 0 and 9999 are numbers, not strings
THEN 1
ELSE 0
END;
But this will raise exception, since conversion of 279A to number fails.
UPDATE: Lets keep aside SUBSTR for a while.
create table ntest(
col1 varchar(20)
);
insert into ntest values('abs');
insert into ntest values('abscond');
insert into ntest values('000');
insert into ntest values('000000A');
insert into ntest values('9999');
insert into ntest values('027A');
insert into ntest values('zip');
insert into ntest values('279');
insert into ntest values('279A');
insert into ntest values('877');
select * from ntest order by col1;
col1
--------------------
000 <--------------------------¬
000000A |
027A |
279 |
279A -- strings starting with 2 are between strings starting with 0 and 9
877 |
9999 <--------------------------⤶
abs
abscond
zip
Upvotes: 4