Drop unique constraint in MySQL and H2 - mysql

I have the following constraint in CREATE statement:
UNIQUE (`field_name`)
These commands to remove constraint work in MySQL but not in H2:
DROP INDEX `field_name` ON `table_name`;
ALTER TABLE `table_name` DROP INDEX `field_name`;
I need a command which would work both in MySQL and H2 (MySQL is used in real environment and H2 in Unit tests)

Found the following workaround: removing column removes the constraint, so:
ALTER TABLE `table_name` ADD COLUMN `tmp_code` VARCHAR(50) NOT NULL DEFAULT 'TMP';
UPDATE `table_name`
SET `tmp_code` = `field_name`;
ALTER TABLE `table_name` DROP COLUMN `field_name`;
ALTER TABLE `table_name` ADD COLUMN `field_name` VARCHAR(50) NOT NULL;
UPDATE `table_name`
SET `field_name` = `tmp_code`;
ALTER TABLE `table_name` DROP COLUMN `tmp_code`;

Do SHOW CREATE TABLE to see the name of the UNIQUE KEY. Then you can proceed with the DROP or ALTER. It will probably say
UNIQUE KEY `col` (`col`),
The first col is the key name.
If you need to maintain the INDEX but get rid of the UNIQUEness constraint, then drop the key, then add a non-unique key.

Related

MySQL: delete constraint UNIQUE KEY

I have this table:
CREATE TABLE table1 (
//..
UNIQUE KEY `UNIQ_60349993F97DBD80` (`contrat_parent_id`)
//..
)ENGINE=InnoDB AUTO_INCREMENT=4384 DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci.
I try this statement:
alter table table drop index UNIQ_60349993F97DBD80
But it doesn't work. I try many statements, but, they don't work.
Can I help me ?
Just remove ALTER TABLE from the begging of your statement, and also add the table Name on the end.
drop index UNIQ_60349993F97DBD80 ON table1
Reference

Performance concerns regarding ALTER TABLE ADD COLUMN

I have a big MySQL InnoDB table having 5 million rows. I need to add a column to the table which will have a default int value.
What is the best way to do it? The normal alter table command appears to take a lot of time. Is there any better way to do it? Basically I want to know if there is any faster way or efficient way of doing it.
And if the table has foreign key references, is there any way other than alter table to do this?
Any help appreciated.
I would not say this is a better way, but ... You could create a separate table for the new data and set it up as foreign key relationship to the existing table. That would be "fast", but if the data really belongs in the main table and every (or most) existing records will have a value, then you should just alter the table and add it.
Suppose the table looked like this:
CREATE TABLE mytable
(
id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(25),
PRIMARY KEY (id),
KEY name (name)
);
and you want to add an age column with
ALTER TABLE mytable ADD COLUMN age INT NOT NULL DEFAULT 0;
You could perform the ALTER TABLE in stages as follows:
CREATE TABLE mytablenew LIKE mytable;
ALTER TABLE mytablenew ADD COLUMN age INT NOT NULL DEFAULT 0;
INSERT INTO mytablenew SELECT id,name FROM mytable;
ALTER TABLE mytable RENAME mytableold;
ALTER TABLE mytablenew RENAME mytable;
DROP TABLE mytableold;
If mytable uses the MyISAM Storage Engine and has nonunique indexes, add two more lines
CREATE TABLE mytablenew LIKE mytable;
ALTER TABLE mytablenew ADD COLUMN address VARCHAR(50);
ALTER TABLE mytablenew DISABLE KEYS;
INSERT INTO mytablenew SELECT id,name FROM mytable;
ALTER TABLE mytable RENAME mytableold;
ALTER TABLE mytablenew RENAME mytable;
DROP TABLE mytableold;
ALTER TABLE mytable ENABLE KEYS;
This will let you see how many seconds each stage takes. From here, you can decide whether or not a straightforward ALTER TABLE is better.
This technique gets a little gory if there are foreign key references.
Your steps would be
SET UNIQUE_CHECKS = 0;
SET FOREIGN_KEY_CHECKS = 0;
Drop the foreign key references in mytable.
Perform the ALTER TABLE in Stages
Create the foreign key references in mytable.
SET UNIQUE_CHECKS = 1;
SET FOREIGN_KEY_CHECKS = 1;
Give it a Try !!!

How to delete a column from a table in MySQL

Given the table created using:
CREATE TABLE tbl_Country
(
CountryId INT NOT NULL AUTO_INCREMENT,
IsDeleted bit,
PRIMARY KEY (CountryId)
)
How can I delete the column IsDeleted?
ALTER TABLE tbl_Country DROP COLUMN IsDeleted;
Here's a working example.
Note that the COLUMN keyword is optional, as MySQL will accept just DROP IsDeleted. Also, to drop multiple columns, you have to separate them by commas and include the DROP for each one.
ALTER TABLE tbl_Country
DROP COLUMN IsDeleted,
DROP COLUMN CountryName;
This allows you to DROP, ADD and ALTER multiple columns on the same table in the one statement. From the MySQL reference manual:
You can issue multiple ADD, ALTER, DROP, and CHANGE clauses in a single ALTER TABLE statement, separated by commas. This is a MySQL extension to standard SQL, which permits only one of each clause per ALTER TABLE statement.
Use ALTER TABLE with DROP COLUMN to drop a column from a table, and CHANGE or MODIFY to change a column.
ALTER TABLE tbl_Country DROP COLUMN IsDeleted;
ALTER TABLE tbl_Country MODIFY IsDeleted tinyint(1) NOT NULL;
ALTER TABLE tbl_Country CHANGE IsDeleted IsDeleted tinyint(1) NOT NULL;
To delete a single column:
ALTER TABLE `table1` DROP `column1`;
To delete multiple columns:
ALTER TABLE `table1`
DROP `column1`,
DROP `column2`,
DROP `column3`;
You can use
alter table <tblname> drop column <colname>
ALTER TABLE `tablename` DROP `columnname`;
Or,
ALTER TABLE `tablename` DROP COLUMN `columnname`;
If you are running MySQL 5.6 onwards, you can make this operation online, allowing other sessions to read and write to your table while the operation is been performed:
ALTER TABLE tbl_Country DROP COLUMN IsDeleted, ALGORITHM=INPLACE, LOCK=NONE;
Use ALTER:
ALTER TABLE `tbl_Country` DROP COLUMN `column_name`;
ALTER TABLE tbl_Country DROP columnName;
It is worth mentioning that MySQL 8.0.23 and above supports Invisible Columns
CREATE TABLE tbl_Country(
CountryId INT NOT NULL AUTO_INCREMENT,
IsDeleted bit,
PRIMARY KEY (CountryId)
);
INSERT INTO tbl_Country VALUES (1, 1), (2,0);
ALTER TABLE tbl_Country ALTER COLUMN IsDeleted SET INVISIBLE;
SELECT * FROM tbl_Country;
CountryId
1
2
ALTER TABLE tbl_Country DROP COLUMN IsDeleted;
db<>fiddle demo
It may be useful in scenarios when there is need to "hide" a column for a time being before it could be safely dropped(like reworking corresponding application/reports etc.).

How to add AUTO_INCREMENT to an existing column?

How do I add auto_increment to an existing column of a MySQL table?
I think you want to MODIFY the column as described for the ALTER TABLE command. It might be something like this:
ALTER TABLE users MODIFY id INTEGER NOT NULL AUTO_INCREMENT;
Before running above ensure that id column has a Primary index.
Method to add AUTO_INCREMENT to a table with data while avoiding “Duplicate entry” error:
Make a copy of the table with the data using INSERT SELECT:
CREATE TABLE backupTable LIKE originalTable;
INSERT backupTable SELECT * FROM originalTable;
Delete data from originalTable (to remove duplicate entries):
TRUNCATE TABLE originalTable;
To add AUTO_INCREMENT and PRIMARY KEY
ALTER TABLE originalTable ADD id INT PRIMARY KEY AUTO_INCREMENT;
Copy data back to originalTable (do not include the newly created column (id), since it will be automatically populated)
INSERT originalTable (col1, col2, col3)
SELECT col1, col2,col3
FROM backupTable;
Delete backupTable:
DROP TABLE backupTable;
More on the duplication of tables using CREATE LIKE:
Duplicating a MySQL table, indices, and data
Alter table table_name modify column_name datatype(length) AUTO_INCREMENT PRIMARY KEY
You should add primary key to auto increment, otherwise you got error in mysql.
Simply just add auto_increment Constraint In column or MODIFY COLUMN :-
ALTER TABLE `emp` MODIFY COLUMN `id` INT NOT NULL UNIQUE AUTO_INCREMENT FIRST;
Or add a column first then change column as -
1. Alter TABLE `emp` ADD COLUMN `id`;
2. ALTER TABLE `emp` CHANGE COLUMN `id` `Emp_id` INT NOT NULL UNIQUE AUTO_INCREMENT FIRST;
This worked for me in case you want to change the AUTO_INCREMENT-attribute for a not-empty-table:
1.)Exported the whole table as .sql file
2.)Deleted the table after export
2.)Did needed change in CREATE_TABLE command
3.)Executed the CREATE_TABLE and INSERT_INTO commands from the .sql-file
...et viola
I managed to do this with the following code:
ALTER TABLE `table_name`
CHANGE COLUMN `colum_name` `colum_name` INT(11) NOT NULL AUTO_INCREMENT FIRST;
This is the only way I could make a column auto increment.
INT(11) shows that the maximum int length is 11, you can skip it if you want.
Alter table table_name modify table_name.column_name data_type AUTO_INCREMENT;
eg:
Alter table avion modify avion.av int AUTO_INCREMENT;
if you have FK constraints and you don't want to remove the constraint from the table. use "index" instead of primary. then you will be able to alter it's type to auto increment
I had existing data in the first column and they were 0's.
First I made the first column nullable.
Then I set the data for the column to null.
Then I set the column as an index.
Then I made it a primary key with auto incrementing turned on. This is where I used another persons answer above:
ALTER TABLE `table_name` CHANGE COLUMN `colum_name` `colum_name` INT(11) NOT NULL AUTO_INCREMENT FIRST;
This Added numbers to all the rows of this table starting at one. If I ran the above code first it wasn't working because all the values were 0's. And making it an index was also required before making it auto incrementing.
Next I made the column a primary key.
This worked in my case , if you want to change the column attribute to auto-increment which is already having some data
1.GO to structure, select the column to want to change.
2.After selecting the column , choose primary key from the options below.
[1]: https://i.stack.imgur.com/r7w8f.png
3.Then change the column attribute to auto-increment using alter method
This is to alter the column adding PRIMARY key:
ALTER TABLE `schema_name`.`table_name`
CHANGE COLUMN `id` `id` INT(11) NOT NULL AUTO_INCREMENT ,
ADD UNIQUE INDEX `id_UNIQUE` (`id` ASC) VISIBLE,
ADD PRIMARY KEY (`id`);
I copied it from MySQL Workbench... I got curious to see if it was possible to do it all in one command. I'm a little rusty in SQL.
If you are working in an specific schema, you don't need to specify it.
The above statement will create the index, set the column as the PRIMARY KEY as well with just one query.
KEEP IN MIND: There could not be duplicated values in the same column, if there are, the statement will fail to commit.
ALTER TABLE Table name ADD column datatype AUTO_INCREMENT,ADD primary key(column);

How to drop unique in MySQL?

Create Table: CREATE TABLE `fuinfo` (
`fid` int(10) unsigned NOT NULL,
`name` varchar(40) NOT NULL,
`email` varchar(128) NOT NULL,
UNIQUE KEY `email` (`email`),
UNIQUE KEY `fid` (`fid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8
I want to drop the unique key on email,how?
Simply you can use the following SQL Script to delete the index in MySQL:
alter table fuinfo drop index email;
There is a better way which don't need you to alter the table:
mysql> DROP INDEX email ON fuinfo;
where email is the name of unique key (index).
You can also bring it back like that:
mysql> CREATE UNIQUE INDEX email ON fuinfo(email);
where email after IDEX is the name of the index and it's not optional. You can use KEY instead of INDEX.
Also it's possible to create (remove) multicolumn unique indecies like that:
mysql> CREATE UNIQUE INDEX email_fid ON fuinfo(email, fid);
mysql> DROP INDEX email_fid ON fuinfo;
If you didn't specify the name of multicolumn index you can remove it like that:
mysql> DROP INDEX email ON fuinfo;
where email is the column name.
mysql> DROP INDEX email ON fuinfo;
where email is the unique key (rather than the column name). You find the name of the unique key by
mysql> SHOW CREATE TABLE fuinfo;
here you see the name of the unique key, which could be email_2, for example. So...
mysql> DROP INDEX email_2 ON fuinfo;
mysql> DESCRIBE fuinfo;
This should show that the index is removed
Use below query :
ALTER TABLE `table_name` DROP INDEX key_name;
If you don't know the key_name then first try below query, you can get key_name.
SHOW CREATE TABLE table_name
OR
SHOW INDEX FROM table_name;
If you want to remove/drop primary key from mysql table, Use below query for that
ALTER TABLE `products` DROP INDEX `PRIMARY`;
Code Taken from: http://chandreshrana.blogspot.in/2015/10/how-to-remove-unique-key-from-mysql.html
DROP INDEX column_name ON table_name
Select the database and query form the sql tab.This removes the index of the particular column. It worked for me in PHP MyADMIN
This may help others
alter table fuinfo drop index fuinfo_email_unique
For MySQL 5.7.11
Step-1: First get the Unique Key
Use this query to get it:
1.1) SHOW CREATE TABLE User;
In the last, it will be like this:
.....
.....
UNIQUE KEY UK_8bv559q1gobqoulqpitq0gvr6 (phoneNum)
.....
....
Step-2: Remove the Unique key by this query.
ALTER TABLE User DROP INDEX UK_8bv559q1gobqoulqpitq0gvr6;
Step-3: Check the table info, by this query:
DESC User;
This should show that the index is removed
Thats All.
ALTER TABLE 0_value_addition_setup DROP INDEX value_code
Try it to remove uique of a column:
ALTER TABLE `0_ms_labdip_details` DROP INDEX column_tcx
Run this code in phpmyadmin and remove unique of column
ALTER TABLE [table name] DROP KEY [key name];
this will work.