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 ::.
Code
-- 建两个测试类型: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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which tables appear in this script?
- `pg_cast` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.