The Apache Hive CAST function is a type conversion function that converts data types from one to another. It can convert a string to an integer, an integer to a decimal, a string to a date, and a date to a timestamp, among other things.
For a better understanding, look at the examples below.
Test Data:
SELECT * FROM testdate;
Result:
Date1 Date2
2021-07-08 2021-07-08 02:49:00
SELECT CAST(date2 AS date) from testdate;
Result: 2021-07-08
The above statement converted the timestamp value into date format.
SELECT CAST(‘2016-10-20’ AS Date);
Result: 2016-10-20
The above statement converted the string value into date format.
SELECT CAST(date2 AS BIGINT) FROM testdate;
Result: 1625737740
The above statement converted the timestamp value into integral representation i.e. BIGINT data type.
SELECT FROM_UNIXTIME(1625737740);
Result: 2021-07-08 02:49:00
The above statement converted the timestamp value which is in an integral representation back into date format.
SELECT TO_DATE(FROM_UNIXTIME(1625737740));
Result: 2021-07-08
The above statement converted the timestamp value which is in an integral representation into a simple date format.
SELECT CAST(1 AS FLOAT);
Result: 1.0
The above statement converted the integral value into decimal format.
SELECT CAST(1.99 AS INT);
Result: 1
The above statement converted the decimal value into integral representation.
SELECT CAST(date1 AS timestamp) from testdate;
Result: 2021-07-08 00:00:00
The above statement converted the date value into timestamp format.
SELECT CAST(‘1.99’ AS float);
Result: 1.99
The above statement converted the string value into decimal format.
SELECT CAST(‘1.99’ AS int);
Result: 1
The above statement converted the string value into integral representation.
Hope you find this article helpful.
Please subscribe for more interesting updates.