pg_typeof Reveals Expression Types
pg_typeof prints the real type of any expression, exposing literal surprises like unknown-typed strings and numeric results from floor(numeric).
Code
-- pg_typeof() 返回表达式的实际类型名:字面量的类型可能出乎意料
SELECT
pg_typeof(17) AS int_literal, -- integer
pg_typeof(17.0) AS numeric_literal, -- numeric
pg_typeof('2026-01-01') AS string_literal, -- unknown:调用上下文才定型
pg_typeof('2026-01-01'::date) AS cast_date; -- date
-- 同一列里 int 与 numeric 混插:列类型决定一切,字面量只是输入
CREATE TABLE measures (value numeric);
INSERT INTO measures VALUES (1), (2.5);
SELECT pg_typeof(value), value FROM measures ORDER BY value;
-- 验证函数返回类型:floor(numeric) 返回 numeric,不会自动变 integer
SELECT pg_typeof(floor(3.7)) AS floor_numeric,
pg_typeof(floor(3.7)::int) AS cast_back;How it works
SELECT / INSERT / CREATE statements share the script, touching measures.
What the statements actually assemble: an ORDER BY that fixes the output order.
Using it
Run the statement against the measures table.
Key statements
SELECT
pg_typeof(17) AS int_literal, -- integer
pg_typeof(17.0) AS numeric_literal, -- numeric
pg_typeof('2026-01-01') AS string_literal, -- unknown:调用上下文才定型
pg_typeof('2026-01-01'::date) AS cast_date; -- date
SELECT pg_typeof(floor(3.7)) AS floor_numeric,
pg_typeof(floor(3.7)::int) AS cast_back;
SELECT pg_typeof(value), value FROM measures ORDER BY value;
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.Cron Expression ExplainerParse a five-field cron expression and get a field-by-field plain-English explanation plus a one-line human-readable schedule summary.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.
FAQ
- What relations does the SQL touch?
- The references are `measures`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.