How7oHow7o
  • Home
  • Tools
    • All Tools
    • Image Tools
    • Text & String Tools
    • Video Tools
    • Developer Tools
    • PDF Tools
    • Calculators & More
  • Prank Screens
  • Learn
  • Blog
  • Contact
Reading: How to Extract Only the Digits from a String in MySQL
Share
Notification Show More
Font ResizerAa
How7oHow7o
Font ResizerAa
  • Tools
  • Prank Screens
  • Learn
  • Blog
Search
  • Home
  • Tools
    • All Tools
    • Image Tools
    • Text & String Tools
    • Video Tools
    • Developer Tools
    • PDF Tools
    • Calculators & More
  • Prank Screens
  • Learn
  • Blog
  • Contact
Follow US
© 2024–2026 How7o. All rights reserved.
How7o > Free Laravel, PHP, WordPress & Server Tutorials > Web Development > How to Extract Only the Digits from a String in MySQL
Web Development

How to Extract Only the Digits from a String in MySQL

how7o
By how7o
Last updated: May 10, 2026
6 Min Read
MySQL extract digits from string — REGEXP_REPLACE negation class
SHARE

To mysql extract digits from string — pulling 123456 out of abc123def456 — use REGEXP_REPLACE with the [^0-9] class in a SELECT. The class negation strips everything that isn’t a digit, leaving only the numeric characters. This guide covers the basic select, the preserve-sign-and-decimal variant, an UPDATE that writes the cleaned value back, and generated-column caching for hot paths.

Contents
  • TL;DR
  • How the regex works
  • Preserving minus sign and decimal point
  • Updating the column in place
  • Generated column (MySQL 8.0+)
  • MySQL 5.7 and earlier
  • Frequently asked questions
  • Related guides
  • References

Last verified: 2026-04-23 on MySQL 8.0 and MariaDB 10.11. Originally published 2022-12-20, rewritten and updated 2026-04-23.

TL;DR

SELECT REGEXP_REPLACE(string_column, '[^0-9]', '') AS digits
FROM table_name;

How the regex works

  • [0-9] — matches any single digit.
  • [^0-9] — matches any character that is not a digit (the ^ at the start of a character class negates it).
  • REGEXP_REPLACE(str, pattern, replacement) — replaces every pattern match with the replacement. Passing an empty string as replacement deletes those characters.

Put together: every non-digit character is removed. "abc123def456" → "123456".

mysql extract digits from string — REGEXP_REPLACE with [^0-9] strips non-digit characters

Preserving minus sign and decimal point

-- "USD -12.50" -> "-12.50"
SELECT REGEXP_REPLACE(string_column, '[^-0-9.]', '') AS numeric_value
FROM table_name;

-- Cast to decimal for math
SELECT CAST( REGEXP_REPLACE(string_column, '[^-0-9.]', '') AS DECIMAL(10, 2) ) AS value
FROM table_name;

For currency-string cleanup (see also PHP string-to-float for the same pattern server-side), include - and . in the keep-set. The final CAST turns the cleaned string into a proper decimal you can use in WHERE or SUM.

Updating the column in place

-- Test on a small slice first
UPDATE table_name
SET string_column = REGEXP_REPLACE(string_column, '[^0-9]', '')
WHERE id < 100;

-- Then run the full update
UPDATE table_name
SET string_column = REGEXP_REPLACE(string_column, '[^0-9]', '');

Destructive — once you’ve replaced "abc123" with "123" the original letters are gone. Take a backup first, and run against a WHERE id < 100 sample to confirm the transform looks correct before touching the whole table.

Generated column (MySQL 8.0+)

ALTER TABLE table_name
ADD COLUMN digits_only VARCHAR(255)
    GENERATED ALWAYS AS (REGEXP_REPLACE(string_column, '[^0-9]', ''))
    STORED;

-- Query the pre-computed column
SELECT digits_only FROM table_name WHERE id = 42;

When you need the extracted digits repeatedly (filtering, joining, indexing), a STORED generated column computes it once on write and caches the result. REGEXP_REPLACE runs only on INSERT / UPDATE, not on every SELECT. You can also add an index on digits_only to make phone-number or invoice-number lookups fast.

MySQL 5.7 and earlier

REGEXP_REPLACE landed in MySQL 8.0. On 5.7 the best options are:

  • Upgrade — MySQL 5.7 reached end-of-life in October 2023 and no longer gets security updates. If you’re still on it, the upgrade path is the right answer.
  • Do it in the app layer — one-liner in any language. PHP: preg_replace('/\D+/', '', $value). Python: re.sub(r'\D', '', value). Adds a round trip but works on any MySQL version.
  • User-defined function — write a stored function that loops through the string character-by-character. Works, but slow and awkward.

Frequently asked questions

What’s the shortest mysql extract digits from string query?

REGEXP_REPLACE(column, '[^0-9]', ''). The [^0-9] class matches any character that is not a digit (^ inside a character class negates the set), and REGEXP_REPLACE replaces each match with an empty string. Result: only digits remain. Needs MySQL 8.0+ or MariaDB 10.0.5+.

What if I’m on MySQL 5.7 without REGEXP_REPLACE?

REGEXP_REPLACE shipped in MySQL 8.0. On 5.7 you have two options: upgrade (5.7 is EOL as of October 2023), or do the extraction in the application layer — a one-liner in PHP is preg_replace('/\D+/', '', $value). See converting a string to float in PHP for the sibling pattern on the app side.

Does this work on negative numbers or decimals?

No — the [^0-9] pattern strips everything that isn’t a digit, including minus signs and decimal points. "-1.25" becomes "125". If you need to preserve sign and decimal, use [^-0-9.] to keep those characters too: REGEXP_REPLACE(column, '[^-0-9.]', ''). Then cast to DECIMAL for math operations.

Can I update the column in place instead of selecting?

Yes — wrap the same expression in an UPDATE: UPDATE table_name SET column = REGEXP_REPLACE(column, '[^0-9]', ''). Take a database backup first — REGEXP_REPLACE is a destructive transform ("abc123def456" becomes "123456", you can’t recover abc and def from the result). Test with a WHERE id < 100 first.

Is a computed column an option?

MySQL 8.0 supports generated columns: ALTER TABLE table_name ADD COLUMN digits_only VARCHAR(255) GENERATED ALWAYS AS (REGEXP_REPLACE(original_column, '[^0-9]', '')) STORED. The value auto-updates whenever the source column changes. Useful when you need the extracted value repeatedly and the extraction cost would otherwise hit every query.

Related guides

  • How to Remove a Specific String from a Column in MySQL — the sibling REPLACE / REGEXP_REPLACE pattern.
  • How to Combine Multiple Columns as One String in MySQL — composite string operations.
  • How to Convert a String to Float in PHP — the app-layer equivalent for currency strings.
  • How to Fix “Unknown column ‘CONCAT'” in Laravel — using MySQL string functions from Eloquent.

References

MySQL REGEXP_REPLACE docs: dev.mysql.com/doc/refman/8.0/en/regexp.

TAGGED:mysqlsql

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
[mc4wp_form]
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Copy Link Print
Previous Article WooCommerce remove checkout fields — woocommerce_checkout_fields filter unsetting fields How to Remove Checkout Fields in WooCommerce
Next Article MySQL remove string from column — REPLACE and REGEXP_REPLACE patterns How to Remove a Specific String from a Column in MySQL
Leave a Comment

Leave a Reply Cancel reply

You must be logged in to post a comment.

You Might Also Like

Disable binary logging in MySQL or MariaDB
Server Management

How to Disable Binary Logging in MySQL or MariaDB

5 Min Read
DataTables default sort order — order: [[1, 'desc']] config
Web Development

How to Change the Default Sort Order in DataTables

4 Min Read
JavaScript format number with decimals — toFixed, Math.floor, and Intl.NumberFormat
Web Development

How to Format a Number with Decimals in JavaScript

5 Min Read
WordPress prepare LIKE SQL — %s placeholder + % wildcards in the value
Web Development

How to Prepare a %LIKE% SQL Statement in WordPress

7 Min Read
How7oHow7o

Free browser-based tools, prank screens, and step-by-step tech tutorials. No signup, nothing uploaded.

  • Private by design — your files never leave your device
  • Instant — no signup, no install, no waiting
  • Always free — no trials, no watermarks, no paywalls

Tools

  • PDF Editor
  • Image Upscaler
  • JPEG Compressor
  • Password Generator
  • QR Code Generator
  • Video Trimmer
  • See all tools →

Pranks

  • Cracked Screen Prank
  • Fake Blue Screen (BSOD)
  • Fake Console Update Screen
  • Fake Disk Format
  • Fake Low Battery
  • Fake Virus Scan
  • See all prank screens →

Company

  • About Us
  • Blog
  • Contact
  • Privacy Policy
  • Terms of Service
  • Sitemap
© 2024–2026 How7o. All rights reserved.
Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?