Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a Postgresql default value datestamp like 'YYYYMM'?

As title, how can I set a table's column to have the default value the current year and month, in format 'YYYYMM', like 200905 for today?

like image 632
Strae Avatar asked May 26 '09 13:05

Strae


People also ask

How do I change the default value of a column in PostgreSQL?

Changing a Column's Default Value. To set a new default for a column, use a command like: ALTER TABLE products ALTER COLUMN price SET DEFAULT 7.77; Note that this doesn't affect any existing rows in the table, it just changes the default for future INSERT commands.

How do I change the default date in PostgreSQL?

Postgres DATE data type You can design a Postgres table with a DATE column and use the keyword DEFAULT CURRENT_DATE to use the current system date as the default value in this column.

How do I change the date format from YYYY-MM-DD in PostgreSQL?

1) Get the current date To get the current date and time, you use the built-in NOW() function. However, to get the date part only (without the time part), you use the double colons (::) to cast a DATETIME value to a DATE value. The result is in the format: yyyy-mm-dd .

What is Postgres default value?

If no default value is declared explicitly, the default value is the null value. This usually makes sense because a null value can be considered to represent unknown data.


1 Answers

Please bear in mind that the formatting of the date is independent of the storage. If it's essential to you that the date is stored in that format you will need to either define a custom data type or store it as a string. Then you can use a combination of extract, typecasting and concatenation to get that format.

However, I suspect that you want to store a date and get the format on output. So, something like this will do the trick for you:

    CREATE TABLE my_table     (     id serial PRIMARY KEY not null,     my_date date not null default CURRENT_DATE     );  (CURRENT_DATE is basically a synonym for now() and a cast to date). 

(Edited to use to_char).

Then you can get your output like:

SELECT id, to_char(my_date, 'yyyymm') FROM my_table; 

Now, if you did really need to store that field as a string and ensure the format you could always do:

CREATE TABLE my_other_table ( id serial PRIMARY KEY not null, my_date varchar(6) default to_char(CURRENT_DATE, 'yyyymm') ); 
like image 166
Nic Gibson Avatar answered Oct 23 '22 13:10

Nic Gibson