I try to create a table with an INTEGER attribute which should be limited to positive numbers. I know there is an UNSIGNED option, but that does the wrong thing. As it allows adding -10 as a value. It will just make a 10 out of it.
Is it possible to deny a wrong entry? I tried using CHECK
DROP TABLE Produkt;
CREATE TABLE Produkt (
Bezeichnung VARCHAR(237) PRIMARY KEY,
ProduktNr INTEGER NOT NULL,
Produktart VARCHAR(3) DEFAULT "XXX",
CONSTRAINT onlyPositive CHECK(ProduktNr >= 0)
);
But I can still add -10 as a value... What am I doing wrong?
1) In a strict sql_mode if you define your column as
ProduktNr INT UNSIGNED NOT NULL,
and then try to insert a negative value you'll get an error
ERROR 1264 (22003): Out of range value for column 'ProduktNr' at row 1
Here is SQLFiddle demo. Uncomment insert statement and click Build Schema
2) MySQL still lacks support for CHECK constraints. The CHECK clause is parsed but ignored by all storage engines.
3) On a side note: don't use a VARCHAR(237) column as a PRIMARY KEY, especially if you're using InnoDB engine (all secondary indices on the table also include PK values).
I believe you can just add the check without naming the constraint. This seemed to work for me:
CREATE TABLE Produkt (
Bezeichnung VARCHAR(237),
ProduktNr INTEGER NOT NULL,
Produktart VARCHAR(3) DEFAULT "XXX",
PRIMARY KEY (Bezeichnung),
CHECK(ProduktNr >= 0)
);
I also moved the declaration of the primary key. I'm not 100% certain that you can declare a key the same time as a field, but I did put what I knew.
Related
It seems like a bug because when I set the integer value on a column it says it has been changed successfully but nothing happens and the integer value remains blank.
I can't use the database because I get the error that all my integer columns have incorrect integer values, but when I try to change them to int(11) e.g. nothing is happening.
Does anyone know how to fix this?
I can set columns with varchar datatypes to have values and they work fine.
Fatal error: Uncaught mysqli_sql_exception: Incorrect integer value: '' for column 'topic_id' at row 1 in C:\wamp64\www\mycode\upload2.php on line 32
mysqli_sql_exception: Incorrect integer value: '' for column 'topic_id' at row 1 in C:\wamp64\www\mycode\upload2.php on line 32
Code:
ALTER TABLE `topics` CHANGE `topic_id` `topic_id` INT(11) NOT NULL
AUTO_INCREMENT;
// This isn't changing the int value at all!
You have multiple errors in what you are attempting to do.
First, there is the problem that the values in the table are not integers.
Second, you cannot set a column to auto-increment unless it is the primary key.
One option is to drop the primary key and auto-increment idea. Then you can update the values to NULL and change the column to an int:
update topics
set topic_id = null
where topic_id regexp '[^0-9]';
ALTER TABLE `topics` CHANGE `topic_id` `topic_id` INT(11) ;
Here is a db<>fiddle.
If you really want topic_id to be an auto-increment primary key, then I would suggest recreating the table. Something like this:
create table temp_topics as
select *
from topics;
drop table topics; -- be very careful here!
create table topics (
topic_id int auto_increment primary key,
. . . -- the rest of the columns
);
insert into topics (<list of columns here>)
select <list of columns here>
from temp_topics;
if you wanna change a value you have to update that row.
what you are trying to do is wrong , int data type has fixed length (4 bytes), so when you give it a length , it actually doesn't mean anything and its been ignored by the sql engine
see MySql Ref: https://dev.mysql.com/doc/refman/8.0/en/integer-types.html
numeric data types are divided into 3 categoies :
Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT
Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC
Floating-Point Types (Approximate Value) - FLOAT, DOUBLE
How can we add a constraint which enforces a column to have only positive values.
Tried the following mysql statement but it doesn't work
create table test ( test_column integer CONSTRAINT blah > 0);
You would use the keyword unsigned to signify that the integer doesn't allow a "sign" (i.e. - it can only be positive):
CREATE TABLE test (
test_column int(11) unsigned
);
You can read more about the numeric data types (signed & unsigned) here.
As far as an actual constraint to prevent the insertion-of negative values, MySQL has a CHECK clause that can be used in the CREATE TABLE statement, however, according to the documentation:
The CHECK clause is parsed but ignored by all storage engines.
For reference, here is how you would use it (and though it will execute absolutely fine, it just does nothing - as the manual states):
CREATE TABLE test (
test_column int(11) unsigned CHECK (test_column > 0)
);
UPDATE (rejecting negative values completely)
I've noticed from a few of your comments that you want queries with negative values to be completely rejected and not set to 0 (as a normal transaction into an unsigned column would do). There is no constraint that can do this in-general (that I know of, at least), however, if you turn strict-mode on (with STRICT_TRANS_TABLES) any query that inserts a negative value into an unsigned column will fail with an error (along with any-other data-insertion errors, such as an invalid enum value).
You can test it by running the following command prior to your insert-commands:
SET ##SESSION.sql_mode = 'STRICT_TRANS_TABLES';
And if it works for you, you can either update your MySQL config with sql-mode="STRICT_TRANS_TABLES" or use SET ##GLOBAL.sql_mode = 'STRICT_TRANS_TABLES'; (I'm not sure if the SET command will affect the global mysql config though, so it may be better to update the actual config-file).
As of MySQL 8.0.16 (MariaDB 10.2.1), CHECK constraints are enforced. (In earlier versions constraint expressions were accepted in the syntax but ignored).
Therefore you can use:
CREATE TABLE test (
test_column INT CHECK (test_column > 0)
);
or
CREATE TABLE test (
test_column INT,
CONSTRAINT test_column_positive CHECK (test_column > 0)
);
The way to fix this is to explicitly tell MySQL Server to create an Unsigned integer.
CREATE TABLE tbl_example (
example_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
example_num INT UNSIGNED NOT NULL,
example_text TEXT
PRIMARY KEY (`example_id`)
);
just use unsigned to allow only positive values.
CREATE TABLE hello
(
world int unsigned
);
SQLFiddle demo
uncomment the line and you will see the error saying: Data truncation: Out of range value for column 'world' at row 1:
You should use UNSIGNED INTEGER data type. For more information, click here
I've got a mysql database with a table (InnoDB) of Games:
gamerooms
id: bigint(20) unsigned not null auto_increment
PRIMARY KEY (`id`)
I'd like to start generating a UUID value for each row which I can share publicly, something like:
gamerooms
id | id_public |
--------------------
1 | abcde
2 | ghijk
3 | lmnop
...
select * from gamerooms where id_public = ...
How do I add this new column, also keeping in mind that there are already records in the table? I'm confused because the column should be marked NOT NULL, but after adding the column, all records that already exist would have empty values.. Do I have to provide a default value?:
ALTER TABLE `gamerooms` ADD COLUMN `id_public` varchar(36) DEFAULT something AFTER `id`
I want to put an index on id_public of course after it's created, so not sure if null values after the column is first created will mess anything up.
Also, I can use varchar(36) with mysqls UUID() output, right?
Thank you
Your ALTER statement is correct:
ALTER TABLE `gamerooms`
ADD COLUMN `id_public` varchar(36) NOT NULL DEFAULT 'something' AFTER `id`
According to my MySQL Pocket Reference, if you don't provide a default value for a column that is defined as NOT NULL:
MySQL picks a value based on the type of the field
In this case, I'm guessing the default would be empty string. Once your column has been added, simply create a new index for the column, and rebuild the index using a null alteration instruction like so:
CREATE INDEX myIndex ON gamerooms(id_public);
ALTER TABLE gamerooms ENGINE = InnoDB;
You may be able to create the index at the same time you do the insert. My MySQL-fu isn't strong enough to know how to do that.
Should the existing records have a value once you create this new column? If yes, you could do this in multiple steps. First, create the new column without constraint or index and then back populate it with the UUID for all existing records. Once everything is populated, add the not null constraint and your indexes.
As a UUID is a 128-bit number, you don't need a varchar column to store it. a char(16) column would just be ok for saving a UUID binary data.
ALTER TABLE `gamerooms` ADD COLUMN `id_public` char(16) NOT NULL DEFAULT '' AFTER `id`
I have a table "Bestelling" with 4 columns: "Id" (PK), "KlantId", "Datum", "BestellingsTypeId", now I want to make the column Id auto_increment, however, when I try to do that, I get this error:
ERROR 1062: ALTER TABLE causes auto_increment resequencing, resulting in duplicate entry '1' for key 'PRIMARY'
SQL Statement:
ALTER TABLE `aafest`.`aafest_bestelling` CHANGE COLUMN `Id` `Id` INT(11) NOT NULL AUTO_INCREMENT
ERROR: Error when running failback script. Details follow.
ERROR 1046: No database selected
SQL Statement:
CREATE TABLE `aafest_bestelling` (
`Id` int(11) NOT NULL,
`KlantId` int(11) DEFAULT NULL,
`Datum` date DEFAULT NULL,
`BestellingstypeId` int(11) DEFAULT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Anyone got an idea?
This will happen if the table contains an existing record with an id of 0 (or negative). Updating all existing records to use positive values will allow auto_increment to be set on that column.
Edit: Some people asked how that 0 got in there. For clarification, the MySQL Reference Manual states that "For numeric types, the default is 0, with the exception that for integer or floating-point types declared with the AUTO_INCREMENT attribute, the default is the next value in the sequence." So, if you performed an insert on a table without providing a value for the numeric column before the auto_increment was enabled, then the default 0 would be used during the insert. More details may be found at https://dev.mysql.com/doc/refman/5.0/en/data-type-defaults.html.
I also had this issue when trying to convert a column to auto_increment where one row had a value of 0. An alternative to changing the 0 value temporarily is via setting:
SET SESSION sql_mode='NO_AUTO_VALUE_ON_ZERO';
for the session.
This allowed the column to be altered to auto_increment with the zero id in place.
The zero isn't ideal - and I also wouldn't recommend it being used in an auto_increment column. Unfortunately it's part of an inherited data set so I'm stuck with it for now.
Best to clear the setting (and any others) afterwards with:
SET SESSION sql_mode='';
although it will be cleared when the current client session clsoes.
Full details on the 'NO_AUTO_VALUE_ON_ZERO' setting here.
This happens when MySQL can not determine a proper auto_increment value. In your case, MySQL choose 1 as next auto_increment value, however there is already row with that value in the table.
One way to resolve the issue is to choose a proper auto_increment value yourself:
ALTER TABLE ... CHANGE COLUMN `Id` `Id` INT(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT = 123456;
(Note the AUTO_INCREMENT=123456 at the end.)
The easiest way that I have found to solve this issue is to first set the table's AUTO INCREMENT value before altering the column. Just make sure that you set the auto increment value higher than the largest value currently in that column:
ALTER TABLE `aafest`.`aafest_bestelling`
AUTO_INCREMENT = 100,
CHANGE COLUMN `Id` `Id` INT(11) NOT NULL AUTO_INCREMENT
I tested this on MySQL 5.7 and it worked great for me.
Edit: Don't know exactly how that would be caused, but I do have a workaround.
First, create a new table like the old one:
CREATE TABLE aafest_bestelling_new LIKE aafest_bestelling;
Then change the column
ALTER TABLE `aafest`.`aafest_bestelling_new`
CHANGE COLUMN `Id` `Id` INT(11) NOT NULL AUTO_INCREMENT
Dump in the new data:
INSERT INTO aafest_bestelling_new
(KlantId, Datum, BestellingTypeId)
SELECT
KlantId, Datum, BestellingTypeId
FROM aafest_bestelling;
Move the tables:
RENAME TABLE
aafest_bestelling TO aafest_bestelling_old,
aafest_bestelling_new TO aafest_bestelling;
Maybe there's some corruption going on, and this would fix that as well.
P.S.: As a dutchman, I'd highly recommend coding in english ;)
I had a similar issue. Issue was the table had a record with ID = 0 similar to what SystemParadox pointed out. I handled my issue by the following steps:
Steps:
Update record id 0 to be x where x = MAX(id)+1
Alter table to set primary key and auto increment setting
Set seed value to be x+1
Change record id x back to 0
Code Example:
UPDATE foo SET id = 100 WHERE id = 0;
ALTER TABLE foo MODIFY COLUMN id INT(11) NOT NULL AUTO_INCREMENT;
ALTER TABLE foo AUTO_INCREMENT = 101;
UPDATE foo SET id = 0 WHERE id = 100;
This happens because your primary key column already has values.
As the error says ...
ALTER TABLE causes auto_increment resequencing, resulting in duplicate entry '1' for key 'PRIMARY'
which means that your column already has a primary key value 1 which when you auto_increment that column is reassigned causing duplication and hence this error
the solution to this is to remove the primary constraint and then empty the column. Then alter the table setting the primary key again, this time with auto increment.
This error comes because the any table contains an existing record with an id of 0 (or negative). Update all existing records to use positive values will allow auto_increment to be set on that column.
If this didn't work then export all the data and save it any where in you computer and dont first make foreign key relation then fill data in parent table .
This error will also happen if have a MyISAM table that has a composite AUTO_INCREMENT PRIMARY KEY and are trying to combine the keys
For example
CREATE TABLE test1 (
`id` int(11) NOT NULL,
`ver` int(10) unsigned NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`,`ver`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
INSERT INTO test1 (`id`, `ver`) VALUES (1,NULL),(1,NULL),(1,NULL), (2,NULL),(2,NULL),(2,NULL);
ALTER TABLE test1 DROP PRIMARY KEY, ADD PRIMARY KEY(`ver`);
Not being able to set an existing column to auto_increment also happens if the column you're trying to modify is included in a foreign key relation in another table (although it won't produce the error message referred to in the question).
(I'm adding this answer even though it doesn't relate to the specific error message in the body of the question because this is the first result that shows up on Google when searching for issues relating to not being able to set an existing MySQL column to auto_increment.)
I am using a VARCHAR as my primary key. I want to auto increment it (base 62, lower/upper case, numbers), However, the below code fails (for obvious reasons):
CREATE TABLE IF NOT EXISTS `campaign` (
`account_id` BIGINT(20) NOT NULL,
`type` SMALLINT(5) NOT NULL,
`id` VARCHAR(16) NOT NULL AUTO_INCREMENT PRIMARY KEY
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
however, this works:
CREATE TABLE IF NOT EXISTS `campaign` (
`account_id` BIGINT(20) NOT NULL,
`type` SMALLINT(5) NOT NULL,
`id` VARCHAR(16) NOT NULL PRIMARY KEY
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
What is the best way to keep track of incrementation of 'id' myself? (Since auto_increment doesn't work). Do i need to make another table that contains the current iteration of ID? Or is there a better way to do this?
EDIT: I want to clarify that I know that using INT is a auto_increment primary key is the logical way to go. This question is in response to some previous dialogue I saw. Thanks
you have to use an INT field
and translate it to whatever format you want at select time
example of a solution to your problem:
create a file with a unique number and then increment with a function.
the filename can be the prefix and the file binary content represent a number.
when you need a new id to the reg invoque the function
Example
String generateID(string A_PREFIX){
int id_value = parsetoInt(readFile(A_PREFIX).getLine())
int return_id_value = id_value++
return return_id_value
}
where "A_PREFIX-" is the file name wich you use to generate the id for the field.
Or just create a sequence and maintain the pk field using the sequence to generate the primary key value with nextval function. And if perf is an issue, use cache on sequence.
But as others have stated, this is sub-optimal, if your primary key contains a numbered sequence then it's better to use int and auto-increment.
I don't see a use case where pk has to auto-increment but be a varchar data type, it doesn't make sense.
Assuming that for reasons external to the database, you do need that varchar column, and it needs to autoIncrement, then how about creating a trigger that grabs the existing autoIncrement value and uses Convert() to convert that value into a VarChar, dropping the VarChar into the field of interest. As mentioned in a previous answer, you could concatenate the table-name with the new varChar value, if there is some advantage to that.