Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

YYYY-MM column type in PostgreSQL

I need to a value associated to a month and a user in a table. And I want to perform queries on it. I don't know if there is a column data type for this type of need. If not, should I:

  • Create a string field and build year-month concatenation (2017-01)
  • Create a int field and build year-month concatenation (201701)
  • Create two columns (one year and one month)
  • Create a date column at the beginning of the month (2017-01-01 00:00:00)
  • Something else?

The objective is to run queries like (pseudo-SQL):

SELECT val FROM t WHERE year_month = THIS_YEAR_MONTH and user_id='adc1-23...';
like image 704
rap-2-h Avatar asked Apr 27 '17 12:04

rap-2-h


People also ask

What is the date format in PostgreSQL?

PostgreSQL uses the yyyy-mm-dd format for storing and inserting date values. If you create a table that has a DATE column and you want to use the current date as the default value for the column, you can use the CURRENT_DATE after the DEFAULT keyword. Let's look into some examples for better understanding.

What is the data type for year in PostgreSQL?

Introduction to the PostgreSQL DATE data type When storing a date value, PostgreSQL uses the yyyy-mm-dd format e.g., 2000-12-31. It also uses this format for inserting data into a date column.

How do I change the date format of a column in PostgreSQL?

You can change the format in the postgresql. conf file. The date/time styles can be selected by the user using the SET datestyle command, the DateStyle parameter in the postgresql. conf configuration file, or the PGDATESTYLE environment variable on the server or client.


2 Answers

I would suggest not thinking too hard about the problem and just using the first date/time of the month. Postgres has plenty of date-specific functions -- from date_trunc() to age() to + interval -- to support dates.

You can readily convert them to the format you want, get the difference between two values, and so on.

If you phrase your query as:

where year_month = date_trunc('month', now()) and user_id = 'adc1-23...'

Then it can readily take advantage of an index on (user_id, year_month) or (year_month, user_id).

like image 143
Gordon Linoff Avatar answered Oct 02 '22 06:10

Gordon Linoff


If you are interested in display values in YYYY-MM formt you can use to_char(your_datatime_colum,'YYYY-MM')

example:

SELECT to_char(now(),'YYYY-MM') as year_month
like image 35
Stepel Avatar answered Oct 02 '22 06:10

Stepel