1

I have a query having BETWEEN operator but it showing wrong results

My query-

SELECT * FROM register WHERE height BETWEEN  '1' AND  '6'

It also shows the user with height 10, 12 and 16 which is wrong. What is the problem with this query?
I have another query which work fine but is not proper way of using as it make query lengthy

SELECT * FROM register WHERE height > 1 AND height < 12  

Give me idea for right way of getting the query as if more condition is added it would be hard for the query to understand and code.

4
  • what's data type of column height?
    – Omesh
    Aug 24, 2012 at 12:21
  • Why do you use strings for integer comparison? It's pretty logical that you shouldn't quote the numbers, isn't it?
    – N.B.
    Aug 24, 2012 at 12:22
  • 2
    then you use second query, or modify height column to be integer Aug 24, 2012 at 12:24
  • Then coerce the columns to the appropriate types before comparing. It's not MySQL behaving weird, you just can't compare apple and oranges and expect grapes to come out.
    – N.B.
    Aug 24, 2012 at 12:32

4 Answers 4

3

Assuming height is an integer should it not be

SELECT * FROM register WHERE height BETWEEN 1 AND 6

You don't need the single quotes

2
  • You can't use quotes when you want to use BETWEEN and the field is an integer. When the field isn't an integer it should be altered to one.
    – arnoudhgz
    Aug 24, 2012 at 12:27
  • as Mihai Iorga says, I would go with the second query then. It does seem strange that height is a varchar field however....since when is height not going to be a number...? Aug 24, 2012 at 12:30
1

If:
1. You can't or don't want to change the column type
2. The charachters in the field are only numbers

You can change your query to:

SELECT * 
FROM register 
WHERE CONVERT(height, UNSIGNED INTEGER) BETWEEN 1 AND 6

See my example at this SQL fiddle.

0

Check the data type of your column 'Height' it should be a int or float or double and if it is amongs above run the following query

SELECT * FROM register WHERE height BETWEEN 1 AND 6
0

If the height field is not numeric, you could convert it before making you comparison.

SELECT * FROM register WHERE CONVERT(height, unsigned) BETWEEN 1 AND 6

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.