1

I have a column, called value, that includes strings as well as numbers as data, eg:

  • contentid, value
  • 16, 200
  • 18, 150
  • 47, Foo
  • 16, Red
  • 16, 50
  • 18, GREEN

I need a way to retrieve only the results that are actual numbers (and, additionally, that are <= 180).

The expected results from above should be: 18, 150 and 16, 50 but I am getting results with strings as well.

I have tried this from other SO questions:

SELECT * 
FROM  `contentvalues` 
WHERE (
contentid =16
OR contentid =18
)
AND `value` <= 180
AND value NOT LIKE  '%[a-z0-9]%'

But this has not worked.

Would anyone be able to point me in the right direction?

MeltingDog
  • 14,310
  • 43
  • 165
  • 295

2 Answers2

3

According to this:

... AND value REGEXP ('[0-9]')

... but someone's blog is never the best source. Actually that matches everything that contains a number. Better would be

... AND value REGEXP ('^[0-9]+$')

Above regex is

^      "From the begining of the string..."
[0-9]  "There should be a number..."
+      "actually exactly 1 or more of those numbers"
$      "and the the string should just end."
Simo Erkinheimo
  • 1,347
  • 9
  • 17
0

Here is a solution which does not require the REGEXP() function, which may not available in all RDBMS:

SELECT * 
FROM  `contentvalues` 
WHERE (contentid = 16 OR contentid =18)
    AND concat('',value * 1) = value

This will work as long as the numbers in the value column do not appear in scientific notation, with trailing decimals, or other weird formats. Read this SO article for more information.

Community
  • 1
  • 1
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360