Calculating Time Differences with INTERVAL
In this step, you will learn how to calculate the time difference between two events using the INTERVAL
data type.
To calculate the time difference, you can subtract one timestamp from another. The result will be an INTERVAL
value representing the difference.
Let's calculate the time difference between the 'Follow-up Meeting' and the 'Conference Call'. To do this, you can use a subquery or join the table to itself. Here's an example using a join:
SELECT
e1.event_name AS event1,
e2.event_name AS event2,
e2.event_time - e1.event_time AS time_difference
FROM
events e1
JOIN
events e2 ON e1.event_name = 'Conference Call' AND e2.event_name = 'Follow-up Meeting';
This query joins the events
table to itself, aliasing the tables as e1
and e2
. It then selects the event_name
from both tables and calculates the time difference between the event_time
of the 'Follow-up Meeting' and the 'Conference Call'. The output will be:
event1 | event2 | time_difference
----------------+-----------------+---------------------
Conference Call | Follow-up Meeting | 1 day 02:00:00
(1 row)
The time_difference
column shows the interval between the two events.
You can also extract specific components from the INTERVAL
value using the EXTRACT
function. For example, to extract the number of days from the time difference, you can use the following query:
SELECT
e1.event_name AS event1,
e2.event_name AS event2,
EXTRACT(DAY FROM (e2.event_time - e1.event_time)) AS days_difference
FROM
events e1
JOIN
events e2 ON e1.event_name = 'Conference Call' AND e2.event_name = 'Follow-up Meeting';
This query extracts the number of days from the time_difference
and displays it as days_difference
.
Finally, exit the PostgreSQL shell:
\q
This will return you to the terminal.