Type Conversion

Updated · 6 min read
mediumPostgreSQL 18sqlcasttype-conversionconvertinterview

CAST(value AS type) converts a value from one type to another, such as text to a number, or a number to text. Every value has a type, and many operations need a particular one: padding needs text, division needs a decimal, and comparing needs both sides to agree. Usually you convert on purpose, as lpad(payment_id::text, 5, '0') did in String Functions. Sometimes the database converts for you, and that's where surprises come from. This lesson covers CAST and ::, what happens when a conversion fails or rounds, and the implicit conversions to watch for.

In One Minute

  • CAST(value AS type) is the standard; value::type is PostgreSQL's short form.
  • Conversions that can't work fail: CAST('abc' AS integer) is an error.
  • Decimal to integer rounds (3.7 becomes 4); use trunc first to cut instead.
  • Text compares as text: '12' < '9' is true, because '1' sorts before '9'.
  • SQL Server and MySQL also have CONVERT; PostgreSQL has to_char, to_date and to_number for formatted text.

CAST and ::

SQL
CAST(value AS type)
value::type          -- PostgreSQL only
SQL▶ Try it
SELECT CAST('450.00' AS numeric) + 1 AS with_cast,
       '450.00'::numeric + 1         AS with_colons,
       CAST(paid_on AS text)         AS date_as_text
FROM payments
WHERE payment_id = 1;
Output
 with_cast | with_colons | date_as_text
-----------+-------------+--------------
    451.00 |      451.00 | 2025-08-28
(1 row)

Both forms do the same thing. :: is shorter and common in PostgreSQL code; CAST is standard SQL and works in PostgreSQL, MySQL, SQL Server, Oracle and SQLite, so it's the choice for portable queries (MS Access uses functions such as CDbl and CStr instead). Converting to text is how you join numbers or dates into labels:

SQL▶ Try it
SELECT student_id::text || '-' || course_id::text AS enrollment_code
FROM enrollments
ORDER BY student_id, course_id
LIMIT 3;
Output
 enrollment_code
-----------------
 101-1
 101-2
 101-3
(3 rows)

Without the casts, student_id || '-' would work (PostgreSQL converts one side), but 5 || 3, two numbers, fails with operator does not exist: integer || integer.

When a Conversion Fails or Rounds

A conversion that can't produce a valid value is an error, not a NULL:

SQL▶ Try it
SELECT CAST('abc' AS integer);
Output
ERROR:  invalid input syntax for type integer: "abc"

Converting a decimal to an integer rounds; converting to a smaller NUMERIC rounds the extra places:

SQL▶ Try it
SELECT CAST(3.7 AS integer)       AS rounds_up,
       CAST(-3.5 AS integer)      AS rounds_away_from_zero,
       trunc(3.7)::integer        AS cut_first,
       CAST(450.567 AS numeric(6,2)) AS to_cents;
Output
 rounds_up | rounds_away_from_zero | cut_first | to_cents
-----------+-----------------------+-----------+----------
         4 |                    -4 |         3 |   450.57
(1 row)

3.7 becomes 4, not 3. If you want the whole-number part, trunc it first. And a value too big for the target, such as CAST(1234567.00 AS numeric(6,2)), fails with numeric field overflow, as in SQL Data Types.

3.7 casts to 4; trunc(3.7) casts to 3; 'abc' can't become an integer

Implicit Conversion

PostgreSQL converts some values for you, when the intent is clear. A quoted literal has no type until it's used, so it takes whatever type the context needs:

SQL▶ Try it
SELECT payment_id
FROM payments
WHERE paid_on = '2025-12-19';
Output
 payment_id
------------
          7
(1 row)

'2025-12-19' became a DATE because it's compared with paid_on. That's convenient, and it's why the course's WHERE clauses work. But a value that already is text isn't converted silently: '5'::text + 3 fails with operator does not exist: text + integer.

Text compares as text, character by character. That gives the wrong order for numbers stored as text:

SQL▶ Try it
SELECT '12'::integer < '9'::integer AS compared_as_numbers,
       '12' < '9'                   AS compared_as_text;
Output
 compared_as_numbers | compared_as_text
---------------------+------------------
 f                   | t
(1 row)

As numbers, 12 isn't less than 9. As text, '12' comes first, because '1' sorts before '9', the same reason file names sort file10 before file9. Store numbers in number columns, and cast before comparing text that holds numbers.

As numbers 12 is greater than 9; as text '12' sorts before '9' because '1' comes before '9'

CONVERT and Friends in Other Databases

TaskPostgreSQLMySQLSQL ServerOracle
Standard castCAST(x AS numeric)CAST(x AS DECIMAL)CAST(x AS DECIMAL)CAST(x AS NUMBER)
Short formx::numericnonenonenone
Convert functionto_number(x, '999.99')CONVERT(x, DECIMAL)CONVERT(DECIMAL, x)TO_NUMBER(x)
Text to dateto_date(x, 'MM/DD/YYYY')STR_TO_DATE(x, '%m/%d/%Y')CONVERT(DATE, x, 101)TO_DATE(x, 'MM/DD/YYYY')

Note the argument order: MySQL writes CONVERT(value, type) and SQL Server CONVERT(type, value). SQL Server also has TRY_CAST, which returns NULL instead of an error when a conversion fails. Tabs showing each database's version are coming to this course.

The same conversion as CAST, ::, MySQL CONVERT(value, type) and SQL Server CONVERT(type, value)

Common Mistakes

Expecting CAST to truncate. 3.7 becomes 4. Use trunc first.

Comparing numbers stored as text. '12' < '9' is true. Cast, or better, store numbers as numbers.

Joining two numbers with ||. Cast at least one to text.

Mixing up CONVERT argument order. MySQL is (value, type), SQL Server (type, value).

Interview Corner

What's the difference between CAST and :: in PostgreSQL?

They do the same conversion. CAST(x AS type) is standard SQL and works everywhere; x::type is PostgreSQL's shorter syntax.

What does CAST(3.7 AS INTEGER) return in PostgreSQL?

4. Converting a decimal to an integer rounds. Use trunc or floor first to cut off the fraction instead.

Why can numbers stored as text sort incorrectly?

Text is compared character by character, so '12' sorts before '9' because '1' comes before '9'.

Practice

Challenge: Show each payment's payment_id and its amount as a whole number of dollars, cut off (not rounded), sorted by payment_id. Name the column whole_dollars.

Show solution
SQL▶ Try it
SELECT payment_id, trunc(amount_usd)::integer AS whole_dollars
FROM payments
ORDER BY payment_id;
Output
 payment_id | whole_dollars
------------+---------------
          1 |           450
          2 |           250
          3 |           250
          4 |           550
          5 |           200
          6 |           225
          7 |           225
(7 rows)

All the amounts here end in .00, so rounding and cutting agree; with an amount like 225.75, CAST(225.75 AS integer) would give 226, while trunc(225.75)::integer gives 225.

Quick check: Type conversion

3 questions
1What does CAST(3.7 AS integer) return in PostgreSQL?
2What does SELECT '12' < '9' return?
3Which form is standard SQL, supported across the major databases?

Key Takeaways

You want toWrite
Text to numberCAST('450.00' AS numeric) or '450.00'::numeric
Number to textpayment_id::text
Whole part, no roundingtrunc(amount_usd)::integer
Formatted text to dateto_date('12/19/2025', 'MM/DD/YYYY')

Was this tutorial helpful?

Lesson 55 of 115