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?
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.
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.
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 .
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.
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') );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With