Can you please tell How to alter the table so that it can accept the not null constraint
alter table customer add emp_id int not null foreign key references emp(emp_id)
I have tried as above, but it is showing error:
Msg 4901, Level 16, State 1, Line 1
ALTER TABLE only allows columns to be added that can contain nulls, or have a DEFAULT definition specified, or the column being added is an identity or timestamp column,
or alternatively if none of the previous conditions are satisfied the table must be
empty to allow addition of this column. Column 'emp_id1' cannot be added to non-empty table 'customer' because it does not satisfy these conditions.
The error is pretty clear.
You are trying to add a non-null column to a table that has data. When you add the column, it has no value. So, the default value is put into the table for the existing rows. There is no default value, so NULL is used.
You can solve this in a few ways. One would be to empty the table truncate table customer, add the new column, then load the data again.
Another way would be to add the column with NULL allowed. Then fill in the value everywhere and then add the NOT NULL constraint.
Related
I tried to add primary key in a table and set it as a column that has default value and is not null and is not unique.MySQL accepted that column as Primary Key...I want to know that this is wrong as if a user enters 2 records having default values he will not be able to do so..Is this a problem where SQL should have checked column as non default values or this is a designer end problem that default columns should not be made Primary Key...?
I'm not fully understanding the problem. You have declared a column to be a primary key that has these characteristics:
NOT NULL
Default value
A primary key imposes these characteristics:
NOT NULL
Unique
These characteristics are not mutually incompatible. The only issue is that the default value can only be assigned once in the column. The second time you try to insert a row with the default value, you will get a violation of the uniqueness constraint.
In other words, MySQL (and I think other databases as well) allow you declare this even if it doesn't seem like a good idea.
Null:
every column that is flagged wiht NULL is just specified that this column may contain a NULL value. The column can still have another default value.
Primary key:
A PK is always treated unique and you cannot have two identical values on a row
There can only be one PK per table, its the main index which is very fast when querying the table on its primary column.
A PK is always a single column and cannot be spread over multiple columns as every other index (unique or usual index) can do.
A PK column cannot accept NULL values
Sample:
ID (INT, PK) | Name (varchar)
1 | Foo ->Valid
2 | Bar ->Valid
2 | FooBar ->Invalid (Duplicate Primary key value ID)
Conclusion: Yes MySQL should and will throw an error at second attempt to put a default value because its simply treated UNIQUE and a given default value is const. The MySQL server will attempt to insert the default value when you dont specify any value for this column in your insert statement.
Pretty much means: A PrimaryKey column with a default value makes no sense, except you use an auto-increment which is a pseudo "default value" which is different each time you try to insert something.
I hope this answers your questions
I have one table in my database in Cpanel server in which there are 17 columns currently,out of them,one is auto incremented field(which is a primary key).
currently in that table I have 600k rows.
I want to add a new column to table,but I'm getting the following error
1034-137 while fixing the table
Alter command I am using for adding the column
ALter table 'tablename' add 'columnname' Varchar(200) NOT NULL
Please help me what should i do to add the columns to the existing table
Because the new column does not allow NULL values, you will need to specify a default value for the column. All the existing rows in the table will be populated with the default value for the new column when you alter the table.
For example, to set the default value to empty string, you can use this statement.
alter table 'tablename' add 'columnname' Varchar(200) NOT NULL DEFAULT ''
Here is some documentation on using DEFAULT.
You can also drop the DEFAULT constraint after altering the table, so that future inserts into the table will fail if there is an attempt to insert a NULL value into that column,
After researching the error it seems that the indexing on your table may be having issues. Which tables are indexed other than your primary key?
In phpmyadmin select your table, then on the toolbar open Operations.
Under "Table maintenance" on the right hand side click the check table link to find out if there are any errors.
You may need to do some reindexing to correct the error.
This question already has answers here:
Unique constraint that allows empty values in MySQL
(3 answers)
Closed 9 years ago.
I have an existing mysql table, and I want to set one field (varchar) so that it must either be unique, or empty (by default). So when user does not enter value, its empty, otherwise user must enter unique value.
how would I do that ?
MySQL includes a constraint type UNIQUE that allows for exactly this. If you declare a column UNIQUE and allow NULL values in it, then all values will be forced to be unique unless they are NULL values. If you want to prevent empty strings ('') from being stored, you will have to manage that at the code level, because MySQL will treat it as just another string and allow it once in a UNIQUE column. If no value is passed to such a column, it will automatically default to NULL, but you can also specify NULL (not in quotes) programmatically in your code before passing the values to the database.
For the rest of this post I will assume the name of the table is tablename and the name of the column is columnname and the size of the varchar field is 255
If you want to modify an existing table, rather than create a new one:
If the column does not already support null values:
ALTER TABLE tablename ALTER COLUMN columnname VARCHAR(255) NULL
To add the unique constraint:
ALTER TABLE tablename ADD CONSTRAINT un_tablename_column UNIQUE (columnname)`
(I always name my constraints so I can refer to them specifically later)
OR if you want to do it on a new table:
CREATE TABLE tablename (
[...]
columnname varchar(255) UNIQUE NULL,
[...]
)
From what I have read, by standard it should not be possible to have a column in a table that allowes null values AND has a unique constraint; if it is, it is down to a special mysql-engine (that will result in unpredictable/unexpected behavior elsewhere also imho)
Also your question seems kind of reverse of this one
MySQL: UNIQUE, but DEFAULT NULL - allowed by creating of table. More than 1 NULL is allowed to insert. Why?
You could however enforce this using triggers, you can write a trigger on insert/update to check if the value already exists and immediatly delete it if it does.
I think you better process your data before pass to mysql, or not, you can write a trigger trigger whenever your table is update to make sure it pass your rule
I have a database of sql server 2008 which I am using to display in a gridview. I have written some code to add new rows in asp.net and C# as Code behind.
When ever a row is added through the Programming I have put some checking which will not allow the required values to be Null.
But, here comes my problem when ever any one of the user adds a new row manually by opening the Database, then a blank value is allowing in the Primary key column which is not 'Null value'.
So, here I have to restrict even not to allow blank values in primary key column, how can I solve this problem.
You need a check constraint
ALTER TABLE [TableName]
ADD CONSTRAINT [CK_PrimaryKeyNotEmpty]
CHECK
(
LEN([ColumnName]) > 0
)
I'm having trouble figuring out what you actual question is.
1) If you need to make a column not accept null values:
Add a constraint to the column in the db:
ALTER TABLE [Table] ALTER COLUMN [Column] INTEGER NOT NULL
See: Altering a column: null to not null
2) If you need to restrict your PK column to only certain values add a constraint:
ALTER TABLE Table
ADD CONSTRAINT CK_Table_Column_Range CHECK (
Column >= 0
)
I have a column in one of my tables. It's optional, so it can be left blank. However, if a value is provided for that column, it must be unique. Two questions:
How do I implement this in my database design (I'm using MySQL Workbench, by the way)
Is there a potential problem with my model?
Just use a UNIQUE index on the column. See:
http://dev.mysql.com/doc/refman/5.1/en/create-index.html
A UNIQUE index creates a constraint
such that all values in the index must
be distinct. An error occurs if you
try to add a new row with a key value
that matches an existing row. For all
engines, a UNIQUE index permits
multiple NULL values for columns that
can contain NULL. If you specify a
prefix value for a column in a UNIQUE
index, the column values must be
unique within the prefix.
It's can be null (and not blank) and unique. By default value can be null. There is no problem for me.
You can create a UNIQUE index on a table. In MySQL workbench that is the UQ checkbox when creating/editing the table.
Step 1, ALTER the table and MODIFY the field so NULLs are allowed.
ALTER TABLE my_table MODIFY my_field VARCHAR(100) NULL DEFAULT NULL;
Step 2, add a UNIQUE index on the field.
ALTER TABLE my_table ADD UNIQUE INDEX U_my_field (my_field);
It's fine to use -- my only hesitation with putting a UNIQUE index on a nullable field it that it is slightly counter-intuitive at first glance.
1) Move the column to a new table, make it unique and non-nullable. You can now have a row in this new table only when you have a value for it.
2) Yes. Keys and dependencies on keys are the basis of data integrity in a relational database design. If an attribute is supposed to be unique then it should be implemented as a key. A nullable "key" is not a key at all and anyway is never necessary because it can always be moved to a new table and made non-nullable without loss of any information.