CAST converts a value from one data type to another inside PostgreSQL queries.
CAST forces PostgreSQL to treat a value as a different data type, enabling arithmetic, comparison, and formatting operations that require matching types.
Both work, but CAST is SQL-standard and easier to parameterize in ORMs or when migrating from SQL Server, making scripts more portable.
Use CAST(expression AS target_type) or the shorthand expression::target_type.You can also create custom casts for user-defined types.
Pass a format mask to to_date()
first, then CAST: CAST(to_date('2024-06-12','YYYY-MM-DD') AS DATE)
.This avoids runtime errors from malformed strings.
The query below casts order_date to DATE
, truncates to month, and sums totals.
SELECT date_trunc('month', CAST(order_date AS DATE)) AS month,
SUM(total_amount) AS monthly_revenue
FROM Orders
GROUP BY 1
ORDER BY 1;
Always validate input formats, prefer explicit CAST for readability, and index on the converted column if the query runs frequently.
Avoid implicit casting that hides performance hits and never CAST incompatible types without checking for data loss.
.
Yes. CAST(NULL AS INTEGER)
returns an INTEGER NULL, preserving type information for functions and UNION compatibility.
Only if you CAST the indexed column in the query, which can prevent index usage. Create a functional index on the casted expression to keep performance.
Only when the target type can accurately represent all source values. Casting NUMERIC to INTEGER can lose decimals and is not reversible.