Ahsan
Ahsan

Reputation: 469

mysql BETWEEN will return 0 rows

I have a MySQL table with price structure something like this:

-------------------- 
| Price | item_id  |
--------------------
|$10,999|  123     |
|$5,889 |  321     |
|$2999  |  143     | 
|------------------|

Now if i Query this :

SELECT * FROM products WHERE price BETWEEN "$2999" AND "$6000";

It will return two rows. But if i Query this :

SELECT * FROM products WHERE price BETWEEN "$2999" AND "$20000";

It won't return any row as it is expected to return atleast 3 rows?

Please note that there are many other rows aswell which are $11,000, and so on...

Any help would be appreciated!

Upvotes: 0

Views: 97

Answers (4)

Brian
Brian

Reputation: 5028

Drop the $ and leave numbers only. You do not need to save dollar sign with numbers in DB.

SELECT * FROM products WHERE price > 2999 AND price < 6000;
SELECT * FROM products WHERE price > 2999 AND price < 20000;

or

SELECT * FROM products WHERE price BETWEEN 2999 AND 6000";
SELECT * FROM products WHERE price BETWEEN 2999 AND 20000";

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1271231

It would seem that you are storing the price as a string rather than a number. There is nothing between "$2999" and "$20000" because "$2999" > "$20000" alphabetically.

Here is one way to fix this:

SELECT 
FROM products
WHERE cast(replace(replace(price, '$', ''), ',') as signed) BETWEEN 2999 AND 20000;

A better way would be to store the "price" as a number rather than a character.

Upvotes: 2

Vasilis Lourdas
Vasilis Lourdas

Reputation: 1179

I suppose that Price is a text field and not a numeric one. So, when you try to fetch rows between $2999 and $20000 nothing is returned, because actually 20000 is smaller than 2999 when compared as strings.

You must convert the column to a decimal data type with two decimal points.

Upvotes: 1

John Woo
John Woo

Reputation: 263943

You should be storing it as string or varchar. The way it performs now is it compares for string that's why you have not result. If I were you, I will restructure the table by altering column Price to be INT or DECIMAL, or whatever as long as it is a number.

But to answer your question directly, you can do this but doesn't use any index if you have define one.

WHERE CAST(REPLACE(REPLACE(price,'$',''),',','') AS SIGNED) 
      BETWEEN 2999 AND 20000

Upvotes: 4

Related Questions