How to set a Postgresql default value datestamp like 'YYYYMM'?
Just in case Milen A. Radev doesn't get around to posting his solution, this is it:
CREATE TABLE foo (
key int PRIMARY KEY,
foo text NOT NULL DEFAULT TO_CHAR(CURRENT_TIMESTAMP,'YYYYMM')
);
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')
);