Date components (DATE_PART)#
Sometimes you need to extract some specific numbers from the date, such as year, month and day. For such purposes you can use the DATE_PART
function.
In the following cell container, a postgres instance was started and a table was created that will be used for experiments.
--postgreSQL
CREATE TABLE tab(
var1 DATE
);
INSERT INTO tab (var1) VALUES
('2022-12-20'),
('2021-10-15'),
('2018-06-15');
SELECT * FROM tab;
CREATE TABLE
INSERT 0 3
SELECT 3
var1 |
---|
2022-12-20 |
2021-10-15 |
2018-06-15 |
Example#
Here is an example of how to use DATE_PART
. You must use the following syntax: DATE_PART('part', <column name>)
. So in the following cell all dates will be split into day, month and year:
--postgreSQL
SELECT
var1 "Original date",
DATE_PART('year', var1) "Year",
DATE_PART('month', var1) "Month",
DATE_PART('day', var1) "Day"
FROM tab;
SELECT 3
Original date | Year | Month | Day |
---|---|---|---|
2022-12-20 | 2022 | 12 | 20 |
2021-10-15 | 2021 | 10 | 15 |
2018-06-15 | 2018 | 6 | 15 |