make_date And make_interval Builders
Build date and interval values from integers with make_date, make_timestamptz, and make_interval instead of fragile string parsing.
Code
-- 构造器吃整数入参:拼接字符串再隐式转换的坑全绕开
SELECT make_date(2026, 11, 15) AS report_day,
make_timestamptz(2026, 11, 15, 9, 30, 0.0, 'UTC') AS shift_start,
make_interval(years => 1, months => 2, days => 3,
hours => 4, mins => 5, secs => 6.0) AS retention;
-- 参数来自表里的整数列时尤其顺手:无需 to_char/to_timestamp 往返
CREATE TABLE service_terms (
service_id int PRIMARY KEY,
start_year int NOT NULL,
start_mon int NOT NULL,
start_day int NOT NULL
);
INSERT INTO service_terms VALUES (1, 2026, 11, 15), (2, 2026, 2, 29);
SELECT service_id,
make_date(start_year, start_mon, start_day) AS starts_on,
make_date(start_year, start_mon, start_day) + interval '1 year' AS renews_on
FROM service_terms
ORDER BY service_id;
-- 非法日期(2 月 30 日)当场报错,而不是存进脏数据
SELECT make_date(2026, 2, 30);
DROP TABLE service_terms;What the code does
Several statements share this file — SELECT / INSERT / CREATE, with service_terms among the objects involved.
What the statements actually assemble: an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Applying it
Run it in the service_terms database context.
Statements that matter
SELECT make_date(2026, 11, 15) AS report_day,
make_timestamptz(2026, 11, 15, 9, 30, 0.0, 'UTC') AS shift_start,
make_interval(years => 1, months => 2, days => 3,
hours => 4, mins => 5, secs => 6.0) AS retention;
SELECT service_id,
make_date(start_year, start_mon, start_day) AS starts_on,
make_date(start_year, start_mon, start_day) + interval '1 year' AS renews_on
FROM service_terms
ORDER BY service_id;
CREATE TABLE service_terms (
service_id int PRIMARY KEY,
start_year int NOT NULL,
start_mon int NOT NULL,
start_day int NOT NULL
);
Interactive Tools for This Topic
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.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.Date Add/Subtract CalculatorAdd or subtract days, weeks, months, or years from a date, clamping month ends such as January 31 plus one month.Date Difference CalculatorCalculate the number of days, weeks, whole months, and years between two ISO dates, computed in UTC.
FAQ
- Which relations are involved here?
- `service_terms`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.