CAST converts a value from one data type to another using standard or Redshift-specific syntax.
CAST converts a literal, column, or expression to a target data type so functions, joins, and comparisons work without type errors.
Use CAST when implicit conversion fails, when you need exact precision (e.g., money → numeric), or when joining columns stored as different types.
Place CAST(expr AS target_type) in your SELECT, WHERE, GROUP BY, or JOIN clauses, or use the shorthand expr::target_type.
You can cast between compatible types like varchar ⇆ int, numeric ⇆ float, timestamp ⇆ date. Incompatible casts return an error.
Redshift validates each row; non-numeric text such as ‘ABC’ triggers an error when CASTing to int. Clean data or use NULLIF to skip bad rows.
To calculate 10% VAT on total_amount stored as varchar, CAST it to numeric, then multiply.
SELECT id,
total_amount::numeric * 0.10 AS vat
FROM Orders;
Wrap CAST in COALESCE to replace NULL with a default value, ensuring downstream calculations stay robust.
Cast columns in staging tables rather than on the fly in large analytic queries. This lets Redshift scan pre-typed data.
Mistake 1: Casting malformed data. Fix by using REGEXP or TRY_CAST. Mistake 2: Forgetting precision (numeric(10,2)). Fix by always specifying scale.
TRY_CAST(expr AS type) returns NULL instead of error on bad rows, perfect for incremental loads.
Yes. The double-colon is simply shorthand for the CAST function.
Casting on large columns forces on-the-fly conversion and can slow scans. Stage data in the correct type when possible.
Standard CAST throws an error and stops the query. TRY_CAST returns NULL so the query completes.