I used this code however it showed that unrecognized alter operation and also that key is unrecognized.
ALTER TABLE `ecommerce`.`users` (id INT(11) NOT NULL, PRIMARY-KEY AUTO_INCREMENT);
The correct syntax is:
ALTER TABLE ecommerce.users add column id INT AUTO_INCREMENT PRIMARY KEY;
Here is a db<>fiddle.
EDIT:
I realize the OP might already have the column and want to replace the definition. That works with this syntax:
ALTER TABLE users modify column id INT AUTO_INCREMENT PRIMARY KEY;
Here is this db<>fiddle.
you can give primary while creating your table or after create table you can add primary key by alter table
while creating table
create table info(id int primary key,Name varchar(25),dept varchar(25));
create table info(id int,Name varchar(25),dept varchar(25),primary key(id));
after creating table
alter table info add primary key(id);
Related
When I execute the follow two queries (I have stripped them down to absolutely necessary):
mysql> CREATE TABLE foo(id INT PRIMARY KEY);
Query OK, 0 rows affected (0.01 sec)
mysql> CREATE TABLE bar ( id INT, ref INT, FOREIGN KEY (ref) REFERENCES foo(id)) ENGINE InnoDB;
I get the following error:
ERROR 1005 (HY000): Can't create table './test/bar.frm' (errno: 150)
Where the **** is my error? I haven't found him while staring at this for half an hour.
From FOREIGN KEY Constraints
If you re-create a table that was
dropped, it must have a definition
that conforms to the foreign key
constraints referencing it. It must
have the right column names and types,
and it must have indexes on the
referenced keys, as stated earlier. If
these are not satisfied, MySQL returns
error number 1005 and refers to error
150 in the error message.
My suspicion is that it's because you didn't create foo as InnoDB, as everything else looks OK.
Edit: from the same page -
Both tables must be InnoDB tables and they must not be TEMPORARY tables.
You can use the command SHOW ENGINE INNODB STATUS to get more specific information about the error.
It will give you a result with a Status column containing a lot of text.
Look for the section called LATEST FOREIGN KEY ERROR which could for example look like this:
------------------------
LATEST FOREIGN KEY ERROR
------------------------
190215 11:51:26 Error in foreign key constraint of table `mydb1`.`contacts`:
Create table `mydb1`.`contacts` with foreign key constraint failed. You have defined a SET NULL condition but column 'domain_id' is defined as NOT NULL in ' FOREIGN KEY (domain_id) REFERENCES domains (id) ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT contacts_teams_id_fk FOREIGN KEY (team_id) REFERENCES teams (id) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT' near ' ON DELETE SET NULL ON UPDATE CASCADE,
CONSTRAINT contacts_teams_id_fk FOREIGN KEY (team_id) REFERENCES teams (id) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPACT'.
To create a foreign key ,
both the main column and the reference column must have same definition.
both tables engine must be InnoDB.
You can alter the engine of table using this command , please take the backup before executing this command.
alter table [table name] ENGINE=InnoDB;
I had the same problem, for those who are having this also:
check the table name of the referenced table
I had forgotten the 's' at the end of my table name
eg table Client --> Clients
:)
Apart form many other reasons to end up with MySql Error 150 (while using InnoDB), One of the probable reason, is the undefined KEY in the create statement of the table containing the column name referenced as a foreign key in the relative table.
Let's say the create statement of master table is -
CREATE TABLE 'master_table' (
'id' int(10) NOT NULL AUTO_INCREMENT,
'record_id' char(10) NOT NULL,
'name' varchar(50) NOT NULL DEFAULT '',
'address' varchar(200) NOT NULL DEFAULT '',
PRIMARY KEY ('id')
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
and the create syntax for the relative_table table where the foreign key constraint is set from primary table -
CREATE TABLE 'relative_table' (
'id' int(10) NOT NULL AUTO_INCREMENT,
'salary' int(10) NOT NULL DEFAULT '',
'grade' char(2) NOT NULL DEFAULT '',
'record_id' char(10) DEFAULT NULL,
PRIMARY KEY ('id'),
CONSTRAINT 'fk_slave_master' FOREIGN KEY ('record_id') REFERENCES 'master' ('record_id')
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
This script is definitely going to end with MySql Error 150 if using InnoDB.
To solve this, we need to add a KEY for the The column record_id in the master_table table and then reference in the relative_table table to be used as a foreign_key.
Finally, the create statement for the master_table, will be -
CREATE TABLE 'master_table' (
'id' int(10) NOT NULL AUTO_INCREMENT,
'record_id' char(10) NOT NULL,
'name' varchar(50) NOT NULL DEFAULT '',
'address' varchar(200) NOT NULL DEFAULT '',
PRIMARY KEY ('id'),
KEY 'record_id' ('record_id')
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I had very same problem and the reason was the "collation" of columns was different. One was latin1 while the other was utf8
This may also happen if you have not given correct column name after "references" keyword.
ColumnName is Unique (UNIQUE KEY ColumnName).
I just want to make column not unique (must be very simple, but can not understand how).
If in phpMyAdmin check at column name and at bottom click on Unique icon, get #1062 - Duplicate entry '' for key 'RegistrationNumber'. OK, see it is because, clicking on icon it ADD UNIQUE.
There is Unique icon in Structure within row. But the icon is not click-able.
As in phpMyAdmin did not found how to do it, trying with query.
Based on advices tried ALTER TABLE TableName DROP INDEX ColumnName.
Get 1091 Can't DROP 'ColumnName'; check that column/key exists
Here https://stackoverflow.com/a/4414694/2465936 found This error means that you are trying to delete a key which is being used by another table. Possibly the ColumnName is used by another table.
Please advice what need to do to make column not unique.
With SHOW CREATE TABLE get
Array
(
[0] => Array
(
[Table] => 18_6_TransactionPartners
[Create Table] => CREATE TABLE `18_6_TransactionPartners` (
`Number` int(11) NOT NULL AUTO_INCREMENT,
`CompanyName` char(255) COLLATE utf8_unicode_ci NOT NULL,
`RegistrationNumber` char(255) COLLATE utf8_unicode_ci NOT NULL,
.......
PRIMARY KEY (`Number`),
UNIQUE KEY `Number_2` (`Number`),
UNIQUE KEY `CompanyName` (`CompanyName`,`RegistrationNumber`),
KEY `Number` (`Number`)
) ENGINE=InnoDB AUTO_INCREMENT=444 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
)
)
Update
Based on #Bart Friederichs advice tried ALTER TABLE 18_6_TransactionPartners DROP INDEX Number and changed column RegistrationNumber not not unique. Do not understand why (possibly had some mess with unique keys). In any case can change to not unique.
Probably you have a named INDEX. By using SHOW CREATE TABLE tbl you can find out the names of the indices. Then drop them by name (e.g. some test table):
mysql> SHOW CREATE TABLE test;
CREATE TABLE `test` (
`entry_id` int(11) DEFAULT NULL,
`user_id` int(11) DEFAULT NULL,
UNIQUE KEY `k` (`entry_id`)
)
To drop the index, use this:
ALTER TABLE test DROP INDEX k;
Your key name is RegistrationNumber (as is told by the error message):
ALTER TABLE TableName DROP INDEX RegistrationNumber;
If your column was defined unique using UNIQUE clause, then you can do something like this:
ALTER TABLE mytable DROP INDEX constraint_name
For dropping the index do this:-
ALTER TABLE mytable DROP INDEX index_name;
You have to drop the index using the index name, not the column name.
I'm trying to create a database in MySQL on phpMyAdmin. I am able to create the tables without any trouble, but I also want to add some foreign keys. In this case I want to link the BIDS and CLIENTS tables via the CLIENTID attribute.
CREATE TABLE BIDS (
BIDID NUMERIC(3) NOT NULL PRIMARY KEY,
CLIENTID NUMERIC(3) NOT NULL
);
CREATE TABLE CLIENTS (
CLIENTID NUMERIC(3) NOT NULL,
EMAILADDRESSES VARCHAR(100) NOT NULL,
PHONENUMBERS VARCHAR(11) NOT NULL,
FOREIGN KEY (CLIENTID) REFERENCES BIDS (CLIENTID),
PRIMARY KEY (CLIENTID,EMAILADDRESSES,PHONENUMBERS)
);
Research has told me that the syntax is correct, but this code returns the following error.
1005 - Can't create table 'CLIENTS' (errno: 150)
Apparently, a solution might be involved with something called 'InnoDB'. How can I use it to fix my problem?
Syntax is fine but problem is with FORIEGN KEY statement as below. You can't create FK on a non-key column. In BIDS table it's BIDID which is defined as Primary Key and not CLIENTID
FOREIGN KEY (CLIENTID) REFERENCES BIDS (CLIENTID)
So, your FORIEGN KEY definition should actually be
FOREIGN KEY (CLIENTID) REFERENCES BIDS (BIDID)
See a demo here http://sqlfiddle.com/#!2/f1c9ec
When I copy all tables from one database and paste them to other database, how to set all auto_increments from these tables to start value? Is it possible to make a php script for such thing?
Try this one:
ALTER TABLE test AUTO_INCREMENT = 'startvalue'
Condition:
if table not empty start value must greater then MAX(AUTO_INCREMENT)
If AUTO_INCREMENT column is primary key and if you re-sort the AUTO_INCREMENT column data, it may be problem in relationship with other tables. Instead of re-sorting your AUTO_INCREMENT data, you can import as follows:
You can disable the AUTO_INCREMENT on the new table as follows:
ALTER TABLE [your_table] CHANGE auto_increment_column_name auto_increment_column_name INT(11) NOT NULL
After inserting, you can enable AUTO_INCREMENT and set it again as follows:
ALTER TABLE [your_table] AUTO_INCREMENT = [Maximum value]
Alternatively, you have to update all dependent tables foreign key values using a migration script.
I am trying to alter a table which has no primary key nor auto_increment column. I know how to add an primary key column but I was wondering if it's possible to insert data into the primary key column automatically (I already have 500 rows in DB and want to give them id but I don't want to do it manually). Any thoughts? Thanks a lot.
An ALTER TABLE statement adding the PRIMARY KEY column works correctly in my testing:
ALTER TABLE tbl ADD id INT PRIMARY KEY AUTO_INCREMENT;
On a temporary table created for testing purposes, the above statement created the AUTO_INCREMENT id column and inserted auto-increment values for each existing row in the table, starting with 1.
suppose you don't have column for auto increment like id, no, then you can add using following query:
ALTER TABLE table_name ADD id int NOT NULL AUTO_INCREMENT primary key FIRST
If you've column, then alter to auto increment using following query:
ALTER TABLE table_name MODIFY column_name datatype(length) AUTO_INCREMENT PRIMARY KEY
For those like myself getting a Multiple primary key defined error try:
ALTER TABLE `myTable` ADD COLUMN `id` INT AUTO_INCREMENT UNIQUE FIRST NOT NULL;
On MySQL v5.5.31 this set the id column as the primary key for me and populated each row with an incrementing value.
In order to make the existing primary key as auto_increment, you may use:
ALTER TABLE table_name MODIFY id INT AUTO_INCREMENT;
Yes, something like this would do it, it might not be the best though. You might wanna make a backup:
$get_query = mysql_query("SELECT `any_field` FROM `your_table`");
$auto_increment_id = 1;
while($row = mysql_fetch_assoc($get_query))
{
$update_query = mysql_query("UPDATE `your_table` SET `auto_increment_id`=$auto_increment_id WHERE `any_field` = '".$row['any_field']."'");
$auto_increment_id++;
}
Notice that the the any_field you select must be the same when updating.
The easiest and quickest I find is this
ALTER TABLE mydb.mytable
ADD COLUMN mycolumnname INT NOT NULL AUTO_INCREMENT AFTER updated,
ADD UNIQUE INDEX mycolumnname_UNIQUE (mycolumname ASC);
I was able to adapt these instructions take a table with an existing non-increment primary key, and add an incrementing primary key to the table and create a new composite primary key with both the old and new keys as a composite primary key using the following code:
DROP TABLE IF EXISTS SAKAI_USER_ID_MAP;
CREATE TABLE SAKAI_USER_ID_MAP (
USER_ID VARCHAR (99) NOT NULL,
EID VARCHAR (255) NOT NULL,
PRIMARY KEY (USER_ID)
);
INSERT INTO SAKAI_USER_ID_MAP VALUES ('admin', 'admin');
INSERT INTO SAKAI_USER_ID_MAP VALUES ('postmaster', 'postmaster');
ALTER TABLE SAKAI_USER_ID_MAP
DROP PRIMARY KEY,
ADD _USER_ID INT AUTO_INCREMENT NOT NULL FIRST,
ADD PRIMARY KEY ( _USER_ID, USER_ID );
When this is done, the _USER_ID field exists and has all number values for the primary key exactly as you would expect. With the "DROP TABLE" at the top, you can run this over and over to experiment with variations.
What I have not been able to get working is the situation where there are incoming FOREIGN KEYs that already point at the USER_ID field. I get this message when I try to do a more complex example with an incoming foreign key from another table.
#1025 - Error on rename of './zap/#sql-da07_6d' to './zap/SAKAI_USER_ID_MAP' (errno: 150)
I am guessing that I need to tear down all foreign keys before doing the ALTER table and then rebuild them afterwards. But for now I wanted to share this solution to a more challenging version of the original question in case others ran into this situation.
Export your table, then empty your table, then add field as unique INT, then change it to AUTO_INCREMENT, then import your table again that you exported previously.
You can add a new Primary Key column to an existing table, which can have sequence numbers, using command:
ALTER TABLE mydb.mytable ADD pk_columnName INT IDENTITY
I was facing the same problem so what I did I dropped the field for the primary key then I recreated it and made sure that it is auto incremental . That worked for me . I hope it helps others
ALTER TABLE tableName MODIFY tableNameID MEDIUMINT NOT NULL AUTO_INCREMENT;
Here tableName is name of your table,
tableName is your column name which is primary has to be modified
MEDIUMINT is a data type of your existing primary key
AUTO_INCREMENT you have to add just auto_increment after not null
It will make that primary key auto_increment......
Hope this is helpful:)
Well, you have multiple ways to do this:
-if you don't have any data on your table, just drop it and create it again.
Dropping the existing field and creating it again like this
ALTER TABLE test DROP PRIMARY KEY, DROP test_id, ADD test_id int AUTO_INCREMENT NOT NULL FIRST, ADD PRIMARY KEY (test_id);
Or just modify it
ALTER TABLE test MODIFY test_id INT AUTO_INCREMENT NOT NULL, ADD PRIMARY KEY (test_id);
How to write PHP to ALTER the already existing field (name, in this example) to make it a primary key? W/o, of course, adding any additional 'id' fields to the table..
This a table currently created - Number of Records found: 4 name VARCHAR(20) YES
breed VARCHAR(30) YES
color VARCHAR(20) YES
weight SMALLINT(7) YES
This an end result sought (TABLE DESCRIPTION) -
Number of records found: 4
name VARCHAR(20) NO PRI
breed VARCHAR(30) YES
color VARCHAR(20) YES
weight SMALLINT(7) YES
Instead of getting this -
Number of Records found: 5
id int(11) NO PRI
name VARCHAR(20) YES
breed VARCHAR(30) YES
color VARCHAR(20) YES
weight SMALLINT(7) YES
after trying..
$query = "ALTER TABLE racehorses ADD id INT NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY (id)";
how to get this? -
Number of records found: 4
name VARCHAR(20) NO PRI
breed VARCHAR(30) YES
color VARCHAR(20) YES
weight SMALLINT(7) YES
i.e. INSERT/ADD.. etc. the primary key INTO the first field record (w/o adding an additional 'id' field, as stated earlier.
No existing primary key
ALTER TABLE `db`.`table`
ADD COLUMN `id` INT NOT NULL AUTO_INCREMENT FIRST,
ADD PRIMARY KEY (`id`);
;
Table already has an existing primary key'd column
(it will not delete the old primary key column)
ALTER TABLE `db`.`table`
ADD COLUMN `id` INT NOT NULL AUTO_INCREMENT FIRST,
CHANGE COLUMN `prev_column` `prev_column` VARCHAR(2000) NULL ,
DROP PRIMARY KEY,
ADD PRIMARY KEY (`id`);
;
Note: column must be first for auto increment which is why the FIRST command.