error for sysdatetime() - mysql

+-------------------------+
| Tables_in_movierentaldb |
+-------------------------+
| MEMBERSHIP |
| PRICE |
| RENTAL |
| movie |
| video |
+-------------------------+
mysql> describe rental
-> ;
+-----------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------+------+-----+---------+-------+
| RENT_NUM | int(11) | NO | PRI | NULL | |
| MEM_NUM | int(11) | YES | MUL | NULL | |
+-----------+---------+------+-----+---------+-------+
Hello stackoverflow community,
I have an issue when creating a table in mysql, I am trying to enter :
alter table RENTAL add RENT_DATE datetime default SYSDATETIME();
and I am getting a syntax error.
the reason I did not enter when creating the table because I had the same syntax issue when trying to enter it in the create table command:
CREATE TABLE RENTAL (
RENT_NUM int PRIMARY KEY,
RENT_DATE DATE DEFAULT SYSDATETIME(),
MEM_NUM int CONSTRAINT RENTAL_MEM_NUM_FK REFERENCES MEMBERSHIP);
I had the same issue with the constraint MEM_NUM but when I entered the following command it was able to create the constraint:
alter table RENTAL add foreign key (MEM_NUM) references
MEMBERSHIP(MEM_NUM);
Thanks for your time!

You have to use:
alter table RENTAL add RENT_DATE datetime default CURRENT_TIMESTAMP;
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. See Section 12.3.5, “Automatic Initialization and Updating for TIMESTAMP and DATETIME”.
DOCs here

Related

Alter MySQL's SHOW COLUMS "Extra" value

Is there a way to change te value of the Extra column that is shown with the SHOW COLUMNS/DESCRIBE sentences?
The documentation about this column states the following:
Extra
Any additional information that is available about a given column. The
value is nonempty in these cases:
auto_increment for columns that have the AUTO_INCREMENT attribute.
on update CURRENT_TIMESTAMP for TIMESTAMP or DATETIME columns that
have the ON UPDATE CURRENT_TIMESTAMP attribute.
VIRTUAL GENERATED or VIRTUAL STORED for generated columns.
DEFAULT_GENERATED for columns that have an expression default value.
I have the next table columns information but I wish to remove the Extra value of the start_date column.
Is there a way to do this?
+--------------------+--------------------+------+-----+-------------------+-------------------+
| Field | Type | Null | Key | Default | Extra |
+--------------------+--------------------+------+-----+-------------------+-------------------+
| id_machine_product | "int(10) unsigned" | NO | PRI | NULL | auto_increment |
| ... | ... | ... | ... | ... | ... |
| start_date | timestamp | NO | | CURRENT_TIMESTAMP | DEFAULT_GENERATED |
+--------------------+--------------------+------+-----+-------------------+-------------------+
EDIT:
I have implemented a fingerprint validation method in PHP that diffs the DESCRIBE tables values, I have database versions in production that doesn't have that Extra value even though those columns have an expression default value, so currently, I wish to alter that value so I don't get errors from my implemented fingerprint validation method in my development environment.
The production databases are in Mysql < 8.0 so, as per Bill Karwin's answer, I'm having trouble with my MySQL development environment version that is 8.0
It's not clear from your question why you want to eliminate the Extra information. It's just noting that the column's default is an expression.
To make the Extra field blank, you must make the column's default either a constant value or NULL.
mysql> create table foo ( id int unsigned primary key, start_date timestamp not null default current_timestamp);
mysql> show columns from foo;
+------------+------------------+------+-----+-------------------+-------------------+
| Field | Type | Null | Key | Default | Extra |
+------------+------------------+------+-----+-------------------+-------------------+
| id | int(10) unsigned | NO | PRI | NULL | |
| start_date | timestamp | NO | | CURRENT_TIMESTAMP | DEFAULT_GENERATED |
+------------+------------------+------+-----+-------------------+-------------------+
mysql> alter table foo modify start_date timestamp default null;
mysql> show columns from foo;
+------------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+------------------+------+-----+---------+-------+
| id | int(10) unsigned | NO | PRI | NULL | |
| start_date | timestamp | YES | | NULL | |
+------------+------------------+------+-----+---------+-------+
Note that the Extra information "DEFAULT_GENERATED" is only present in MySQL 8.0. I suspect it's related to the new feature to support expressions in the DEFAULT clause. Any other expression also results in this Extra information.
mysql > alter table foo modify start_date timestamp default (now() + interval 1 hour);
mysql> show columns from foo;
+------------+------------------+------+-----+---------------------------+-------------------+
| Field | Type | Null | Key | Default | Extra |
+------------+------------------+------+-----+---------------------------+-------------------+
| id | int(10) unsigned | NO | PRI | NULL | |
| start_date | timestamp | YES | | (now() + interval 1 hour) | DEFAULT_GENERATED |
+------------+------------------+------+-----+---------------------------+-------------------+
Topicstarters comment
I have implemented a fingerprint validation method in PHP that diffs
the DESCRIBE tables values, I have database versions in production
that doesn't have that Extra value even though those columns have an
expression default value, so currently, I wish to alter that value so
I don't get errors from my implemented fingerprint validation method
in my development environment.
The more standard SQL method would be which also works in MySQL 8
Query
SELECT
information_schema.COLUMNS.COLUMN_NAME AS 'Field'
, information_schema.COLUMNS.COLUMN_TYPE AS 'Type'
, information_schema.COLUMNS.IS_NULLABLE AS 'Null'
, information_schema.COLUMNS.COLUMN_KEY AS 'Key'
, information_schema.COLUMNS.COLUMN_DEFAULT AS 'Default'
, information_schema.COLUMNS.EXTRA AS 'Extra'
FROM
information_schema.TABLES
INNER JOIN
information_schema.COLUMNS ON information_schema.TABLES.TABLE_NAME = information_schema.COLUMNS.TABLE_NAME
WHERE
information_schema.TABLES.TABLE_NAME = '<table>'
This query should match the output of DESCRIBE
Then you could use REPLACE() on information_schema.COLUMNS.EXTRA output to remove or edit the way you want. For example removing extra features like DEFAULT_GENERATED or VIRTUAL GENERATED (generated columns)
you need an alter table statement. Something like
ALTER TABLE `document` MODIFY COLUMN `start_date ` INT AUTO_INCREMENT;
You can set a default value like
DEFAULT 1 NOT NULL

mySQL: What is preventing my foreign key constraint?

I have tried everything I can think of but I am still having problems creating a table.
I have a user table with a primary key username
+---------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------------+-------------+------+-----+---------+-------+
| created_at | datetime | YES | | NULL | |
| updated_at | datetime | YES | | NULL | |
| username | varchar(50) | NO | PRI | NULL | |
| administrator | tinyint(1) | YES | | NULL | |
| fullname | text | YES | | NULL | |
| description | text | YES | | NULL | |
| password | varchar(60) | NO | | NULL | |
+---------------+-------------+------+-----+---------+-------+
and I want to create a new table like this:
CREATE TABLE sessions (
created_at DATETIME,
updated_at DATETIME,
token VARCHAR(50) NOT NULL,
username VARCHAR(50),
PRIMARY KEY (token),
FOREIGN KEY(username) REFERENCES users (username)
);
but I get a nasty error:
ERROR 1215 (HY000): Cannot add foreign key constraint
I usually find this error is caused by a mismatch in the data type of the pk/fk pair but this time both are clearly varchar(50) so it looks like the problem is elsewhere.
I have also tried this just in case:
CREATE TABLE sessions (
created_at DATETIME,
updated_at DATETIME,
token VARCHAR(50) NOT NULL,
username varchar(50) NOT NULL, #<- ***added not null***
PRIMARY KEY (token),
FOREIGN KEY(username) REFERENCES users (username)
);
mysql>SHOW ENGINE INNODB STATUS
LATEST FOREIGN KEY ERROR
2016-08-03 15:13:23 a46fcb70 Error in foreign key constraint of table savesdev/sessions:
FOREIGN KEY(username) REFERENCES users (username)):
Cannot find an index in the referenced table where the
referenced columns appear as the first columns, or column types
in the table and the referenced table do not match for constraint.
Note that the internal storage type of ENUM and SET changed in
tables created with >= InnoDB-4.1.12, and such columns in old tables
cannot be referenced by such columns in new tables.
See http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html
for correct foreign key definition.
It seems the error is raised under two circumstances:
1) When there is a mismatch (which I have ruled out)
column types in the table and the referenced table do not match for constraint.
2) When there is no suitable index on the referenced column
Cannot find an index in the referenced table where the referenced columns appear as the first columns
I think both of these are covered so what's the deal?
Can anyone spot my error?
Maybe your columns username have different charset can you try this :
ALTER TABLE sessions MODIFY username VARCHAR(50) CHARACTER SET utf8;
ALTER TABLE users MODIFY username VARCHAR(50) CHARACTER SET utf8;
As suggested by #Graeme Stuart here is a link to see how we can check the charterer set of a database / table or a column : How do I see what character set a MySQL database / table / column is?

Error 1062: duplicate entry in non-primary field

I have recently started to work with MySQL for my study job and now face following problem:
My predecessor created a textmining table of the following structure:
+------------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| TokenId | int(11) | NO | PRI | 0 | |
| Value | varchar(255) | YES | | NULL | |
| Frequency | int(11) | YES | | NULL | |
| PMID | int(11) | YES | MUL | NULL | |
+------------+--------------+------+-----+---------+-------+
In the context of restructuring, I added the following column:
+------------+--------------+------+-----+---------+-------+
| NewTokenId | int(11) | YES | | NULL | |
+------------+--------------+------+-----+---------+-------+
If I now run the query:
insert into TitleToken(NewTokenId) select t.TokenId from Token as t, TitleToken as tt where t.Value = tt.Value
or even the query:
insert into TitleToken(NewTokenId) values(1);
I get following output:
ERROR 1062 (23000): Duplicate entry '0' for key 'PRIMARY'
As I said, I am relatively new to (hands-on) *SQL and it feels like a stupid mistake, but since the column NewTokenId is no primary key, not unique and even Null is YES, I thought I'd be able to insert basically anything I want.
Any hint would be appreciated... thanks in advance :)
The problem here is that you have a default value for the primary key "TokenID", if you do not insert a value for the key in your insert statement the system will automatically insert 0. However, if there is another tuple with the same value for this attribute (which is probable because the default is 0) you will get that error.
You are attempting to perform an insert into a table without providing a unique value for TokenId. By default, according to the table description, TokenId defaults to 0, you cannot have multiple identical values in that column.

CURRENT_DATE/CURDATE() not working as default DATE value

Pretty straight forward question here, I think this should work but it doesn't. Why doesn't it?
CREATE TABLE INVOICE(
INVOICEDATE DATE NOT NULL DEFAULT CURRENT_DATE
)
It doesn't work because it's not supported
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
According to this documentation, starting in MySQL 8.0.13, you will be able to specify:
CREATE TABLE INVOICE(
INVOICEDATE DATE DEFAULT (CURRENT_DATE)
)
MySQL 8.0.13 was released to General Availability in October 2018. The release info is located here.
declare your date column as NOT NULL, but without a default. Then add this trigger:
USE `ddb`;
DELIMITER $$
CREATE TRIGGER `default_date` BEFORE INSERT ON `dtable` FOR EACH ROW
if ( isnull(new.query_date) ) then
set new.query_date=curdate();
end if;
$$
delimiter ;
Currently from MySQL 8 you can set the following to a DATE column:
In MySQL Workbench, in the Default field next to the column, write: (curdate())
If you put just curdate() it will fail. You need the extra ( and ) at the beginning and end.
create table the_easy_way(
capture_ts DATETIME DEFAULT CURRENT_TIMESTAMP,
capture_dt DATE AS (DATE(capture_ts))
)
(MySQL 5.7)
I have the current latest version of MySQL: 8.0.20
So my table name is visit, my column name is curdate.
alter table visit modify curdate date not null default (current_date);
This writes the default date value with no timestamp.
----- 2016-07-04 MariaDB 10.2.1 -- Release Note -- -----
Support for DEFAULT with expressions (MDEV-10134).
----- 2018-10-22 8.0.13 General Availability -- -- -----
MySQL now supports use of expressions as default values in data type specifications. This includes the use of expressions as default values for the BLOB, TEXT, GEOMETRY, and JSON data types, which previously could not be assigned default values at all. For details, see Data Type Default Values.
As the other answer correctly notes, you cannot use dynamic functions as a default value. You could use TIMESTAMP with the CURRENT_TIMESTAMP attribute, but this is not always possible, for example if you want to keep both a creation and updated timestamp, and you'd need the only allowed TIMESTAMP column for the second.
In this case, use a trigger instead.
I came to this page with the same question in mind, but it worked for me!, Just thought to update here , may be helpful for someone later!!
MariaDB [niffdb]> desc invoice;
+---------+--------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+--------+------+-----+---------+----------------+
| inv_id | int(4) | NO | PRI | NULL | auto_increment |
| cust_id | int(4) | NO | MUL | NULL | |
| inv_dt | date | NO | | NULL | |
| smen_id | int(4) | NO | MUL | NULL | |
+---------+--------+------+-----+---------+----------------+
4 rows in set (0.003 sec)
MariaDB [niffdb]> ALTER TABLE invoice MODIFY inv_dt DATE NOT NULL DEFAULT (CURRENT_DATE);
Query OK, 0 rows affected (0.003 sec)
Records: 0 Duplicates: 0 Warnings: 0
MariaDB [niffdb]> desc invoice;
+---------+--------+------+-----+-----------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+--------+------+-----+-----------+----------------+
| inv_id | int(4) | NO | PRI | NULL | auto_increment |
| cust_id | int(4) | NO | MUL | NULL | |
| inv_dt | date | NO | | curdate() | |
| smen_id | int(4) | NO | MUL | NULL | |
+---------+--------+------+-----+-----------+----------------+
4 rows in set (0.002 sec)
MariaDB [niffdb]> SELECT VERSION();
+---------------------------+
| VERSION() |
+---------------------------+
| 10.3.18-MariaDB-0+deb10u1 |
+---------------------------+
1 row in set (0.010 sec)
MariaDB [niffdb]>
While creating a table, you have to use CURRENT_DATE() function as default value. Please see below example I just tested.
CREATE TABLE SALES_DATA (
SALES_ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
SALES_GIRL_ID INT UNSIGNED NOT NULL,
SALES_DATE DATE NOT NULL DEFAULT (CURRENT_DATE()),
TOTAL_SALES FLOAT(6, 2),
PRIMARY KEY (SALES_ID),
FOREIGN KEY (SALES_GIRL_ID) REFERENCES SALES_GIRLS(ID)
);

ALTER TABLE not letting me set NULL or default value?

I am trying to change an existing column in a table I have to allow for null values and then set the default value to null. I tried running the following but it does not seem to be updating the table:
mysql> ALTER TABLE answers_form MODIFY sub_id int unsigned NULL DEFAULT NULL;
Query OK, 0 rows affected (0.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> desc answers_form;
+--------------+------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------------+------------------+------+-----+---------+-------+
| answer_id | int(10) unsigned | NO | PRI | 0 | |
| sub_id | int(10) unsigned | NO | PRI | 0 | |
| form_id | int(10) unsigned | NO | PRI | NULL | |
| value | varchar(255) | NO | | NULL | |
| non_response | bit(1) | YES | | b'0' | |
+--------------+------------------+------+-----+---------+-------+
5 rows in set (0.01 sec)
Can anyone see what I am doing wrong here?
its a primary key , mysql doesn't allow any part of the primary key to be null, which does make the fact that it allows a default value of null for the form_id odd, however the docs at
http://dev.mysql.com/doc/refman/5.5/en/optimizing-primary-keys.html
say "Query performance benefits from the NOT NULL optimization, because it cannot include any NULL values".
Just out of curiosity, does it actually allow you to put in null values in the form_id field?
You have 2 non-nullable columns with the default value of null. This shouldn't be allowed by your database engine. If it is, it is rather far from a best practice.
sub_id is listed as a primary key
From the MySQL docs (5.7, but other versions say the same thing):
A PRIMARY KEY is a unique index where all key columns must be defined
as NOT NULL. If they are not explicitly declared as NOT NULL, MySQL
declares them so implicitly (and silently).
As to the discussion about the Non-null columns having a Default of NULL...
The NULL value in the Default column means that there is no default, not that the default is NULL.
Fiddle: http://sqlfiddle.com/#!2/c718d/1
If I create a simple table like so:
CREATE TABLE name_num(
Number INT PRIMARY KEY,
Name TEXT NOT NULL
);
And then do desc name_num, I get:
| FIELD | TYPE | NULL | KEY | DEFAULT | EXTRA |
---------------------------------------------------
| Number | int(11) | NO | PRI | (null) | |
| Name | text | NO | | (null) | |
Again, from the MySQL docs:
If the column cannot take NULL as the value, MySQL defines the column with no explicit DEFAULT clause. Exception: If the column is defined as part of a PRIMARY KEY but not explicitly as NOT NULL, MySQL creates it as a NOT NULL column (because PRIMARY KEY columns must be NOT NULL), but also assigns it a DEFAULT clause using the implicit default value. To prevent this, include an explicit NOT NULL in the definition of any PRIMARY KEY column.