MySQL default value using another column - mysql

I have a table
-------------
| id | date |
-------------
Now i need to add column "week", so is it possible to add column like
alter table `a` add column `week` INT(6) not null default DATE_FORMAT(`date`, '%Y%v')
?

The comment above about using a trigger, is the way to go on this but doesn't elaborate on why you can't do it. So, from the documentation ...
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.

Related

INSERT INTO using subquery is telling me an uninvolved field is the error?

I'm not entirely sure how to explain what's happening but basically I'm trying to insert values into my table using a subquery and it's telling me that I'm getting an error because a field that is not involved in the query at all does not have a default value.
INSERT INTO customerPayment (customerOrderId)
SELECT ID FROM customerOrder
WHERE customerOrder.orderStateId = (
SELECT ID
FROM orderState
WHERE orderState.state = "Payment Recieved"
);
ERROR 1364 (HY000): Field 'total' doesn't have a default value
And then when I go into the table itself to try and set a default value for total, it then tells me I have an invalid default value for another unrelated field.
ALTER TABLE customerPayment ALTER total SET DEFAULT 0.0;
ERROR 1067 (42000): Invalid default value for 'paymentDate'
It may be relevant to note that 'paymentDate' currently has a default value of curdate().
From what I can see, the total column was created with NOT NULL condition but wasn't assigned with any default value. Something like this example:
total DECIMAL(4,4) NOT NULL,
And it seems CURDATE() or CURRENT_DATE() can't be assigned as default value from my testing. Instead, the column datatype should be TIMESTAMP or DATETIME then can only assign with default value of CURRENT_TIMESTAMP() or NOW(). So, maybe the first step is to change the paymentDate datatype and default value like:
ALTER TABLE customerPayment MODIFY COLUMN `paymentDate` TIMESTAMP NOT NULL DEFAULT NOW();
Then you can proceed with modifying the total column like:
ALTER TABLE customerPayment MODIFY COLUMN total DECIMAL(4,4) NOT NULL DEFAULT 0.0;
Then probably you can do your INSERT after that.
Here's a fiddle: https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=4af3d11f90916469d8fbe61011b3fcab

What is the Meaning of "DEFAULT" in Mysql Datetime?

In this following mysql command i am seeing the Keyword DEFAULT
CREATE Table User
(
id int(11) NOT NULL AUTO_INCREMENT,
created_at datetime DEFAULT NULL
)
My Question Is :
Why is there a default keyword if i am allowing datetime to be null
Is it about the Datetime syntax, so that it should be in default format.
please explain it to me. I also found the documentation page for DEFAULT in mysql. but i am not understanding it.
[N.B.: Pardon Me, If this a beginner question, or already asked. But I did not find exactly what i was looking for.]
1. Why is there a default keyword if i am allowing datetime to be null
If a column definition includes no explicit DEFAULT value, MySQL determines the default value as described in Section 12.7, “Data Type Default Values”.
MySQL will add default value to column definition by it's own rules if you don't set it manually. So, DEFAULT is always presented, except special datatypes
DEFAULT does not apply to the BLOB, TEXT, GEOMETRY, and JSON types
2. Is it about the Datetime syntax, so that it should be in default format.
No. If you allow null, then column can take any valid datetime value OR null. Null is valid too. And from manual:
If the column can take NULL as a value, the column is defined with an explicit DEFAULT NULL clause.
As result, if you create table with column created_at datetime it will be converted according these rules to created_at datetime DEFAULT NULL.
Update
Some examples. Next CREATE TABLE statements are equivalent:
CREATE Table User
(
created_at datetime NULL
);
CREATE Table User
(
created_at datetime DEFAULT NULL
);
You said, that you "allow null" for this column. Probably, you was using first query with created_at datetime NULL syntax. But MySQL really translates it into second query, because of rules above.
Why is there a default keyword if i am allowing datetime to be null
You mistake the NULL after DEFAULT with the NULL that allows a column to contain NULL values. Read below about the difference.
Is it about the Datetime syntax, so that it should be in default format.
The DEFAULT keyword in a CREATE TABLE statement doesn't tell anything about any format. It specifies the default value to be used for the column when an INSERT statement doesn't provide a value for it.
The complete definition of a table column in the CREATE TABLE statement contain the following pieces, in this order:
field name;
field type;
NULL or NOT NULL - are NULL values allowed to be stored in the field? If neither is specified, NULL is assumed;
DEFAULT default value - the value to be used for the field when an INSERT statement doesn't provide a value for it; NULL can be used as default value if the column is nullable; if it's not specified, MySQL uses some rules to compute the default value based on the field type;
AUTO_INCREMENT - when a value is not provided for the column, MySQL uses the biggest value existing in the column plus one; can be used only with integer and float columns;
one of UNIQUE, UNIQUE KEY, KEY, PRIMARY KEY - the first two are equivalent and they specify that the column is an unique index of the table (it cannot contain the same value for two or more rows); the last two specify the column is the identifier of the row (it is an UNIQUE INDEX and it cannot contain NULL values); these attributes can be specified here for compatibility with other database systems; on MySQL one usually specifies the table indexes after the columns using a different syntax;
COMMENT string - a comment for the column; it is not used by MySQL but it can be useful for the developers (to specify what represents the column);
other, less used, options.
Only the first two pieces from the list above (the name and the type) are required; all the others are optional. If present, they must be provided in the order of the list.
Your statement:
CREATE TABLE User
(
id INT(11) NOT NULL AUTO_INCREMENT,
created_at DATETIME DEFAULT NULL
)
The column id specifies NOT NULL, skips DEFAULT and specifies AUTO_INCREMENT. Without AUTO_INCREMENT, MySQL uses 0 as the default value (this is the default value for integer types). Because of AUTO_INCREMENT, when a value is not provided in the INSERT statement, MySQL finds the largest value already stored in the column, increases it with 1 and uses this computed value for the column.
The column created_at doesn't specify if it allows NULL values (it allows them, this is the default) and specifies that the default value for the column is NULL.
Examples
Let's see how it works:
INSERT INTO User(id, created_at) VALUES (5, '2016-06-01 11:22:33')
inserts a new row having the values provided in the INSERT statement; no surprise here.
INSERT INTO User(created_at) VALUES ('2016-06-02 12:34:56')
inserts a new row with id = 6, created_at = '2016-06-02 12:34:56'. Because a value was not provided for column id, the AUTO_INCREMENT option generated 6 for it (the successor of the larger value already in the column).
The same happens when NULL is provided for the AUTO_INCREMENT column:
INSERT INTO User(id, created_at) VALUES (NULL, '2016-06-03')
inserts id = 7, created_at = '2016-06-03 00:00:00'. Please also note that, because the time components were not specified in the value provided for created_at, MySQL defaulted them to 00:00:00.
A new statement:
INSERT INTO User(id) VALUES (10)
creates a row having id = 10, created_at = NULL.
The statement
INSERT INTO User() VALUES()
looks strange but it's perfectly legal and inserts a row that uses the default values for all its columns. In this case, the new row have the values id = 11, created_at = NULL.
Finally, the statement
INSERT INTO User(id) VALUES(5)
fails because there already exists a row having id = 5 in the table (it was inserted by the first statement at the start of the examples.
The DEFAULT constraint is used to insert a default value into a column.
The default value will be added to all new records, if no other value is specified.
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.
For More Information See This Question.
MySQL columns with default null - stylistic choice, or is it?
Think of NULL as unknown. This has interesting implications, like:
mysql> select null = true;
+-------------+
| null = true |
+-------------+
| NULL |
+-------------+
and
mysql> select null != true;
+--------------+
| null != true |
+--------------+
| NULL |
+--------------+
From MySQL Data Type Default Values
If the column can take NULL as a value, the column is defined with an explicit DEFAULT NULL clause.
For MySQL those definitions are all same and identical
column type
column type NULL
column type DEFAULT NULL
column type NULL DEFAULT NULL

MySQL sets field to current date when value is null

I have a table with two timestamp fields. They are not nullable. The problem is that whenever I insert null into those fields, the current date is automatically saved, instead of throwing an error saying "Column 'first_data_dt' cannot be null", just like it happens when I insert a value into another non-nullable field.
There are no triggers associated to this table.
Does anybody know why this is happening?
EDIT to add table definition:
CREATE TABLE `ui_mytable` (
`id` int(11) NOT NULL,
`first_data_dt` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`last_data_dt` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I understand now why first_data_dt is updated to the current timestamp anytime I insert null. But what about last_data_dt?
That's what a TIMESTAMP column does:
The TIMESTAMP data type offers automatic initialization and updating to the current date and time (that is, the current timestamp). [...] You can initialize or update any TIMESTAMP column to the current date and time by assigning it a NULL value, unless it has been defined with the NULL attribute to permit NULL values.
Source: MySQL documentation
Maybe you want to use a DATETIME instead?

MYSQL alter table current_time default error

I tried to alter the table with inserting a new attribute date1 where it will auto set the date for each entry into the table.
When i insert the query
ALTER TABLE `vessellist` ADD `date1` DATE NOT NULL DEFAULT CURRENT_TIMESTAMP FIRST;
It says INVALID DEFAULT VALUE FOR date1
The DEFAULT clause specifies 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 a TIMESTAMP column
http://dev.mysql.com/doc/refman/5.5/en/create-table.html

Create a column 'Date' with default value current datetime MYSQL

Following is my SQL query, it throws an error:-
CREATE TABLE IF NOT EXISTS USER_PROFILE(Id INT PRIMARY KEY AUTO_INCREMENT, date DATETIME NOT NULL DEFAULT NOW) ;
It says Invalid default value for 'date'.
I've tried synonyms for NOW() as well, namely CURRENT_TIMESTAMP, but still the same error.
How can I create a column date with default value current time?
On the documentation page, it says to assign this way
CREATE TABLE t1 (
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
dt DATETIME DEFAULT CURRENT_TIMESTAMP
);
From the document
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 no function is allowed in the default value hence the first query is failing.
Again from the document
As of MySQL 5.6.5, TIMESTAMP and DATETIME columns can be automatically
initializated and updated to the current date and time (that is, the
current timestamp). Before 5.6.5, this is true only for TIMESTAMP, and
for at most one TIMESTAMP column per table. The following notes first
describe automatic initialization and updating for MySQL 5.6.5 and up,
then the differences for versions preceding 5.6.5.
Before 5.6.5, this is true only for TIMESTAMP
So your mysql version is less than 5.6.5 hence the 2nd query is failing too.
So you need to create the table as
CREATE TABLE IF NOT EXISTS
USER_PROFILE
(
Id INT PRIMARY KEY AUTO_INCREMENT,
date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ;
It might be that DATE, as a reserved word, is confusing it by the time it gets to the DEFAULT clause. Try a different name and if that works, try quoting "date".