TO_CHAR Timestamp And Number Patterns
Map timestamps and numbers to display strings with format patterns — quoted literals, FM trimming, and currency via the locale setting.
Code
-- to_char 的格式模型 patterns 逐位映射,双引号包裹字面量
SELECT
to_char(TIMESTAMP '2026-06-14 09:05:03', 'YYYY-MM-DD HH24:MI:SS') AS iso_like,
to_char(TIMESTAMP '2026-06-14 09:05:03', 'DD Mon YYYY') AS human_date,
to_char(TIMESTAMP '2026-06-14 09:05:03', 'HH12:MI AM') AS clock_12h,
to_char(TIMESTAMP '2026-06-14 09:05:03', '"W"IW') AS iso_week;
-- 数字格式化:9 是数字占位、FM 去填充、D 是小数点、L 的货币符号取决于 lc_monetary
SELECT
to_char(1234567.891, 'FM999,999,990.00') AS grouped,
to_char(1234567.891, 'L9999990.00') AS money;
-- 用在 GROUP BY 里生成月份账期
SELECT to_char(placed_at, 'YYYY-MM') AS billing_month, SUM(total_cents)
FROM orders
GROUP BY 1
ORDER BY 1;Inside the snippet
Several statements share this file — SELECT, with orders among the objects involved.
Mechanically, the statements are built from: SUM aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order.
Using it
Run the statement against the orders table.
Key statements
SELECT to_char(placed_at, 'YYYY-MM') AS billing_month, SUM(total_cents)
FROM orders
GROUP BY 1
ORDER BY 1;
SELECT
to_char(1234567.891, 'FM999,999,990.00') AS grouped,
to_char(1234567.891, 'L9999990.00') AS money;
Interactive Tools for This Topic
Phone Number FormatterNormalize a phone number with an optional country code into E.164, RFC 3966, and grouped national formats, with digit-count validation.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.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.
FAQ
- What relations does the SQL touch?
- `orders` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.