Example 1
Extract numeric amounts from a column that contains non-numeric placeholders
Rows 1, 3, and 5 contain valid integer strings ('150', '200', '75') and are converted to integers. Rows 2 and 4 contain 'N/A' and 'error', which fail the numeric check: SQL Server's TRY_CAST catches the conversion error and returns NULL; the CASE WHEN ... REGEXP and CASE WHEN ... ~ approaches skip the CAST entirely for non-matching strings, defaulting the CASE to NULL. The regex ^[0-9]+$ matches only strings made entirely of digits, which handles the non-negative integer case. For values that could be negative or decimal, the regex would need to be adjusted to ^-?[0-9]+(\.[0-9]+)?$. SQL Server's TRY_CAST handles all numeric formats automatically without a regex.
CREATE TABLE raw_data (id INT, amount_text VARCHAR(20));
INSERT INTO
raw_data
VALUES
(1, '150'),
(2, 'N/A'),
(3, '200'),
(4, 'error'),
(5, '75');SELECT
id,
amount_text,
CASE
WHEN amount_text REGEXP '^[0-9]+$' THEN CAST(amount_text AS SIGNED)
ELSE NULL
END AS amount
FROM
raw_data
ORDER BY
id;| id | amount_text | amount |
|---|---|---|
| 1 | 150 | 150 |
| 2 | N/A | NULL |
| 3 | 200 | 200 |
| 4 | error | NULL |
| 5 | 75 | 75 |
CREATE TABLE raw_data (id INT, amount_text VARCHAR(20));
INSERT INTO
raw_data
VALUES
(1, '150'),
(2, 'N/A'),
(3, '200'),
(4, 'error'),
(5, '75');SELECT
id,
amount_text,
TRY_CAST (amount_text AS INT) AS amount
FROM
raw_data
ORDER BY
id;| id | amount_text | amount |
|---|---|---|
| 1 | 150 | 150 |
| 2 | N/A | NULL |
| 3 | 200 | 200 |
| 4 | error | NULL |
| 5 | 75 | 75 |
CREATE TABLE raw_data (id INT, amount_text VARCHAR(20));
INSERT INTO
raw_data
VALUES
(1, '150'),
(2, 'N/A'),
(3, '200'),
(4, 'error'),
(5, '75');SELECT id, amount_text, CASE WHEN amount_text ~ '^[0-9]+$' THEN amount_text::INT END AS amount FROM raw_data ORDER BY id;| id | amount_text | amount |
|---|---|---|
| 1 | 150 | 150 |
| 2 | N/A | NULL |
| 3 | 200 | 200 |
| 4 | error | NULL |
| 5 | 75 | 75 |
SQL Server uses TRY_CAST natively. PostgreSQL uses a regex-guarded CASE expression with :: cast syntax. MySQL and MariaDB use REGEXP in a CASE expression with CAST AS SIGNED. All return NULL for non-numeric values.