PostgreSQL supports a CAST operator that is used to convert a value of one type to another.
Syntax: CAST ( expression AS target_type );
Let’s analyze the above syntax:
- First, specify an expression that can be a constant, a table column, an expression that evaluates to a value.
- Then, specify the target data type to which you want to convert the result of the expression.
The following statement converts a string constant to an integer:
SELECT CAST ('100' AS INTEGER);
If the expression cannot be converted to the target type, PostgreSQL will raise an error. See the following:
SELECT CAST ('10C' AS INTEGER);
This will result to the below-depicted error:
This example uses the CAST to convert a string to a date:
SELECT CAST ('2020-01-01' AS DATE), CAST ('01-OCT-2020' AS DATE);
This example uses the CAST() to convert the string ‘true’, ‘T’ to true and ‘false’, ‘F’ to false:
SELECT CAST('true' AS BOOLEAN), CAST('false' as BOOLEAN), CAST('T' as BOOLEAN), CAST('F' as BOOLEAN);
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.