Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add CHECK constraint to already populated table

I created a table called test with column called code:

create table test(  
code char(3) not null);

I then populated the table with the following data:

insert into test values ('A12');
insert into test values ('B23');
insert into test values ('C45');

I then altered the column to make it char(4):

alter table test
alter column code char(4) not null;

I then added a 'X' to all existing data so that it becomes 4 characters long:

update test
  set code='X'+code
where LEN(code)=3;

So far so good but then when I tried to add a check constraint:

alter table test
add constraint codeCheck check (code like 'A-Z''A-Z''0-9''0-9');

I got this error:

The ALTER TABLE statement conflicted with the CHECK constraint "codeCheck".

I understand that the error implies that the existing data violates the check constraint that I am trying to add into the table, but why?

and how do I do it such that the existing data and check constraint do not violate each other?

like image 971
j_t_fusion Avatar asked Sep 27 '12 12:09

j_t_fusion


People also ask

Can you add a constraint on table that has already some data?

The ADD CONSTRAINT command is used to create a constraint after a table is already created.

How do I add a check constraint in Oracle after creating table?

The syntax for creating a check constraint in an ALTER TABLE statement in Oracle is: ALTER TABLE table_name ADD CONSTRAINT constraint_name CHECK (column_name condition) [DISABLE]; The DISABLE keyword is optional.

Can I add a primary key constraint to an existing table with data?

Because a table can have only one primary key, you cannot add a primary key to a table that already has a primary key defined. To change the primary key of a table, delete the existing key using a DROP clause in an ALTER TABLE statement and add the new primary key.

What will happen if you are trying to add a check constraint to a table?

The CHECK constraint is used to limit the value range that can be placed in a column. If you define a CHECK constraint on a column it will allow only certain values for this column. If you define a CHECK constraint on a table it can limit the values in certain columns based on values in other columns in the row.


2 Answers

Your pattern syntax is wrong. It should be

alter table test
add constraint codeCheck check (code like '[A-Z][A-Z][0-9][0-9]');
like image 153
Martin Smith Avatar answered Nov 15 '22 21:11

Martin Smith


Because your data doesn't match the like constraint.

Try

alter table test
     add constraint codeCheck check (code like '[A-Z][A-Z][0-9][0-9]' );
like image 25
podiluska Avatar answered Nov 15 '22 20:11

podiluska