Often in PostgreSQL you may want to subtract a specific number of minutes from a timestamp.
You can use the following basic syntax to do so:
SELECT *,
((start_time) - INTERVAL '10 MIN') AS ten_before
FROM emp;
This particular example subtracts 10 minutes from the timestamps in the start_time column of the table named emp and saves the results to a column named ten_before.
Note: To subtract a different number of minutes, simply change 10 MIN to a different number, e.g. 20 MIN.
The following example shows how to use this syntax in practice.
Example: How to Subtract Minutes from a Timestamp in PostgreSQL
Suppose that we create the following table named emp that contains information about when various employees at some company started working on a specific task:
-- create table named 'emp'
CREATE TABLE emp (
empID INT PRIMARY KEY,
start_time TIMESTAMP
);
-- add rows to the table
INSERT INTO emp VALUES (0001, '2024-09-23 04:15:23');
INSERT INTO emp VALUES (0002, '2024-04-01 04:05:56');
INSERT INTO emp VALUES (0003, '2024-10-26 07:00:10');
INSERT INTO emp VALUES (0004, '2024-12-14 09:15:00');
INSERT INTO emp VALUES (0005, '2024-12-07 12:56:30');
-- view all rows in table
SELECT * FROM emp;
empid | start_time
-------+---------------------
1 | 2024-09-23 04:15:23
2 | 2024-04-01 04:05:56
3 | 2024-10-26 07:00:10
4 | 2024-12-14 09:15:00
5 | 2024-12-07 12:56:30
Suppose that we would like to create a new column that subtracts 10 minutes from each timestamp in the start_time column.
We can use the following syntax to do so:
SELECT *,
((start_time) - INTERVAL '10 MIN') AS ten_before
FROM emp;
empid | start_time | sales | ten_before
-------+---------------------+-------+---------------------
1 | 2024-09-23 04:15:00 | 134 | 2024-09-23 04:05:00
2 | 2024-04-01 04:05:00 | 201 | 2024-04-01 03:55:00
3 | 2024-10-26 07:00:00 | 155 | 2024-10-26 06:50:00
4 | 2024-12-14 09:15:00 | 98 | 2024-12-14 09:05:00
5 | 2024-12-07 12:56:00 | 67 | 2024-12-07 12:46:00
The resulting table contains a new column named ten_before that contains the timestamp from the start_time column with 10 minutes subtracted from it.
Feel free to use similar syntax to subtract a specific number of minutes from a timestamp column in your own table.
Additional Resources
The following tutorials explain how to perform other common tasks in PostgreSQL:
PostgreSQL: Calculate Timestamp Difference in Hours
PostgreSQL: Calculate Timestamp Difference in Minutes
PostgreSQL: Calculate Difference Between Dates in Days
