Brightlane's logistics platform measures the elapsed time between when an order was placed and when it shipped.
Write a query to return the duration between the placement timestamp '2024-01-01 09:00:00' and the shipment timestamp '2024-03-15 12:00:00'.
Output:
- A single row with one column,
elapsed_time, typed as an interval.
Schema · ecommerce 5 tables
Run previews · Check grades
Write a query, then run it to see results here.
Worked solution Try it yourself first
SELECT
'2024-03-15 12:00:00'::TIMESTAMP - '2024-01-01 09:00:00'::TIMESTAMP AS elapsed_time The shape
Subtracting one TIMESTAMP from another returns an INTERVAL that carries both the day count and the hour count between them. Unlike DATE - DATE, which returns a plain integer, timestamp subtraction returns a duration type because the difference can include sub-day components.
Clause by clause
SELECT '2024-03-15 12:00:00'::timestamp - '2024-01-01 09:00:00'::timestamp AS elapsed_timecasts both literals toTIMESTAMPand subtracts the earlier from the later. PostgreSQL computes the difference and returns74 days 03:00:00: seventy-four whole days between the calendar positions, plus the three-hour gap between 09:00 and 12:00. The aliasAS elapsed_timenames the duration column.
Why this returns an INTERVAL and not an integer
The return type of date and timestamp subtraction depends on the input types. DATE - DATE returns an integer because dates have no time-of-day component and the gap can be expressed as a whole-number day count. TIMESTAMP - TIMESTAMP returns an INTERVAL because timestamps carry hours, minutes, and seconds, and a number cannot express that combined gap. The duration type can: it stores days and the sub-day remainder side by side.
You practiced timestamp - timestamp returning an INTERVAL — duration arithmetic produces a duration type, not a number.