CREATE CAST Registers Conversions

CREATE CAST tells PostgreSQL how to convert between two types, with WITH/AS assignment or implicit context deciding which casts apply without an explicit ::.

SqlData Integrity

Code

snippet
-- 建两个测试类型:varchar 与自定义复合转换
CREATE TABLE casts_demo (raw text);

-- 显式转换(::)不需要 CAST 注册:任何类型对都能显式转
SELECT '42'::int, 42::text;

-- CREATE CAST ... WITHOUT FUNCTION:声明两类型二进制兼容,免函数调用
CREATE CAST (text AS varchar) WITHOUT FUNCTION;
SELECT 'hello'::varchar AS via_cast;

-- AS ASSIGNMENT:只允许出现在 INSERT/UPDATE 赋值位置,不允许隐式比较
CREATE CAST (text AS int) WITH INOUT AS ASSIGNMENT;

-- AS IMPLICIT:连比较与运算都自动转,最容易掩盖类型错误,慎用
SELECT 'implicit context' AS note;

-- 隐式转换是否生效可由 pg_cast 目录查询
SELECT castsource::regtype, casttarget::regtype, castcontext
FROM pg_cast
WHERE casttarget = 'int'::regtype
LIMIT 3;

How the logic moves

SELECT / CREATE statements share the script, touching pg_cast.

Mechanically, the statements are built from: a WHERE clause that keeps only the rows a statement is meant to touch; a row cap (LIMIT) bounding the result size.

Applying it

Point it at the pg_cast table — the LIMIT keeps the probe cheap while you tune the predicates.

Statements that matter

SELECT castsource::regtype, casttarget::regtype, castcontext
FROM pg_cast
WHERE casttarget = 'int'::regtype
LIMIT 3;
CREATE CAST (text AS int) WITH INOUT AS ASSIGNMENT;
CREATE CAST (text AS varchar) WITHOUT FUNCTION;

Interactive Tools for This Topic

FAQ

Which tables appear in this script?
`pg_cast` — referenced directly, no join needed.