In PostgreSQL, the CAST
function is used to explicitly convert a value from one data type to another. It is an alternative to using the shorthand ::
operator for type conversion.
Syntax:
CAST (value AS target_type)
value
: The value or column you want to convert.target_type
: The target data type you want to convert the value to.
Examples:
1. Converting a String to an Integer
If you have a string representation of a number and you want to convert it to an integer, you can use CAST
.
SELECT CAST('123' AS INTEGER) AS converted_value;
Output:
converted_value
-----------------
123
2. Converting a Number to a String
You can convert a number to a string using CAST
.
SELECT CAST(456 AS TEXT) AS converted_value;
Output:
converted_value
-----------------
456
3. Converting a String to a Numeric
If you have a string with a floating-point number, you can convert it to a numeric type.
SELECT CAST('123 …