MySQL set default value for DATE column using DATE_ADD? - mysql

I'm trying to add a DATE column to my table with DEFAULT DATE value using an expression:
ALTER TABLE `wp_ezts_project_params` ADD `est_completion` DATE NOT NULL
DEFAULT DATE_ADD( CURRENT_DATE(), INTERVAL 1 MONTH ) AFTER `client_id`
I have tried different variations of several SQL functions, but every time get an syntax error near DATE_ADD.
Are we not allowed to use expressions as default values in phpMyAdmin?

Are we not allowed to use expressions as default values in phpMyAdmin?
Yes, it's not allowed. It's explictly stated in the manual
The DEFAULT value clause in a data type specification indicates a
default value for a column. With one exception, the default value must
be a constant; it cannot be a function or an expression. 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
So if you really want to assign a value for this column you will a) need to pass that in or b) use a trigger
But really you don't need this column at all. It sounds like you are storing a value that's the result of a simple date add - storing it means you are introducing redundancy. Simply calculate it on the fly.

Related

date(now()) giving "'(' is not valid at this position, expecting 'text'" in MySQL 8.0.22 [duplicate]

This question already has answers here:
CURRENT_DATE/CURDATE() not working as default DATE value
(10 answers)
Closed 2 years ago.
I am very new to learning SQL and database creation/management and I'm running into an issue that I can't seem to find an existing answer for. I'm using MySQL to learn right now and I'm running version 8.0.22. I'm trying to use the date function to extract the date portion of the result from now() to use as a default value, but it's giving me the error specified in the title.
I have tried a couple things and they haven't seemed to change anything.
This is what I tried first.
INV_DATE DATE DEFAULT date(now()) NOT NULL,
I then tried it like:
INV_DATE DATE DEFAULT date'2016-01-01' NOT NULL,
Just to see if that worked syntactically and it did.
NOW() on its own works when I change the DATE datatype to DATETIME.
I'm just not really sure what's going on here with this function.
Any help would be appreciated!
Edit: This is the context in which this is being run.
CREATE TABLE INVOICE (
INV_NUMBER INTEGER,
INV_DATE DATE DEFAULT now() NOT NULL,
PRIMARY KEY(INV_NUMBER),
FOREIGN KEY (CUS_CODE) REFERENCES CUSTOMER (CUS_CODE) ON UPDATE CASCADE);
The reason I'm trying to use now() as a default value is because the learning material I'm using jumps between dialects to demonstrate things and is using Oracle SQL for this part. It shows:
INV_DATE DATE DEFAULT SYSDATE NOT NULL,
And I was trying to convert it into the MySQL equivalent.
Rule - now() is not allowed as a default value for the date data type column.
Also, If you want to use now() in your query then you don't need date(now()) only now() is enough.
Check the db<>fiddle to see the error with now() as default value and without it.
Unfortunately, MySQL does not allow default values for date columns. You have two reasonable alternatives.
The first is to use a trigger to assign the date value when you insert new rows.
The second is to use a datetime column along with a generated column:
CREATE TABLE INVOICES (
INV_NUMBER INTEGER PRIMARY KEY,
INV_DATETIME DATETIME DEFAULT NOW(),
INV_DATE DATE GENERATED ALWAYS AS (DATE(INV_DATETIME))
);
You can use a view (or other mechanisms) to hide the INV_DATETIME column. However, you need to update INV_DATETIME because INV_DATE is generated based on that column.

MySQL set a default value YEAR type

The code below doesn't seem to work. I'm trying to set a default value and a time in the future (taking current year + 6 years). any idea?
ALTER TABLE users CHANGE COLUMN dpicture dpicture YEAR NULL DEFAULT 'YEAR(NOW())+6';
MySQL table defaults cannot be dynamic, except in the case of timestamp fields. There's also no such thing as a "year" field type in mysql, so your alter query is wrong on two levels.
You'll probably have to use a after-insert/update trigger to set the +6 years, and use a proper date or int field.

MySQL Update DATETIME to DATE

I have a large table with a DATETIME column and for index reasons I want to add a column which just contains a DATE type. It seems that MySQL is not able to use an index by the following expression GROUP BY DATE(datetime) therefore I want to add another column with a second index.
For updating I use this simple statement:
UPDATE table SET datecol = DATE(datetimecol)
Now a strange behavior occurs: the datecol-column contains the correct values. But the datetimecolumn changes as well: to the current timestamp. This is the default value for this column.
I'm working now for many years with databases and MySQL but I cannot explain this behavior.
The current version is MySQL 5.1.66-0.
Do you have any suggestions or explanations for this?
Your datetimecol is not of type DATETIME, but of type TIMESTAMP which (by default) has the ON UPDATE CURRENT_TIMESTAMP attribute that automatically updates to the current time when a record is modified.
To suppress automatic properties for the first TIMESTAMP column, do either of the following:
Define the column with a DEFAULT clause that specifies a constant default value.
Specify the NULL attribute. This also causes the column to permit NULL values, which means that you cannot assign the current timestamp by setting the column to NULL. Assigning NULL sets the column to NULL.
Therefore:
ALTER TABLE my_table
MODIFY datetimecol TIMESTAMP DEFAULT CURRENT_TIMESTAMP;
To update the records this one time without altering the values in datetimecol, you should explicitly set them to their incumbent values:
UPDATE my_table SET
datetimecol = datetimecol,
datecol = DATE(datetimecol);

MySQL: Trying to insert a value in a timestamp throws an error

I have a table with this column:
last_modified timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
And it looks like I can not insert a row with a custom timestamp, I get this error:
Incorrect datetime value: '1145868501' for column 'last_modified' at row 1
I am trying to populate this table with data coming from another table, that other table only has a creation_time field which is a DATETIME so I use UNIX_TIMESTAMP(creation_time) to populate the timestamp.
I think the timestamp column with "DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP" prevents me from inserting my own stuff, am I right? If yes where is the official doc about that, and what is the best solution? Creating a simple timestamp first then alter the table after inserting data?
Thanks!
EDIT: since people are advising me to not use UNIX_TIMESTAMP, I have to say that I didn't want to use that at the beginning, but I got this kind of error:
Incorrect datetime value: '2010-03-28 02:15:51' for column 'last_modified'
So I thought I had to insert a "real" timestamp...
You can explicitedly insert a value in a TIMESTAMP column. Read: TIMESTAMP Properties
The auto-update TIMESTAMP column, if there is one, is automatically updated to the current timestamp when the value of any other column in the row is changed from its current value. If all other columns are set to their current values, the TIMESTAMP column does not change. Automatic updating does not apply if the TIMESTAMP column is explicitly assigned a value other than NULL.
Update
Hehe, the error occurs because - well- there was no datetime with '2010-03-28 02:15:51'! This was in the daylight saving time gap (which usually appears some day in March, between 02:00 - 03:00 or 03:00 - 04:00.
See: Daylight Saving Time explanation.
You're trying to put a long integer into a datetime field. That doesn't work. Remove the call to UNIX_TIMESTAMP() and it should work.
The MySQL TIMESTAMP type is almost identical to a DATETIME; it just has some extra auto-update magic. As far as SELECT and UPDATE is concerned, it is a DATETIME.
If the column is always auto-updated, you can remove the property, getters and setters from the Entity.
Doing this way, it will be ignored in all queries.

Is there a reason to use CURRENT_TIMESTAMP in inserts/updates?

I was using phpmyadmin to insert some dummy data into a table, and noticed it structured the insert like this:
INSERT INTO `arc`.`transactions` (
`txn_id` ,
`date_time` )
VALUES (
'50005',
CURRENT_TIMESTAMP );
Normally, I'd just not include the field "date_time" and the value is created by mySQL (as the field is of type timestamp), and auto-updates whenever you insert or update a record.
Is there any reason to structure the query as you see it above, explicitly inserting CURRENT_TIMESTAMP? Or is this a phpmyadmin oddity?
It could also be a matter of compatibility. CURRENT_TIMESTAMP is defined by the SQL standard. Automatically updated timestamp columns are not. An app that wants to be portable and record timestamps is better off explicitly specifying the currrent timestamp. And what better way to do that than to use the standard, built-in CURRENT_TIMESTAMP function?
You can have TIMESTAMP fields that don't auto-update (see the TIMESTAMP properties page for how to specify these), so depending on how you define the column, it might not be the case that an UPDATE query automatically adjusts the TIMESTAMP field.
PHPMyAdmin is probably taking the safe approach here and specifying the value to ensure it's updated, no matter the column definition. PHPMyAdmin can probably detect the default value if it wants to, so another possible explanation would be compatibility between various server versions and modes for any SQL that it generates.
It depends solely on date_time column definition. if it is like
`date_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
Then you surely don't need to specify anything when inserting or updating a row, but if it is:
`date_time` TIMESTAMP NOT NULL
Then you have to specify something every time you create or update a row