← Back to PostgreSQL Course | Chapter 5: Filtering & Functions | Lesson 6 of 7

CAST

CAST converts a value to another data type inside a query.

In this page:

  1. CAST
Syntax
sql
SELECT CAST(value AS type);
SELECT value::type;

CAST

CAST(value AS type) works everywhere, and PostgreSQL also offers value::type. Common uses are turning text into numbers or dates, numbers into text for concatenation, and decimals into integers.

Explicit casts show intent and avoid surprising implicit conversions.

Note: :: is shorter, but CAST is portable across databases.

Example: CAST

sql
CREATE TABLE raw (id INTEGER PRIMARY KEY, amount_text TEXT);
INSERT INTO raw VALUES (1, '12'), (2, '7'), (3, '100');
SELECT SUM(CAST(amount_text AS INTEGER)) AS total FROM raw;
SELECT id, amount_text < '7' AS text_compare, CAST(amount_text AS INTEGER) < 7 AS number_compare FROM raw ORDER BY id;
SELECT CAST(9 AS REAL) / 4 AS ratio;

-- Output:
-- total
-- 119
-- id | text_compare | number_compare
-- 1 | 1 | 0
-- 2 | 0 | 0
-- 3 | 1 | 0
-- ratio
-- 2.25
Related Topics
Common Mistakes
  1. Casting strings that are not valid numbers
  2. Assuming casts round instead of truncating
  3. Ignoring precision loss
Chapter Summary
  • CAST(x AS type) or x::type
  • Text to number requires valid text
  • Numeric to integer truncates or rounds by type
  • Cast explicitly for clarity
🔒

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.