PostgreSQL - DATES
While working with PostgreSQL Date datatypes, it is essential to know about the dates format when performing different operations on a database. Please note that, the datatype of column must be chosen while creating a new table in the database.
The different data types available in PostgreSQL for storing a date or a date/time value are mentioned below:
Data type | Description |
---|---|
DATE | A calendar date (year, month, day). Format: 'YYYY-MM-DD'. |
TIMESTAMP(fsp) | A date and time with no time zone. Format: 'YYYY-MM-DD HH:MM:SS'. |
TIMESTAMP(fsp) WITHOUT TIME ZONE | A date and time with no time zone. Format: 'YYYY-MM-DD HH:MM:SS'. |
TIMESTAMP(fsp) WITH TIME ZONE | A date and time with no time zone. Format: 'YYYY-MM-DD HH:MM:SS-TZ'. Equivalent to TIMESTAMPTZ. |
TIME(fsp) | A time of day with no time zone. Format: 'HH:MM:SS'. |
TIME(fsp) WITHOUT TIME ZONE | A time of day with no time zone. Format: 'HH:MM:SS'. |
TIME(fsp) WITH TIME ZONE | A time of day with time zone. Format: 'HH:MM:SS-TZ'. Equivalent to TIMETZ. |
Example: Create a table with date datatype
The below mentioned statement creates a table called Employee which contains five columns: EmpID, Name, City, Age and Date_of_Joining.
CREATE TABLE Employee ( EmpID INT NOT NULL, Name VARCHAR(255) NOT NULL, City VARCHAR(100), Age INT, Date_of_Joining DATE );
This will create a empty table named Employee containing five columns.
Example: Working with date datatype
Consider a database table called Employee with the following records:
EmpID | Name | City | Age | Date_of_Joining |
---|---|---|---|---|
1 | John | London | 25 | 2019-05-25 |
2 | Marry | New York | 24 | 2018-10-15 |
3 | Jo | Paris | 27 | 2017-06-09 |
4 | Kim | Amsterdam | 30 | 2014-04-21 |
5 | Ramesh | New Delhi | 28 | 2019-05-25 |
6 | Huang | Beijing | 28 | 2020-01-10 |
To fetch data of all employees present in the Employee table who joined the organization on '2019-05-25', the query is:
SELECT * FROM Employee WHERE Date_of_Joining = '2019-05-25';
This will produce the result as shown below:
EmpID | Name | City | Age | Date_of_Joining |
---|---|---|---|---|
1 | John | London | 25 | 2019-05-25 |
5 | Ramesh | New Delhi | 28 | 2019-05-25 |
Complete PostgreSQL Date and Time Reference
For a complete reference of all PostgreSQL Date and Time functions, see the PostgreSQL Data and Time Reference.