CAST converts a value from one data type to another in PostgreSQL.
CAST changes the data type of a value or column, letting you treat it as another compatible type for calculations, comparisons, or storage.
Use CAST when joining columns of different types, formatting output, inserting data that needs conversion, or enforcing precision on arithmetic.
In PostgreSQL you can use either the CAST(expr AS type) function or the shorthand expr::type operator. Both are interchangeable.
Common conversions include text ↔ integer, numeric ↔ text, timestamp ↔ date, and UUID ↔ text. Conversions that lose precision may need an explicit USING clause.
Simple casts are cheap, but casting on indexed columns can prevent index use. Pre-cast data or create functional indexes to keep queries fast.
Convert order totals from numeric to text for JSON export:SELECT id, total_amount::text AS total_str FROM Orders;
Join integer customer IDs with text input:SELECT * FROM Customers c JOIN Orders o ON c.id = CAST($1 AS integer);
Cast once, not repeatedly in subqueries. Prefer explicit casts over implicit to avoid surprises. Validate that the target type can hold every source value.
See below for two frequent errors and their fixes.
Yes. Create a cast with CREATE CAST
after defining conversion functions between the types.
Yes. ::
is just shorthand. Use the style your team prefers for readability.
Extract the leaf value with the JSON operators (->>
for text) and then cast: (json_col->>'price')::numeric
.