How to cast the String to Date in Teradata?
Contents
CAST function in Teradata
CAST function is used to converts an expression of a given data type to a different data type in Teradata. If the given expression is not valid for the targeted data type, it will throw the error.
Syntax of CAST function in Teradata
1 |
CAST (<expression> AS sql_data_type) |
- expression – an expression with known data type to be cast as a different data type.
- sql_data_type – the new data type for expression.
Example : CAST the String to DATE
In some cases, we want to explicitly mention the Date value and compare the same with some of Date column in Teradata table. If we didn’t convert the String value to Date value, Teradata will not provide the correct result set.
To resolve this issue,We can use CAST function to convert the String data type to Date.
1 |
SELECT CAST( '2020/01/31' AS DATE); |
Lets execute this function against the table which contains Date columns. Here is the Student table with the Date column of Dateofbirth.
1 2 |
SELECT * FROM Master_DB.Student WHERE dateofbirth = CAST ('2019-12-01' AS DATE); |
Using the CAST function, we have converted the string value of ‘2019-12-01’ to Date value and extracting the required row from the Student table.
Lets use the Interval function to subtract the 1 month from the given Date value without CAST function.
1 2 |
SELECT * FROM Master_DB.Student WHERE dateofbirth > '2019-12-01' - INTERVAL '1' MONTH; |
Since we didn’t convert the String data type to Date, Interval function is not able to subtract month from 2019-12-01 and it throws the error as below.
If we apply the CAST function in this place, this error will be resolved and we will get the required output.
1 2 |
SELECT * FROM Master_DB.Student WHERE dateofbirth > CAST('2019-12-01' AS DATE) - INTERVAL '1' MONTH; |
Now the Cast function converted the String to Date type and the interval function has subtracted the one month from the Date value.
Recommended Articles
- How to get Current Date and Time in Teradata?
- Extract function in Teradata with examples
- Timestamp to Date conversion in Teradata
- Add Day/Month/Year to Date using Add_months and Interval function in Teradata?