CAST
PG 7.4+→ target_typeConverts a value to the specified data type. SQL-standard syntax. Equivalent to the :: operator in PostgreSQL.
Signature
CAST ( expression AS type ) → typeParameters
| Parameter | Type | Description |
|---|---|---|
| expression | any | Value to convert |
| target_type | type name | The destination data type |
Examples
SELECT CAST('42' AS integer);42Truncates toward zero
SELECT CAST(3.7 AS integer);3SELECT CAST('2025-03-07' AS date);2025-03-07Casting NULL to any type stays NULL
SELECT CAST(NULL AS integer);NULLSELECT CAST(true AS integer);1Wrapping an indexed column in CAST inside a WHERE clause forces a sequential scan because PostgreSQL cannot use the index on the raw column.
✓ Instead: Cast the literal to match the column type, not the other way around. E.g., use `WHERE created_at = '2025-01-01'::date` rather than `WHERE CAST(created_at AS date) = '2025-01-01'`.
`CAST(x AS int)` is SQL standard and works in all databases. `x::int` is PostgreSQL-specific shorthand. Use `::` in scripts, `CAST` in code meant to run on multiple database engines.
SELECT '3.14'::numeric, CAST('3.14' AS numeric);3.14 | 3.14 (identical results)