DATE_PART

DATE_PART is a SQL function that is used to extract a specific part of a date such as year, month, day, etc., from a date or timestamp value.

DATE_PART(text, timestamp) returns double precision

  • text: This is the first parameter which represents the part of the date/time value aimed to be extracted. This is a string input and includes options such as year, month, day, hour, minute, second, etc.
  • timestamp: This is the second parameter representing the timestamp from which the value will be extracted. The format is standard date/time format

Example

SELECT DATE_PART('year', TIMESTAMP '2001-02-16 20:38:40');

Output

2001

Explanation

The DATE_PART function in PostgreSQL is used to extract a subfield (like year, month, day, etc.) from a date or time value. The example code provided fetches the ‘year’ element from the given timestamp.

DATE_PART(text, timestamp) RETURNS double precision

  • text: A field identifier that specifies which part of the timestamp data type will be extracted. This parameter is a string and it accepts various identifiers such as ‘year’, ‘month’, ‘day’, ‘hour’, ‘minute’, ‘second’.
  • timestamp: The source from which the function will extract the data. This parameter is a timestamp data type and it can be an entire timestamp (consisting of the date and the time) or specific parts of it.

Example

SELECT DATE_PART('month', TIMESTAMP '2022-01-31') AS Month_Part;

Output

Month_Part
----------
1

Explanation

The DATE_PART function is used to extract a part of a date or a time in SQL. In the provided example, ‘month’ is extracted from the specified timestamp ‘2022-01-31’, yielding an output of ‘1’, as January is the first month of the year.

For in-depth explanations and examples SQL keywords where you write your SQL, install our extension.