TypesSQL standard

CAST

Converts a value from one type to another: text to a number, text to a date, a number to text.

Syntax

CAST(<value> AS <type>)
<value>::<type>

The ::<type> form does the same and is shorter, but it exists only in PostgreSQL. You need it when data arrives as text or when a type gets in the way of a calculation.

Data for the examples

orders

idcreated_atamount
12026-07-03 10:15:00120.50
22026-07-28 18:40:0080.25
32026-08-09 09:05:00199.99
42026-08-21 14:30:0045.00
52026-09-02 11:00:0064.75

These tables already exist in the sandbox — the examples below use them. Want to try this in your own database? Copy the SQL.

Text to a number and a date
SELECT CAST('42' AS integer) + 1 AS number,
CAST('2026-09-13' AS date) AS day;
numberday
432026-09-13
The same with ::
SELECT '42'::integer + 1 AS number,
'2026-09-13'::date + 7 AS week_later;
numberweek_later
432026-09-20

You can convert to a date and add days to it right away.

Order amounts as integers
SELECT id, amount,
CAST(amount AS integer) AS whole
FROM orders;
idamountwhole
1120.50121
280.2580
3199.99200
445.0045
564.7565

120.50 became 121: converting to integer rounds rather than drops the fractional part.

Watch out

If the text doesn't look like the target type, the query fails: CAST('abc' AS integer) — invalid input syntax for type integer. One “broken” row in a table breaks the whole query.

Converting a fractional number to integer rounds it: CAST(2.5 AS integer) gives 3. To simply drop the fractional part, use TRUNC.

:: is PostgreSQL only. If the query has to work in other DBMSs as well, write CAST(… AS …).

Related functions

Learn more in the course