2

I am trying to select all the rows in which COLUMN has a value between 1 and 9. The problem is the datatype for COLUMN is text and I have used the following code to get those rows:

SELECT * FROM TABLE WHERE COLUMN BETWEEN '1' AND '9';

Instead of getting rows with COLUMN value between 1 and 9, I also get rows with COLUMN values 10, 11 and so forth. How can I make it give me only rows with COLUMN values between 1 and 9?

3 Answers 3

5

If all of the values in the column are guaranteed to be integers™ you could do this:

SELECT * FROM TABLE WHERE CInt(COLUMN) BETWEEN 1 AND 9
Sign up to request clarification or add additional context in comments.

Comments

3

For example like this:

SELECT * FROM TABLE WHERE COLUMN BETWEEN '1' AND '9' and LEN(COLUMN) = 1;

3 Comments

It seems odd that numeric values are quoted. I think you will also find that Column is a reserved word.
Tried this and it worked thank you any everyone else for your help. I appreciate it :).
@Fionnuala: Well, we are looking for strings. Actually simply WHERE COLUMN in ('1','2','3','4','5','6','7','8','9') - which is another solution without BETWEEN. I agree that TABLE and COLUMN would probably cause conflicts if used thus. They are mere placeholders for the actual names here.
-1

You can convert column type in where clause.

SELECT * FROM TABLE WHERE convert(bigint,COLUMN) BETWEEN '1' AND '9';

but make sure all values can be converted to bigint type or u can use float/int etc.

4 Comments

u did not mention it that you need it for microsoft access.
It not my question, but in any case it's tagged as ms-access.
Yes, but SQL is a generic language and some databases does not support it fully, for instance Microsoft Access. In this case the SQL is limited by what ms-access supports. The SQL tag refers to the language, not MS SQL Server or some other specific database.
By tagging Sql I meant I am using sql code in Ms-access

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.