Detect if value is number in MySQL
To detect whether a value in MySQL is numeric, leverage the power of REGEXP like so:
Tada! This query returns 1
if value
screams "I am a number!", and 0
otherwise.
Mastering REGEXP for digits
How do we ensure a column value is a proud citizen of the "digit kingdom"? The '^[0-9]+$'
REGEXP. This REGEXP unmasks strings that only contain digits.
When numbers get decimal and scientific
What if numbers want to go all decimal or scientific on you? Fear not, REGEXP has your back.
This REGEXP identifies both integer and decimal numbers, or numbers diving into the deep "scientific notation" sea.
Coercing MySQL into numeric shape
What happens when MySQL stubbornly sees a numeric string as a character type? You pull out your Type Coercion card.
This coerces character strings into numeric data, especially useful when you need to perform mathematical operations with your data.
Catching numeric patterns in the wild
To catch numbers trying to sneak around in your string values, you can use the REGEXP '[0-9]+'
.
This REGEXP gives you a big "gotcha" moment whenever it encounters even a single digit in your strings.
The full REGEXP ensemble for various numeric formats
We've discussed several REGEXP variations, but now let's bring them all together to handle all types of numeric formats.
This pattern advertises an open house for all numeric kinds: plain, decimal, scientific notation, you name it.
Time to filter our SQL queries
Weeding out non-numeric rows
Sometimes, you only want to party with number folks, so you use the !
operator.
This query filters out the "non-numeric" crowd from your SQL party.
Filtering for positive numeric vibes
Want to hang out with only positive numbers? We got you.
This query leaves "negative Nellies" out in the cold.
Was this article helpful?