CAST converts a value from one data type to another.
CAST changes a value’s data type, letting you treat, store, or compare the value as another compatible type. It is ANSI-SQL compliant and mirrors Oracle’s CAST function, so migration is straightforward.
Use either the keyword CAST(value AS target_type) or the shorthand value::target_type. Both perform the same conversion.
Convert customer IDs stored as text to integers: SELECT CAST(id AS integer) FROM Customers;
.The query returns integer IDs that can be summed or compared numerically.
Strip time parts for daily sales: SELECT order_date::date, SUM(total_amount) FROM Orders GROUP BY order_date::date;
. The cast enables GROUP BY on pure dates.
Down-casting can lose precision. Example: SELECT CAST(price AS numeric(10,2)) FROM Products;
. Always pick a scale and precision large enough to avoid rounding errors.
Yes.SELECT CAST(NULL AS varchar);
makes the planner treat the NULL as varchar for union or comparison operations.
The :: operator is shorter and favored in PostgreSQL-specific code. Use CAST() when you need Oracle-compatible SQL or want clearer ANSI syntax.
Extract and cast: SELECT (details->>'quantity')::integer AS qty FROM OrderItems;
.The text extracted from JSON is cast to integer for arithmetic.
1) Validate input formats before casting strings.
2) Use domain-specific types (e.g., money) where appropriate.
3) Index the casted expression if querying often.
1) Casting incompatible types: CAST('abc' AS integer)
throws an error. Use regex or try_cast-like PL/pgSQL wrappers to pre-validate.
2) Precision loss: casting 19.999 to numeric(5,2) rounds to 20.00.Pick correct precision.
Replace Oracle’s CAST with identical PostgreSQL syntax. Most expressions work unchanged. Only date format masks differ; use TO_DATE
or TO_TIMESTAMP
first, then CAST if needed.
.
Performance is identical; both call the same internal cast function. Choice is purely stylistic.
Yes. Superusers can CREATE CAST (source_type AS target_type) WITH FUNCTION …
to support user-defined types.
Use TO_DATE first: SELECT CAST(TO_DATE('2024-05-12','YYYY-MM-DD') AS date);
. This validates the format before casting.