57

I am looking for a Built-in UDF to convert values of a string column to integer in my hive table for sorting using SELECT and ORDER BY. I searched in the Language Manual, but no use. Any other suggestions also welcome.

mrsrinivas
  • 34,112
  • 13
  • 125
  • 125
Srinivas
  • 2,479
  • 8
  • 47
  • 69

3 Answers3

132

cast(str_column as int)

From: Language manual UDFs - type conversion functions

Joe K
  • 18,204
  • 2
  • 36
  • 58
  • Just curious, but will this return a unique int for every possible string, including non-ascii ones (e.g.: foreign words or phrases)? – Ward W Jun 11 '18 at 21:22
  • 3
    @wardw123 it will return `NULL` if string is non-numeric or too large/small to fit `int` data type – mangusta Oct 19 '18 at 04:43
7

If the value is between –2147483648 and 2147483647, cast(string_filed as int) will work. else cast(string_filed as bigint) will work

    hive> select cast('2147483647' as int);
    OK
    2147483647
    
    hive> select cast('2147483648' as int);
    OK
    NULL
    
    hive> select cast('2147483648' as bigint);
    OK
    2147483648
Anil
  • 301
  • 4
  • 9
-2

It would return NULL but if taken as BIGINT would show the number

ravi
  • 15
  • 3