← Back to PostgreSQL Course | Chapter 3: Data Types | Lesson 7 of 7

Type casting

Casting converts a value from one type to another with CAST or the :: shortcut.

In this page:

  1. Type casting
Syntax
sql
SELECT CAST(expression AS type);
SELECT expression::type;

Type casting

CAST(expr AS type) is standard SQL and works in every database, while expr::type is PostgreSQL's shorter form. Casting text to a number fails if the text is not a valid number.

Integer division truncates, so cast one side to a decimal type when you need a fractional result. The example uses CAST so it also runs on SQLite.

Note: In PostgreSQL, 42::integer and CAST(42 AS integer) are equivalent.

Example: Type casting

sql
SELECT CAST('42' AS INTEGER) + 8 AS sum_int;
SELECT 7 / 2 AS integer_division, CAST(7 AS REAL) / 2 AS decimal_division;
SELECT CAST(3.99 AS INTEGER) AS truncated;
SELECT CAST(12345 AS TEXT) || ' items' AS label;

-- Output:
-- sum_int
-- 50
-- integer_division | decimal_division
-- 3 | 3.5
-- truncated
-- 3
-- label
-- 12345 items
Related Topics
Common Mistakes
  1. Dividing integers and expecting decimals
  2. Casting invalid text to numbers
  3. Relying on implicit conversions
Chapter Summary
  • CAST(expr AS type) is standard
  • :: is the PostgreSQL shortcut
  • Invalid text fails to cast
  • Cast before dividing for decimals
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.