6

I need to test if a field is numeric or not using standard SQL in BigQuery.

The example below works and is similar to what I have done in Cognos using TRANSLATE('mystring','1234567890.','') but its not very elegant.

SELECT
IF(LENGTH(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE('1234.56','1',''),'2',''),'3',''),'4',''),'5',''),'6',''),'7',''),'8',''),'9',''),'0',''),'.',''))=0,
'A number',
'Not a number')

4 Answers 4

21

You can use SAFE_CAST to try casting to a number. SAFE_CAST casts similar to CAST, but if casting fails, instead of erring null is returned.

For example you can do:

SAFE_CAST('1234567890' AS FLOAT64);

which will return 1.23456789E9

5

Thanks for both suggestions, both work a treat and I have gone for the SAFE_CAST option as it runs a fraction quicker.

#standardSQL
WITH `project.dataset.table` AS (
  SELECT '1234.56' col UNION ALL
  SELECT '1234.' col UNION ALL
  SELECT '1234' col UNION ALL
  SELECT '.56' col UNION ALL
  SELECT '1234..56' col UNION ALL
  SELECT 'a1234.56' 
 )
 SELECT
   col,
   if(SAFE_CAST(col AS FLOAT64) is null,'Not a number', 'A number')
 FROM `project.dataset.table`
2

but its not very elegant

Below examples for BigQuery Standard SQL

#standardSQL
WITH `project.dataset.table` AS (
  SELECT '1234.56' col UNION ALL
  SELECT '1234.' col UNION ALL
  SELECT '1234' col UNION ALL
  SELECT '.56' col UNION ALL
  SELECT '1234..56' col UNION ALL
  SELECT 'a1234.56' 
)
SELECT
  col,
  IF(LENGTH(REGEXP_REPLACE(col, r'[\d.]', '')) = 0, 'A number', 'Not a number') ,
  IF(REGEXP_CONTAINS(col, r'^\d*.?\d*$'), 'A number', 'Not a number') 
FROM `project.dataset.table`
-2

I think that we could use translate function to replace digits from 0 to 9 by 0 (let's say string_1 ) and then compare it to a string (let's say String_2) that equals to as much of 0 as then lengh of String_1.

(translate(src.NUM_BU , '0123456789', '0000000000')) 
= 
rpad('', length((translate(src.NUM_BU , '0123456789', '0000000000'))), '0')
1
  • A code-only answer is not high quality. While this code may be useful, you can improve it by saying why it works, how it works, when it should be used, and what its limitations are. Please edit your answer to include explanation and link to relevant documentation. Commented Jan 5, 2023 at 13:00

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.