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?

2 Answers 2

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."
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks! Sorry - should have put it above - but would you know of anyway to exclude values that contain both numbers and letters as well? Eg: RED123?
If the current answer doesn't cover that case, use this: REGEXP ('^[0-9]+$')
Ah, weird, Its picking up some HTML I have stored in the table (specifically, Google Map iframes)
@MeltingDog Sorry I just edited the comment above. Try the new one.
yep, perfect! Thanks!
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.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.