Casts#
What are Casts in PostgreSQL?#
In PostgreSQL, a CAST defines how to convert a value from one data type to another.
In simple words:
Casts tell PostgreSQL how to change one data type into another data type.
Example
SELECT '123'::integer;
- Here:
β123β is text
::integer tells PostgreSQL to cast text β integer
Result:
123
This conversion works because a cast exists from text β integer.
Why Casts Exist#
- PostgreSQL supports many data types:
text
integer
numeric
date
timestamp
json / jsonb
uuid
custom types
- PostgreSQL must know:
Which conversions are allowed
How safe they are
Whether they are automatic or manual
That logic lives in Casts.
Where Casts Live (Important)#
Casts are database-level objects.
Thatβs why in pgAdmin you see:
Database
βββ Casts
They are not per table
They are not per schema
They apply to the entire database.
Types of Casts#
PostgreSQL supports three kinds of casts:
1οΈβ£ Implicit Casts (Automatic)
PostgreSQL converts automatically.
Example:
SELECT 10 + 2.5;
- Here:
10 β integer
2.5 β numeric
PostgreSQL implicitly casts 10 β numeric
β No error
β Automatic conversion
2οΈβ£ Assignment Casts
Used when assigning values.
CREATE TABLE test (
price numeric
);
INSERT INTO test VALUES (10);
10 (integer) β numeric
Allowed due to an assignment cast.
3οΈβ£ Explicit Casts (Manual)
You must specify the cast.
SELECT CAST('2024-01-01' AS date);
Or
SELECT '2024-01-01'::date;
PostgreSQL will not guess unless you tell it.
Real Example: Why Casts Matter#
Without proper cast
SELECT 'abc'::integer;
β Error:
invalid input syntax for type integer
The cast exists, but the value is invalid.
JSON Example
SELECT '{"a":1}'::jsonb;
- Here:
text β jsonb
Works because PostgreSQL has a cast defined
Creating Your Own Cast (Advanced)#
You usually do NOT need this, but PostgreSQL allows it.
Example: Custom cast
CREATE CAST (text AS uuid)
WITH FUNCTION uuid(text)
AS EXPLICIT;
β οΈ Only advanced users do this
β οΈ Can break queries if misused
When Should You Care About Casts?#
- You should understand casts if:
β You get confusing type errors
β You work with JSON / dates / numeric
β You write complex SQL
β You define custom types
β You build database frameworks (like you)
When You Can Ignore Casts#
- You donβt need to manage casts manually if:
You write normal CRUD queries
You use ORMs (Django, SQLAlchemy)
You donβt define custom types
PostgreSQL handles them automatically.
Summary
Note
Casts in PostgreSQL define how one data type can be converted into another. They enable PostgreSQL to safely and correctly handle operations involving different data types across the database.