Add a field in a table and check condition with another column - mysql

I need to add a field – DOC with Date type to the Registration table also ensure DOC greater than DOJ.I tried this
ALTER TABLE Registration
ADD DOC date
CHECK (DOC>DOJ);
It shows error.Where i went wrong?

Firstly, prior to MySQL version 8.0.16, MySQL permitted only a very limited version of table CHECK constraint syntax, which was parsed and ignored. So if your MySQL version < 8.0.16, then your ALTER TABLE statement would not fulfill any purpose; and possibly the reason of syntax error as well.
Now, if your version is indeed correct; then you are defining Table Constraint incorrectly. As per Documentation:
A CHECK constraint is specified as either a table constraint or column
constraint:
A table constraint does not appear within a column definition and can refer to any table column or columns. Forward references are
permitted to columns appearing later in the table definition.
A column constraint appears within a column definition and can refer only to that column.
Since your CHECK constraint involves more than one column, it is a Table constraint. Also, ALTER TABLE syntax to add a new CHECK constraint is as follows:
ALTER TABLE tbl_name
ADD CONSTRAINT [symbol] CHECK (expr) [[NOT] ENFORCED];
Try the following instead:
ALTER TABLE Registration
ADD DOC date,
ADD CONSTRAINT chk_doc_greater_doj CHECK (DOC>DOJ);

ALTER TABLE REGISTRATION
ADD DOC DATE
ADD CONSTRAINT DATE_OF_COMPLETION CHECK(DOC>DOJ);

Hey I encountered same problem, I solved it by writing in two seperate queries
ALTER TABLE Registration ADD DOC date;
ALTER TABLE Registration ADD CONSTRAINT check_date CHECK (DOC>DOJ);

Related

Update an already existing field MYSQL

I was just wondering, how do you modify an already existing field from the command line in my sql. I have a foreign key which is appearing as MUL for some reason, and I want to try and reference it to a primary key of another. I had originally tried to do this from MYSQL Workbench and thus I think I have done something wrong.
Have a look at the alter table syntax. You will probably need
alter table ... drop index
alter table ... add foreign key ...
http://dev.mysql.com/doc/refman/5.1/en/alter-table.html

Adding foreign key to existing table gives error 1050 table already exists

I've a table CustomizationSet with the columns:
customization_set_guid (which is a non-nullable guid and also the primary key)
creator_account_guid
and a few others
And a table with existing data Registration with the columns:
registration_id (an int and the primary key)
customization_set_guid (also a guid (so a char(36)) which is nullable, and all entries are currently null)
and a few other columns
When I try and run
ALTER TABLE Registration ADD FOREIGN KEY
(
customization_set_guid
) REFERENCES CustomizationSet (
customization_set_guid
);
in MySQL Workbench, it gives the error 1050Table '.\dbname\registration' already exists.
If I try to use the UI to add the foreign keys with the Foreign Keys tab of the Alter Table Dialog, and choose CustomizationSet as the referenced table, it doesn't let me choose customization_set_guid in the list of columns.
I'm really not sure why it won't let me add this foreign key. I've just successfully created foreign keys between tables I just added. The Registration table has existed for awhile...
I got the same error, and it was due to the fact that the foreign key already existed. What you want is just to add the constraint:
ALTER TABLE Registration
ADD CONSTRAINT idx_Registration_CustomizationSet
FOREIGN KEY (customization_set_guid)
REFERENCES CustomizationSet(customization_set_guid);
It looks like there is a bug report for this at MySQL located here:
MySQL Bug 55296
In the end, I guess they upgraded their server and it fixed the issue. From reading it, I'm not sure though. They did have some workarounds like putting in constraint names/changing them. If you think this is the same, I would request that the bug is reopened.
At one point, they mention the types didn't match and workbench was responding with the wrong error (it should have been an errno 150, or errno 121). You can see the causes for those errors here:
MySQL Foreign Key Errors and Errno 150
So a team member figured this out. The one table was set with the type utf8_general, and another was set to the type default. I didn't think this was an issue, since the default is utf8_general, but apparently mysql just looks at the type names and not the underlying type.
I got the same error, and since my case wasnt mentioned yet, i ll post this answer and hopefully it may save somebody's time!
My two tables engines, where different.
The one was InnoDB, and the other MyIsam.
To change the engine of a table:
choose table, hit alter table, and then to hit that double arrow at
the right-most of the Workbench(so it will point upwards).
Now change the engine!
Check the Storage Engine type for CustomizationSet table.
I had a same issue but i could solve it by changing engine type to
InnoDB , because few types don't support foreign key constraints.
Not sure about the table already existing, but the reason it's not letting you choose the column you want is most likely due to the columns not being the same type. Check to ensure they are both the same type, same length, and have all the same options.
I'm not sure if it's a typo but shouldn't be
ALTER TABLE Registration ADD FOREIGN KEY
(
customization_set_guid
) REFERENCES CustomizationSet (
customization_set_guid
);
be something like
ALTER TABLE Registration ADD FOREIGN KEY
customization_set_guid_fk (customization_set_guid)
REFERENCES CustomizationSet (customization_set_guid);
I had a similar problem and in the end it was a problem of Integrity Constraint.
The Foreign Key column was referencing a foreign column that didnt
exist.
Try run the following to test whether this is the case:
select r.customization_set_guid, c.customization_set_guid
from Registration r
right join CustomizationSet c
on
r.customization_set_guid = c.customization_set_guid
where isnull(c.customization_set_guid);
When using MysqlWorkbench the error is misleading. My issue was that I was trying to add a foreign key constraint on table that already had rows and one of the rows was empty (did not meet the FK constraint. Instead of complaining that constraint will fail if applied, MysqlWorkbench reported that table exists.
Removing the offending row fixed (or adding and constraint acceptable value to the field) solved the problem.

Alter a live table to make a key non-unique

I saw some other questions related to this, but they were not MySQL.
The database is a live database, so I don't want to delete and recreate the table. I simply want to make a column no longer unique, which is less permissive in nature so it shouldn't cause any problems.
If your column was defined unique using UNIQUE clause, then use:
ALTER TABLE mytable DROP INDEX constraint_name
, or, if your constraint was implicitly named,
ALTER TABLE mytable DROP INDEX column_name
If it was defined unique using PRIMARY KEY clause, use:
ALTER TABLE mytable DROP PRIMARY KEY
Note, however, that if your table is InnoDB, dropping PRIMARY KEY will result in implicit recreation of your table and rebuilding all indexes, which will lock the table and may make it inaccessible for quite a long time.
These are instructions for phpmyadmin app (if you are using phpMyAdmin) ::
In a some cases, the developer (you) may not want to drop it but rather just modify the "uniqueness" to "not-unique".
Steps :
Go to the table in context, where you want to make the modification
Click on the "Structure" tab (mostly next to Browse)
Look for the "+Indexes" link, just under the columns. Yeah... now click it
Now you can see all the "Indexes" and you can now click on the "DROP" button or link to modify.
Answer was found here :
Source : https://forums.phpfreaks.com/topic/164827-phpmyadmin-how-to-make-not-unique/
Just DROP the unique index. There shouldn't be a problem with the fact that it is a live DB. If it is a really large table, you may block some queries temporarily while the index is removed. But that should only happen if you were adding an index.
ALTER TABLE table_name DROP INDEX index_name;
Although the accepted answer is incorrect (see comments), the suggested workaround is possible. But it is not correct too, at least for a "live table", as asked.
To lower the impact you should create a new index at first, and then delete the old one:
ALTER TABLE mytable ADD INDEX idx_new (column);
ALTER TABLE mytable DROP INDEX idx_old;
This avoids using the table (column) without index at all, which can be quite painful for clients and the MySQL itself.
MySQL requires indexes on foreign keys and referenced keys so that foreign key checks can be fast (MySQL Manual).
If the unique key that you want to make non-unique is used by a foreign key constraint, then you'll get an error when dropping it. You will have to recreate it on the same line:
alter table mytable drop KEY myUniqueKey, add key myUniqueKey (myColumn);

"please select equal number of source and reference" on sqlyog

I am trying to add a foreign key constraint via sqlyog, and getting this error, although I am only select one source and one reference columns
please select equal number of source
and reference
Does anyone knows what it means in this case? Note that I do have an equal number of source and reference columns...
I came across the same issue with SQLYog v9.01. The error message is misleading and the real cause of an error can be totally different.
Things I checked to solve this are the following:
Check table engyne types, should be both InnoDb
Check if your target table is not the same as source.
Check datatypes, length and charset collation of referenced fields.
If you already have data in your tables check its consistency.
For example, you should remove all unrelated data from table B which relates to table A
DELETE target FROM B AS target LEFT JOIN A USING(id_A) WHERE A.id_A IS NULL
Finally ones in my case I had to FLUSH tables to create my constraints successfully.
Manual constraint creation from Query window can give you more information on your error type.
Just a reminder:
ALTER TABLE `B` ADD CONSTRAINT `FK_B` FOREIGN KEY (`id_A`) REFERENCES `A` (`id_A`) ON DELETE CASCADE ;
Good luck!

What does mysql error 1025 (HY000): Error on rename of './foo' (errorno: 150) mean?

I tried this in mysql:
mysql> alter table region drop column country_id;
And got this:
ERROR 1025 (HY000): Error on rename of './product/#sql-14ae_81' to
'./product/region' (errno: 150)
Any ideas? Foreign key stuff?
You usually get this error if your tables use the InnoDB engine. In that case you would have to drop the foreign key, and then do the alter table and drop the column.
But the tricky part is that you can't drop the foreign key using the column name, but instead you would have to find the name used to index it. To find that, issue the following select:
SHOW CREATE TABLE region;
This should show you the name of the index, something like this:
CONSTRAINT region_ibfk_1 FOREIGN
KEY (country_id) REFERENCES
country (id) ON DELETE NO
ACTION ON UPDATE NO ACTION
Now simply issue an:
alter table region drop foreign key
region_ibfk_1;
And finally an:
alter table region drop column
country_id;
And you are good to go!
It is indeed a foreign key error, you can find out using perror:
shell$ perror 150
MySQL error code 150: Foreign key constraint is incorrectly formed
To find out more details about what failed, you can use SHOW ENGINE INNODB STATUS and look for the LATEST FOREIGN KEY ERROR section it contains details about what is wrong.
In your case, it is most likely cause something is referencing the country_id column.
You can get also get this error trying to drop a non-existing foreign key. So when dropping foreign keys, always make sure they actually exist.
If the foreign key does exist, and you are still getting this error try the following:
SET #OLD_UNIQUE_CHECKS=##UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET #OLD_FOREIGN_KEY_CHECKS=##FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET #OLD_SQL_MODE=##SQL_MODE, SQL_MODE='TRADITIONAL';
// Drop the foreign key here!
SET SQL_MODE=#OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=#OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=#OLD_UNIQUE_CHECKS;
This always does the trick for me :)
Simply run the alter table query using 'KEY' instead of 'FOREIGN KEY' in the drop statement. I hope it will help to solve the issue, and will drop the foreign key constraint and you can change the table columns and drop the table.
ALTER TABLE slide_image_sub DROP KEY FK_slide_image_sub;
here in DROP KEY instead of DROP FOREIGN KEY,
hope it will help.
Thanks
I know, this is an old post, but it's the first hit on everyone's favorite search engine if you are looking for error 1025.
However, there is an easy "hack" for fixing this issue:
Before you execute your command(s) you first have to disable the foreign key constraints check using this command:
SET FOREIGN_KEY_CHECKS = 0;
Then you are able to execute your command(s).
After you are done, don't forget to enable the foreign key constraints check again, using this command:
SET FOREIGN_KEY_CHECKS = 1;
Good luck with your endeavor.
I had a similar issues once. I deleted the primary key from TABLE A but when I was trying to delete the foreign key column from table B I was shown the above same error.
You can't drop the foreign key using the column name and to bypass this in PHPMyAdmin or with MySQL, first remove the foreign key constraint before renaming or deleting the attribute.
Take a look in error file for your mysql database. According to Bug #26305 my sql do not give you the cause. This bug exists since MySQL 4.1 ;-)
If you are using a client like MySQL Workbench, right click the desired table from where a foreign key is to be deleted, then select the foreign key tab and delete the indexes.
Then you can run the query like this:
alter table table_name drop foreign_key_col_name;
There is probably another table with a foreign key referencing the primary key you are trying to change.
To find out which table caused the error you can run SHOW ENGINE INNODB STATUS and then look at the LATEST FOREIGN KEY ERROR section
Use SHOW CREATE TABLE categories to show the name of constraint.
Most probably it will be categories_ibfk_1
Use the name to drop the foreign key first and the column then:
ALTER TABLE categories DROP FOREIGN KEY categories_ibfk_1;
ALTER TABLE categories DROP COLUMN assets_id;
I got this error with MySQL 5.6 but it had nothing to do with Foreign keys. This was on a Windows 7 Professional machine acting as a server on a small LAN.
The client application was doing a batch operation that creates a table fills it with some external data then runs a query joining with permanent tables then dropping the "temporary" table. This batch does this approximately 300 times and this particular routine had been running week in week out for several years when suddenly we get the Error 1025 Unable to rename problem at a random point in the batch.
In my case the application was using 4 DDL statements a CREATE TABLE followed by 3 CREATE INDEX, there is no foreign key. However only 2 of the indexes actually get created and the actual table .frm file was renamed, at the point of failure.
My solution was to get rid of the separate CREATE INDEX statements and create them using the CREATE TABLE statement. This at the time of writing has solved the issue for me and my help someone else scratching their head when they find this thread.
I'd guess foreign key constraint problem. Is country_id used as a foreign key in another table?
I'm not DB guru but I think I solved a problem like this (where there was a fk constraint) by removing the fk, doing my alter table stuff and then redoing the fk stuff.
I'll be interested to hear what the outcome is - sometime mysql is pretty cryptic.
In my case, I was using MySQL workbench and I faced the same issue while dropping one of my columns in a table. I could not find the name of the foreign key. I followed the following steps to resolve the issue:
Rt. click on your schema and select 'schema inspector'. This gives you various tables, columns, indexes, ect.
Go to the tab named 'Indexes' and search the name of the column under the column named 'Column'. Once found check the name of the table for this record under the column name 'Table'. If it matches the name of the table you want, then note down the name of the foreign key from the column named 'Name'.
Now execute the query : ALTER table tableNamexx DROP KEY foreignKeyName;
Now you can execute the drop statement which shall execute successfully.
Doing
SET FOREIGN_KEY_CHECKS=0;
before the Operation can also do the trick.
averageRatings= FOREACH groupedRatings GENERATE group AS movieID, AVG(ratings.rating) AS avgRating, COUNT(ratings.rating) AS numRatings;
If you are using any command like above you must use group in small letters. This may solve your problem it solved mine. At least in PIG script.