mariadb/mysql - How to make a date column with sysdate/curdate? - mysql

I want to make a column in my table that has the equivalent functionality as the oracle sysdate variable as the default value. So when a row is inserted (without the date, the current sysdate is used). what is the query to create this table?
Also should I allow nulls for this column, how would that work?
Also, I want to be able to insert a row into this table, such that the functionality occurs. Please provide sample insert query that uses this functionality.
Also, I want to be able to do the same for the DATETIME column type.
Thanks in advance.

This is pretty well explained in the documentation:
TIMESTAMP and DATETIME columns can be automatically initializated and
updated to the current date and time (that is, the current timestamp).
The syntax looks like:
create table t (
. . .,
createdAt datetime not null default current_timestamp
);
If you are giving the column a default value, then you might as well declare it as NOT NULL.
You can also do the same thing for updates:
updatedAt datetime not null default current_timestamp on update current_timestamp

Related

How to store unix timestamp as int with default and on update?

I have been updating my MySQL tables with the following:
ALTER TABLE logs ADD COLUMN updateTimeStamp timestamp DEFAULT current_timestamp() ON UPDATE current_timestamp;
This stores the timestamp in the format of
2021-12-29 15:21:34
I tried originally to do the alter like so:
ALTER TABLE logs ADD COLUMN updateTimeStamp timestamp DEFAULT unix_timestamp() ON UPDATE unix_timestamp();
so that could store like 12121232, however that results in an error.
Is there anyway I can achieve the default and on update and store the timestamp in the format of 1212112, instead of the human readable datetime?
I know I can do SELECT unix_timestamt(columnname), but ideally I don't want to do that.
If you want to automatically get an integer when you select the column, you need to make it an int (or int unsigned) type. You can set its default with default (unix_timestamp()) (the extra parentheses are needed when not using one of the historically allowed default values). And you will need to add a trigger to set it on update.
But I suggest you not do that; just use a timestamp type. You just make future trouble for yourself by not using the type designed to store timestamps.

MySQL DATE field with default CURDATE(). NOT DATETIME

It is possible to set default value on DATE (NOT DATETIME) column in MySQL 5.7 to current date?
I try this (generated by Workbench):
ALTER TABLE `db`.`table` CHANGE COLUMN `column` `column` DATE NOT NULL DEFAULT CURDATE() ;
but not works for me.
(no data in table)
No, you cannot. The documentation is pretty clear on this:
This means, for example, that you cannot set the default for a date
column to be the value of a function such as NOW() or CURRENT_DATE.
The exception is that you can specify CURRENT_TIMESTAMP as the default
for TIMESTAMP and DATETIME columns. See Section 12.3.5, “Automatic
Initialization and Updating for TIMESTAMP and DATETIME”.
You can do one of the following:
Set up a column with a default value for the DATETIME. Create view that extracts the date as a separate column.
Create an insert trigger to set the date column.
There is a way you can do this if you have another column that has a for example a datetime field with a default of NOW(). See this post:

Force MySQL to update TIMESTAMP column

I believe I have set my 5.6.17 ver MySQL server to recognize IANA TZ Databases as evidenced by
a system_time_zone variable being set to "Pacific Daylight Time"
a time_zone variable being set to UTC
NOW(), giving me a standard SQL format date time
I thought that that would be sufficient to create an auto updating time stamp field, but, if I create a table via:
CREATE TABLE test (
id SERIAL,
stamp TIMESTAMP,
stuff VARCHAR(255)
);
INSERT INTO test ( stuff ) VALUES ( 'abc' );
SELECT * FROM test;
records seem to be created with NULL in the stamp field:
id stamp stuff
1 NULL abc
I thought that maybe the date gets entered only when doing an update, but when I update:
UPDATE test SET note = 'xyz' WHERE id = 1;
still the stamp is NULL
id stamp stuff
1 NULL xyz
I attempted to change the create as
stamp TIMESTAMP DEFAULT NOW(),
which provides a proper value, but the stamp field remains unchanged when I update (even minutes later).
I also attempted to use
stamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
which, also, gave me an initial value, but never changed when updating.
Also, attempting to append AUTO_INCREMENT didn't seem to work for me. Did I mention that I'm a MySQL newb?
How do I force my TIMESTAMP field to fill at creation and modify when updated?
A field with type TIMESTAMP is also just another field without any special properties like auto initialization or update.
DEFAULT CURRENT_TIMESTAMP only sets the current timestamp when you create the row.
You are looking for the property ON UPDATE CURRENT_TIMESTAMP. This will set the timestamp each time you update the row, given that at least one of the row's values actually changes.
For more infos, have a look at the MySQL docs regarding Automatic Initialization and Update for TIMESTAMP.
Bottom line, create your table like this and stamp will always give you the timestamp of the last change:
CREATE TABLE test (
id SERIAL,
stamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
stuff VARCHAR(255)
);
Sorry can't comment without enough reputation, and I don't know what is IANA TZ Database
But you can try to add On update CURRENT_TIMESTAMP when you create the table:
CREATE TABLE test (
id SERIAL,
stamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,`
stuff VARCHAR(255)
)
it is quite simple
update table set fieldname=now() where fieldname = value;
here we assume that field we try to update is timestamp type field

Setting default value for DATE type column to current date without time part?

NOTE: The question is about DATE type, not Datetime nor Timestamp
How to alter column of date data type to use current date by default?
I saw a lot of examples for datetime (with time part), but not for date. I have tried:
ALTER TABLE `accounting` ALTER `accounting_date`
SET DEFAULT CURRENT_DATE;
ALTER TABLE `accounting` CHANGE `accounting_date`
`accounting_date` DATE NOT NULL DEFAULT CURRENT_DATE;
I also tried with CURDATE(), NOW(), CURRENT_DATE() ...
MySQL 8.0+:
CREATE TABLE foo (
`creation_time` DATE DEFAULT (DATE_FORMAT(NOW(), '%Y-%m-%d'))
)
I use version 8.0.26, this is working:
datecolumn date DEFAULT (CURDATE())
It does not work, if you don't use the brackets!
Probably you cannot set default value for 'date' data type in mysql. You need to change the type to timestamp or datetime.
You may have a look at this similar question.
Invalid default value for 'Date'
EDIT:
In version 5.6.5, it is possible to set a default value on a datetime column, and even make a column that will update when the row is updated. The type definition:
CREATE TABLE foo (
`creation_time` DATETIME DEFAULT CURRENT_TIMESTAMP,
`modification_time` DATETIME ON UPDATE CURRENT_TIMESTAMP
)
Reference: http://optimize-this.blogspot.com/2012/04/datetime-default-now-finally-available.html
As noted in this question Invalid default value for 'create_date' timestamp field, this error may happen when MySQL is in strict mode (which is default behavior, I believe).
If you want to override it, just disable all these checks when creating your table:
SET SQL_MODE='ALLOW_INVALID_DATES';
The warning will be still generated, however it will allow to create the table.
It seems to work in sqlite:
"date" DATE NOT NULL DEFAULT (DATE(CURRENT_TIMESTAMP))
No, you cannot. The documentation is pretty clear on this:
This means, for example, that you cannot set the default for a date column to be the value of a function such as NOW() or CURRENT_DATE. The exception is that you can specify CURRENT_TIMESTAMP as the default for TIMESTAMP and DATETIME columns.

mysql timestamp column

Is it possible to define a timestamp column in a MySQL table that will automatically be updated every time a field in the same row is modified? Ideally this column should initially be set to the time a row was inserted.
Cheers,
Don
You can use the timestamp column as other posters mentioned. Here is the SQL you can use to add the column in:
ALTER TABLE `table1` ADD `lastUpdated` TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ;
This adds a column called 'lastUpdated' with a default value of the current date/time. When that record is updated (lets say 5 minutes later) that timestamp will automatically update to the current time.
That is the default functionality of the timestamp column type. However, note that the format of this type is yyyymmddhhmmss (all digits, no colons or other separation).
EDIT: The above comment about the format is only true for versions of MySQL < 4.1... Later versions format it like a DateTime
This is what I have observed (MySql 5.7.11) -
The first TIMESTAMP column in the table gets current timestamp as the default value. So, if you do an INSERT or UPDATE without supplying a value, the column will get the current timestamp.
Any subsequent TIMESTAMP columns should have a default value explicitly defined. If you have two TIMESTAMP columns and if you don't specify a default value for the second column, you will get this error while trying to create the table -
ERROR 1067 (42000): Invalid default value for 'COLUMN_NAME'
A MySQL timestamp is set with creation or update time only if their default value is set as it. ALTER TABLE some_table ADD when TIMESTAMP DEFAULT CURRENT_TIMESTAMP.
Otherwise it works just like a DateTime field, only that it's relative to 1970/01/01 UTC, so it's an absolute point in time not depending on a specific timezone as is DateTime.