When I use this query:
CREATE TABLE users(
id int not null auto_increment primary key,
username varchar(30) not null unique,
email varchar(255) not null unique,
password varchar(255) not null
);
CREATE TABLE items(
id int not null auto_increment primary key,
name varchar(30) not null,
user_id int not null,
FOREIGN KEY user_key(user_id)
REFERENCES users(id)
);
DROP TABLE users;
It shows this error:
1217 - Cannot delete or update a parent row: a foreign key constraint fails
Which is alright because that is how mySQL database naturally reacts when we want to drop table that is referenced by other table that depends on it.
However, this same query shows no errors and actually drops users table on my pal's PC.
What could be the case? Is there a way to disable it?
You may be using different database engines. MyISAM and InnoDB have different FK support/enforcement, I believe. It could also be that the data in each of your tables is different.
If you want to drop a table that is a dependency of another table, though, the "right" way is to remove the FK from the dependent table and then drop the table that you want to.
I created a table in phpMyAdmin. When I export my MySQL database, the unique key is defined as UNIQUE KEY `id` (`id`), with the column name repeated in parentheses:
CREATE TABLE IF NOT EXISTS `beitraege` (
`id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, // smallint? (65000!)
...
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
Why is the column name repeated in parentheses? What does that mean? Creating a table in MySQL (and not using phpMyAdmin), when do I need to use this parenthetical repetition, and are there cases where the parenthesis might contain the name of a different column?
You can define indexes that span several columns. Imagine your table contains city names and you want to ensure the names are unique, but of course you can have cities with the same name in different states and countries. You can achieve that with:
UNIQUE KEY uniq_state_city (state, city)
The first id is the name for the index. The second id in parentheses is the column name. see create table
I have the following table with 1,000,000+ records:
CREATE TABLE `products` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`description` text,
PRIMARY KEY (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
What I'd like to do is be able to fetch products with null description quickly - forget about empty string.
If I add a key by description, the whole description will be indexed and I don't want such a big index. I could indeed do:
ALTER TABLE products ADD KEY has_description (description(1));
This will create an index with only the first character. This is much better than having a "complete" index, but I'd like to know if there's a way to create a proper index - e.g. a boolean index, true/false depending on the product having a description or not respectively.
Additional requirement is not adding a new column with this value - that is trivial, but it's duplicated information I don't want to have in the table.
Already tried stuff like
ALTER TABLE products ADD KEY has_description (description IS NULL);
... but didn't work.
Can this be done at all?
You can only have Index on existing fields.
The answer is: no way
But you can add another Field (and Index for that) containing the description state (empty or not).
Use Insert and Update trigger to have that field always synced with description data.
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.
I'm relatively new to MySQL.
So, let's say I make a table and my table utilizes an "id" column to keep track of a unique identification number. However, when creating my table, I neglected to specify that I wanted the column to be auto-incremented, not null, and the primary key of the table. What MySQL statement can I use to alter the information of this table so that it is correct for what I want? I have tried some variations of the "ALTER TABLE" command, don't seem to understand the syntax.
use this:
ALTER TABLE `table_name`
MODIFY COLUMN `id` BIGINT( 20 ) PRIMARY KEY AUTO_INCREMENT
ALTER TABLE `yourTable`
CHANGE COLUMN `id` `id` INT(10) NOT NULL AUTO_INCREMENT FIRST,
ADD PRIMARY KEY (`id`);