CAST converts a value from one data type to another in PostgreSQL.
CAST lets you convert numbers, text, dates, JSON, and more to the exact data type your query or application expects, preventing type-mismatch errors and enabling index use.
PostgreSQL offers two interchangeable forms: CAST(expression AS target_type)
and the shorthand expression::target_type
. Both return a new value without altering the source column.
Wrap the numeric column or literal and specify TEXT
:SELECT total_amount::TEXT AS amount_str FROM Orders;
This is handy when concatenating values for reports.
Provide a parsable string:SELECT CAST('2024-06-15 12:34' AS TIMESTAMP);
Invalid formats trigger Invalid input syntax for type timestamp
.
Yes. Example converting cents to dollars:SELECT id, total_amount/100.0 AS dollars, (total_amount/100.0)::NUMERIC(10,2) AS dollars_exactFROM Orders;
Use CAST to align key types:SELECT *FROM Orders oJOIN Customers c ON o.customer_id::TEXT = c.id::TEXT;
Converting both sides avoids planner warnings.
::
is purely syntactic sugar around CAST()
. Use whichever style improves readability in your team.
• Prefer explicit casts in production code.
• Match precision/scale when casting numerics.
• Avoid casting away indexes; cast the literal instead of the column.
• Validate text formats before casting to dates or JSON.
Using wrong date format: CAST('06/15/2024' AS DATE)
fails if datestyle
is ISO
. Fix with TO_DATE('06/15/2024','MM/DD/YYYY')
.
Casting NULL without type: CAST(NULL AS TEXT)
or NULL::TEXT
required; bare NULL
keeps an unknown type and breaks unions.
Yes. PostgreSQL uses CAST/:: while SQL Server and MySQL use CONVERT. Functionally, they perform the same type conversion.
No. CAST returns a new value at query time. To persist the change, use an UPDATE statement.
Superusers can define CREATE CAST
between user-defined types, but this is rare outside advanced extensions.